(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&i(n)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();class wi{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const 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=[];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}}wi._BabylonFileParsers={};wi._IndividualBabylonFileParsers={};class vr{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in vr.Triggers)if(Object.prototype.hasOwnProperty.call(vr.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in vr.Triggers)if(Object.prototype.hasOwnProperty.call(vr.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in vr.Triggers)if(Object.prototype.hasOwnProperty.call(vr.Triggers,t)&&parseInt(t)===e)return!0;return!1}}vr.Triggers={};class aE{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class qC{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class G{static FromPromise(e,t){const i=new G;return e.then(s=>{i.notifyObservers(s)}).catch(s=>{if(t)t.notifyObservers(s);else throw s}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new aE(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new qC(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){const s=this._observers[i];if(!s._willBeUnregistered&&s.callback===e&&(!t||t===s.scope))return this._deferUnregister(s),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?n.lastReturnValue=o.callback.apply(o.scope,[e,n]):n.lastReturnValue=o.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new G;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const Kc=1/2.2,Ud=2.2,rt=.001;class Xi{static BuildArray(e,t){const i=[];for(let s=0;s<e;++s)i.push(t());return i}static BuildTuple(e,t){return Xi.BuildArray(e,t)}}function QC(a,e,t){const i=a[e];if(typeof i!="function")return null;const s=function(){const r=a.length,n=s.previous.apply(a,arguments);return t(e,r),n};return i.next=s,s.previous=i,a[e]=s,()=>{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,a[e]=r),s.next=void 0,s.previous=void 0}}const ZC=["push","splice","pop","shift","unshift"];function oE(a,e){const t=ZC.map(i=>QC(a,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const lE={};function V(a,e){lE[a]=e}function Si(a){return lE[a]}class gs{static SetMatrixPrecision(e){if(gs.MatrixTrackPrecisionChange=!1,e&&!gs.MatrixUse64Bits&&gs.MatrixTrackedMatrices)for(let t=0;t<gs.MatrixTrackedMatrices.length;++t){const i=gs.MatrixTrackedMatrices[t],s=i._m;i._m=new Array(16);for(let r=0;r<16;++r)i._m[r]=s[r]}gs.MatrixUse64Bits=e,gs.MatrixCurrentType=gs.MatrixUse64Bits?Array:Float32Array,gs.MatrixTrackedMatrices=null}}gs.MatrixUse64Bits=!1;gs.MatrixTrackPrecisionChange=!0;gs.MatrixCurrentType=Float32Array;gs.MatrixTrackedMatrices=[];class Ae{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}Ae.Instances=[];Ae.OnEnginesDisposedObservable=new G;Ae._LastCreatedScene=null;Ae.UseFallbackTexture=!0;Ae.FallbackTexture="";function Ms(a,e,t=1401298e-51){return Math.abs(a-e)<=t}function Pt(a,e){return a===e?a:Math.random()*(e-a)+a}function _r(a,e,t){return a+(e-a)*t}function xi(a,e=0,t=1){return Math.min(t,Math.max(e,a))}function hE(a){return a-=Math.PI*2*Math.floor((a+Math.PI)/(Math.PI*2)),a}function dn(a){const e=a.toString(16);return a<=15?("0"+e).toUpperCase():e.toUpperCase()}const ar=a=>parseInt(a.toString().replace(/\W/g,""));class Z{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){const e=ar(this.x),t=ar(this.y);let i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return Z.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new this.constructor(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.copyFromFloats(this.x-e,this.y-t)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=rt){return e&&Ms(this.x,e.x,t)&&Ms(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new Z(0,0)}static One(){return new Z(1,1)}static Random(e=0,t=1){return new Z(Pt(e,t),Pt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Pt(e,t),Pt(e,t))}static get ZeroReadOnly(){return Z._ZeroReadOnly}static FromArray(e,t=0){return new Z(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,l=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),h=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(l,h)}static ClampToRef(e,t,i,s){return s.x=xi(e.x,t.x,i.x),s.y=xi(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=xi(e.x,t.x,i.x),r=xi(e.y,t.y,i.y);return new e.constructor(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.x*l+i.x*h+t.x*c+s.x*u,f=e.y*l+i.y*h+t.y*c+s.y*u;return new e.constructor(d,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=(o-r)*6*e.x+(3*o-4*r+1)*t.x+(-o+r)*6*i.x+(3*o-2*r)*s.x,n.y=(o-r)*6*e.y+(3*o-4*r+1)*t.y+(-o+r)*6*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new e.constructor(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return Z.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.x<t.x?e.x:t.x,s=e.y<t.y?e.y:t.y;return new e.constructor(i,s)}static Maximize(e,t){const i=e.x>t.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new e.constructor(i,s)}static Transform(e,t){const i=new e.constructor;return Z.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&l>0&&o+l<2*r*n}static Distance(e,t){return Math.sqrt(Z.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){const i=new e.constructor;return Z.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=Z.DistanceSquared(t,i);if(s===0)return Z.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,Z.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return Z.Distance(e,o)}}Z._ZeroReadOnly=Z.Zero();Object.defineProperties(Z.prototype,{dimension:{value:[2]},rank:{value:1}});class m{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){const e=ar(this._x),t=ar(this._y),i=ar(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return m.FromArrayToRef(e,t,this),this}toQuaternion(){return Q.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(this._x*-1,this._y*-1,this._z*-1)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,l=e._z,h=e._w,c=2*(o*r-l*s),u=2*(l*i-n*r),d=2*(n*s-o*i);return t._x=i+h*c+o*d-l*u,t._y=s+h*u+l*c-n*d,t._z=r+h*d+n*u-o*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=Oe.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=m.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const l=-(m.Dot(t,s)+r)/o,h=n.scaleInPlace(l);t.addToRef(h,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=rt){return e&&Ms(this._x,e._x,t)&&Ms(this._y,e._y,t)&&Ms(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!Ms(t,i,e))return!0;const s=Math.abs(this._z);return!Ms(t,s,e)||!Ms(i,s,e)}get isNonUniform(){const e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;const i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new this.constructor(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=Oe.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Oe.Matrix[0]),m.TransformCoordinatesToRef(this,Oe.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,Oe.Vector3[0]),Oe.Vector3[0].rotateByQuaternionToRef(e,Oe.Vector3[0]),t.addToRef(Oe.Vector3[0],i),i}cross(e){const t=new this.constructor;return m.CrossToRef(this,e,t)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=m.Dot(e,i),n=m.Dot(t,i);return(r-s)/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(Oe.Vector3[1]),r=t.normalizeToRef(Oe.Vector3[2]);let n=m.Dot(s,r);n=xi(n,-1,1);const o=Math.acos(n),l=Oe.Vector3[3];return m.CrossToRef(s,r,l),m.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){Oe.Vector3[0].copyFrom(e);const s=Oe.Vector3[0];Oe.Vector3[1].copyFrom(t);const r=Oe.Vector3[1];Oe.Vector3[2].copyFrom(i);const n=Oe.Vector3[2],o=Oe.Vector3[3],l=Oe.Vector3[4];s.normalize(),r.normalize(),n.normalize(),m.CrossToRef(n,s,o),m.CrossToRef(o,n,l);const h=Math.atan2(m.Dot(r,o),m.Dot(r,l));return hE(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=U.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=m.Zero();return m.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=xi(i,0,1);const r=Oe.Vector3[0],n=Oe.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const l=n.length();n.normalizeFromLength(l);const h=m.Dot(r,n);let c,u;if(h<1-rt){const d=Math.acos(h),f=1/Math.sin(d);c=Math.sin((1-i)*d)*f,u=Math.sin(i*d)*f}else c=1-i,u=i;return r.scaleInPlace(c),n.scaleInPlace(u),s.copyFrom(r).addInPlace(n),s.scaleInPlace(_r(o,l,i)),s}static SmoothToRef(e,t,i,s,r){return m.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new m(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return m.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return m.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new m(0,0,0)}static One(){return new m(1,1,1)}static Up(){return new m(0,1,0)}static get UpReadOnly(){return m._UpReadOnly}static get DownReadOnly(){return m._DownReadOnly}static get RightReadOnly(){return m._RightReadOnly}static get LeftReadOnly(){return m._LeftReadOnly}static get LeftHandedForwardReadOnly(){return m._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return m._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return m._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return m._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return m._ZeroReadOnly}static get OneReadOnly(){return m._OneReadOnly}static Down(){return new m(0,-1,0)}static Forward(e=!1){return new m(0,0,e?-1:1)}static Backward(e=!1){return new m(0,0,e?1:-1)}static Right(){return new m(1,0,0)}static Left(){return new m(-1,0,0)}static Random(e=0,t=1){return new m(Pt(e,t),Pt(e,t),Pt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Pt(e,t),Pt(e,t),Pt(e,t))}static TransformCoordinates(e,t){const i=m.Zero();return m.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return m.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],c=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*c,r._y=l*c,r._z=h*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=m.Zero();return m.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,l=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),h=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),c=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(l,h,c)}static Clamp(e,t,i){const s=new e.constructor;return m.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=r<t._x?t._x:r;let n=e._y;n=n>i._y?i._y:n,n=n<t._y?t._y:n;let o=e._z;return o=o>i._z?i._z:o,o=o<t._z?t._z:o,s.copyFromFloats(r,n,o),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e._x*l+i._x*h+t._x*c+s._x*u,f=e._y*l+i._y*h+t._y*c+s._y*u,_=e._z*l+i._z*h+t._z*c+s._z*u;return new e.constructor(d,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=(o-r)*6*e._x+(3*o-4*r+1)*t._x+(-o+r)*6*i._x+(3*o-2*r)*s._x,n._y=(o-r)*6*e._y+(3*o-4*r+1)*t._y+(-o+r)*6*i._y+(3*o-2*r)*s._y,n._z=(o-r)*6*e._z+(3*o-4*r+1)*t._z+(-o+r)*6*i._z+(3*o-2*r)*s._z,n._isDirty=!0,n}static Lerp(e,t,i){const s=new e.constructor(0,0,0);return m.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){return s._x=e._x+(t._x-e._x)*i,s._y=e._y+(t._y-e._y)*i,s._z=e._z+(t._z-e._z)*i,s._isDirty=!0,s}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){const i=new e.constructor;return m.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){const s=e._y*t._z-e._z*t._y,r=e._z*t._x-e._x*t._z,n=e._x*t._y-e._y*t._x;return i.copyFromFloats(s,r,n),i}static Normalize(e){const t=m.Zero();return m.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,s){const r=new e.constructor;return m.ProjectToRef(e,t,i,s,r),r}static ProjectToRef(e,t,i,s,r){const n=s.width,o=s.height,l=s.x,h=s.y,c=Oe.Matrix[1];D.FromValuesToRef(n/2,0,0,0,0,-o/2,0,0,0,0,.5,0,l+n/2,o/2+h,.5,1,c);const u=Oe.Matrix[0];return t.multiplyToRef(i,u),u.multiplyToRef(c,u),m.TransformCoordinatesToRef(e,u,r),r}static Reflect(e,t){return this.ReflectToRef(e,t,new m)}static ReflectToRef(e,t,i){const s=U.Vector3[0];return s.copyFrom(t).scaleInPlace(2*m.Dot(e,t)),i.copyFrom(e).subtractInPlace(s)}static _UnprojectFromInvertedMatrixToRef(e,t,i){m.TransformCoordinatesToRef(e,t,i);const s=t.m,r=e._x*s[3]+e._y*s[7]+e._z*s[11]+s[15];return Ms(r,1)&&i.scaleInPlace(1/r),i}static UnprojectFromTransform(e,t,i,s,r){return this.Unproject(e,t,i,s,r,D.IdentityReadOnly)}static Unproject(e,t,i,s,r,n){const o=new e.constructor;return m.UnprojectToRef(e,t,i,s,r,n,o),o}static UnprojectToRef(e,t,i,s,r,n,o){return m.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,s,r,n,o),o}static UnprojectFloatsToRef(e,t,i,s,r,n,o,l,h){var d;const c=Oe.Matrix[0];n.multiplyToRef(o,c),c.multiplyToRef(l,c),c.invert();const u=Oe.Vector3[0];return u.x=e/s*2-1,u.y=-(t/r*2-1),(d=Ae.LastCreatedEngine)!=null&&d.isNDCHalfZRange?u.z=i:u.z=2*i-1,m._UnprojectFromInvertedMatrixToRef(u,c,h),h}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(m.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e._x-t._x,s=e._y-t._y,r=e._z-t._z;return i*i+s*s+r*r}static ProjectOnTriangleToRef(e,t,i,s,r){const n=Oe.Vector3[0],o=Oe.Vector3[1],l=Oe.Vector3[2],h=Oe.Vector3[3],c=Oe.Vector3[4];i.subtractToRef(t,n),s.subtractToRef(t,o),s.subtractToRef(i,l);const u=n.length(),d=o.length(),f=l.length();if(u<rt||d<rt||f<rt)return r.copyFrom(t),m.Distance(e,t);e.subtractToRef(t,c),m.CrossToRef(n,o,h);const _=h.length();if(_<rt)return r.copyFrom(t),m.Distance(e,t);h.normalizeFromLength(_);let p=c.length();if(p<rt)return r.copyFrom(t),0;c.normalizeFromLength(p);const g=m.Dot(h,c),x=Oe.Vector3[5],T=Oe.Vector3[6];x.copyFrom(h).scaleInPlace(-p*g),T.copyFrom(e).addInPlace(x);const S=Oe.Vector3[4],C=Oe.Vector3[5],v=Oe.Vector3[7],b=Oe.Vector3[8];S.copyFrom(n).scaleInPlace(1/u),b.copyFrom(o).scaleInPlace(1/d),S.addInPlace(b).scaleInPlace(-1),C.copyFrom(n).scaleInPlace(-1/u),b.copyFrom(l).scaleInPlace(1/f),C.addInPlace(b).scaleInPlace(-1),v.copyFrom(l).scaleInPlace(-1/f),b.copyFrom(o).scaleInPlace(-1/d),v.addInPlace(b).scaleInPlace(-1);const A=Oe.Vector3[9];let P;A.copyFrom(T).subtractInPlace(t),m.CrossToRef(S,A,b),P=m.Dot(b,h);const L=P;A.copyFrom(T).subtractInPlace(i),m.CrossToRef(C,A,b),P=m.Dot(b,h);const w=P;A.copyFrom(T).subtractInPlace(s),m.CrossToRef(v,A,b),P=m.Dot(b,h);const $=P,J=Oe.Vector3[10];let ne,oe;L>0&&w<0?(J.copyFrom(n),ne=t,oe=i):w>0&&$<0?(J.copyFrom(l),ne=i,oe=s):(J.copyFrom(o).scaleInPlace(-1),ne=s,oe=t);const re=Oe.Vector3[9],ce=Oe.Vector3[4];if(ne.subtractToRef(T,b),oe.subtractToRef(T,re),m.CrossToRef(b,re,ce),!(m.Dot(ce,h)<0))return r.copyFrom(T),Math.abs(p*g);const Ce=Oe.Vector3[5];m.CrossToRef(J,ce,Ce),Ce.normalize();const ae=Oe.Vector3[9];ae.copyFrom(ne).subtractInPlace(T);const ie=ae.length();if(ie<rt)return r.copyFrom(ne),m.Distance(e,ne);ae.normalizeFromLength(ie);const F=m.Dot(Ce,ae),j=Oe.Vector3[7];j.copyFrom(T).addInPlace(Ce.scaleInPlace(ie*F)),b.copyFrom(j).subtractInPlace(ne),p=J.length(),J.normalizeFromLength(p);let se=m.Dot(b,J)/Math.max(p,rt);return se=xi(se,0,1),j.copyFrom(ne).addInPlace(J.scaleInPlace(se*p)),r.copyFrom(j),m.Distance(e,j)}static Center(e,t){return m.CenterToRef(e,t,m.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){const s=new e.constructor;return m.RotationFromAxisToRef(e,t,i,s),s}static RotationFromAxisToRef(e,t,i,s){const r=Oe.Quaternion[0];return Q.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(s),s}}m._UpReadOnly=m.Up();m._DownReadOnly=m.Down();m._LeftHandedForwardReadOnly=m.Forward(!1);m._RightHandedForwardReadOnly=m.Forward(!0);m._LeftHandedBackwardReadOnly=m.Backward(!1);m._RightHandedBackwardReadOnly=m.Backward(!0);m._RightReadOnly=m.Right();m._LeftReadOnly=m.Left();m._ZeroReadOnly=m.Zero();m._OneReadOnly=m.One();Object.defineProperties(m.prototype,{dimension:{value:[3]},rank:{value:1}});class we{constructor(e=0,t=0,i=0,s=0){this.x=e,this.y=t,this.z=i,this.w=s}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){const e=ar(this.x),t=ar(this.y),i=ar(this.z),s=ar(this.w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){return[this.x,this.y,this.z,this.w]}toArray(e,t){return t===void 0&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this}fromArray(e,t=0){return we.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addInPlaceFromFloats(e,t,i,s){return this.x+=e,this.y+=t,this.z+=i,this.w+=s,this}add(e){return new this.constructor(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,t}subtractFromFloats(e,t,i,s){return new this.constructor(this.x-e,this.y-t,this.z-i,this.w-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,r.w=this.w-s,r}negate(){return new this.constructor(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1,this.z*-1,this.w*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e,this.z*e,this.w*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsWithEpsilon(e,t=rt){return e&&Ms(this.x,e.x,t)&&Ms(this.y,e.y,t)&&Ms(this.z,e.z,t)&&Ms(this.w,e.w,t)}equalsToFloats(e,t,i,s){return this.x===e&&this.y===t&&this.z===i&&this.w===s}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,t}multiplyByFloats(e,t,i,s){return new this.constructor(this.x*e,this.y*t,this.z*i,this.w*s)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}toVector3(){return new m(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new we(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return we.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new we(0,0,0,0)}static One(){return new we(1,1,1,1)}static Random(e=0,t=1){return new we(Pt(e,t),Pt(e,t),Pt(e,t),Pt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Pt(e,t),Pt(e,t),Pt(e,t),Pt(e,t))}static Clamp(e,t,i){const s=new e.constructor;return we.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(xi(e.x,t.x,i.x),xi(e.y,t.y,i.y),xi(e.z,t.z,i.z),xi(e.w,t.w,i.w))}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return we._ZeroReadOnly}static Normalize(e){const t=we.Zero();return we.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(we.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return we.CenterToRef(e,t,we.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){const i=we.Zero();return we.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return we.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],c=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=l,r.z=h,r.w=c,r}static TransformNormal(e,t){const i=new e.constructor;return we.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new we(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}we._ZeroReadOnly=we.Zero();Object.defineProperties(we.prototype,{dimension:{value:[4]},rank:{value:1}});class Q{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=ar(this._x),t=ar(this._y),i=ar(this._z),s=ar(this._w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return Q.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=rt){return e&&Ms(this._x,e._x,t)&&Ms(this._y,e._y,t)&&Ms(this._z,e._z,t)&&Ms(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new this.constructor)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=m.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=r*r,h=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*r),-h-c+u+l),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),h-c-u+l),e._isDirty=!0}return e}toRotationMatrix(e){return D.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return Q.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new Q;return Q.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],l=i[5],h=i[9],c=i[2],u=i[6],d=i[10],f=s+l+d;let _;return f>0?(_=.5/Math.sqrt(f+1),t._w=.25/_,t._x=(u-h)*_,t._y=(n-c)*_,t._z=(o-r)*_,t._isDirty=!0):s>l&&s>d?(_=2*Math.sqrt(1+s-l-d),t._w=(u-h)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+c)/_,t._isDirty=!0):l>d?(_=2*Math.sqrt(1+l-s-d),t._w=(n-c)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(h+u)/_,t._isDirty=!0):(_=2*Math.sqrt(1+d-s-l),t._w=(o-r)/_,t._x=(n+c)/_,t._y=(h+u)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=Q.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=xi(n,0,1),Q.SlerpToRef(e,t,n,r),r}static Zero(){return new Q(0,0,0,0)}static Inverse(e){return new e.constructor(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new Q(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return Q.RotationAxisToRef(e,t,new Q)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new Q(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new Q;return Q.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return Q.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new Q;return Q.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return Q.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=rt){const r=m.Dot(e,t)+1;return r<s?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(m.CrossToRef(e,t,U.Vector3[0]),i.set(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new Q;return Q.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,o=e*.5,l=Math.sin(r),h=Math.cos(r),c=Math.sin(n),u=Math.cos(n),d=Math.sin(o),f=Math.cos(o);return s._x=f*c*h+d*u*l,s._y=d*u*h-f*c*l,s._z=f*u*l-d*c*h,s._w=f*u*h+d*c*l,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new Q;return Q.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,o=t*.5;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new Q(0,0,0,0);return Q.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=Oe.Matrix[0];return D.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),Q.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new Q;return Q.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=Oe.Matrix[0];return D.LookDirectionLHToRef(e,t,s),Q.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new Q;return Q.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=Oe.Matrix[0];return D.LookDirectionRHToRef(e,t,s),Q.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=Q.Identity();return Q.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)n=1-i,r=l?-i:i;else{const h=Math.acos(o),c=1/Math.sin(h);n=Math.sin((1-i)*h)*c,r=l?-Math.sin(i*h)*c:Math.sin(i*h)*c}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e._x*l+i._x*h+t._x*c+s._x*u,f=e._y*l+i._y*h+t._y*c+s._y*u,_=e._z*l+i._z*h+t._z*c+s._z*u,p=e._w*l+i._w*h+t._w*c+s._w*u;return new e.constructor(d,f,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=(o-r)*6*e._x+(3*o-4*r+1)*t._x+(-o+r)*6*i._x+(3*o-2*r)*s._x,n._y=(o-r)*6*e._y+(3*o-4*r+1)*t._y+(-o+r)*6*i._y+(3*o-2*r)*s._y,n._z=(o-r)*6*e._z+(3*o-4*r+1)*t._z+(-o+r)*6*i._z+(3*o-2*r)*s._z,n._w=(o-r)*6*e._w+(3*o-4*r+1)*t._w+(-o+r)*6*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=Q.Zero();return Q.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new e.constructor;return Q.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(xi(e.x,t.x,i.x),xi(e.y,t.y,i.y),xi(e.z,t.z,i.z),xi(e.w,t.w,i.w))}static Random(e=0,t=1){return new Q(Pt(e,t),Pt(e,t),Pt(e,t),Pt(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Pt(e,t),Pt(e,t),Pt(e,t),Pt(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(Q.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return Q.CenterToRef(e,t,Q.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(Q.prototype,{dimension:{value:[4]},rank:{value:1}});class D{static get Use64Bits(){return gs.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=D._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,gs.MatrixTrackPrecisionChange&&gs.MatrixTrackedMatrices.push(this),this._m=new gs.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],f=e[11],_=e[12],p=e[13],g=e[14],x=e[15],T=d*x-g*f,S=u*x-p*f,C=u*g-p*d,v=c*x-_*f,b=c*g-d*_,A=c*p-_*u,P=+(o*T-l*S+h*C),L=-(n*T-l*v+h*b),w=+(n*S-o*v+h*A),$=-(n*C-o*b+l*A);return t*P+i*L+s*w+r*$}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}
${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}
${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}
${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return D.FromArrayToRef(e,t,this)}copyFromFloats(...e){return D.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return D.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let n=0;n<16;n++)s[n]=i[n]+r[n];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]-s[n];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new this.constructor)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]-r[n];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return D.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],f=t[10],_=t[11],p=t[12],g=t[13],x=t[14],T=t[15],S=f*T-x*_,C=d*T-g*_,v=d*x-g*f,b=u*T-p*_,A=u*x-f*p,P=u*g-p*d,L=+(l*S-h*C+c*v),w=-(o*S-h*b+c*A),$=+(o*C-l*b+c*P),J=-(o*v-l*A+h*P),ne=i*L+s*w+r*$+n*J;if(ne===0)return e.copyFrom(this),e;const oe=1/ne,re=h*T-x*c,ce=l*T-g*c,Se=l*x-g*h,Ce=o*T-p*c,ae=o*x-p*h,ie=o*g-p*l,F=h*_-f*c,j=l*_-d*c,se=l*f-d*h,Ie=o*_-u*c,Ye=o*f-u*h,$e=o*d-u*l,fe=-(s*S-r*C+n*v),me=+(i*S-r*b+n*A),Xe=-(i*C-s*b+n*P),Fe=+(i*v-s*A+r*P),ke=+(s*re-r*ce+n*Se),Ue=-(i*re-r*Ce+n*ae),Rt=+(i*ce-s*Ce+n*ie),hi=-(i*Se-s*ae+r*ie),_i=-(s*F-r*j+n*se),pi=+(i*F-r*Ie+n*Ye),er=-(i*j-s*Ie+n*$e),Os=+(i*se-s*Ye+r*$e);return D.FromValuesToRef(L*oe,fe*oe,ke*oe,_i*oe,w*oe,me*oe,Ue*oe,pi*oe,$*oe,Xe*oe,Rt*oe,er*oe,J*oe,Fe*oe,hi*oe,Os*oe,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new m(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]*=i[s];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]*r[n];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],l=s[2],h=s[3],c=s[4],u=s[5],d=s[6],f=s[7],_=s[8],p=s[9],g=s[10],x=s[11],T=s[12],S=s[13],C=s[14],v=s[15],b=r[0],A=r[1],P=r[2],L=r[3],w=r[4],$=r[5],J=r[6],ne=r[7],oe=r[8],re=r[9],ce=r[10],Se=r[11],Ce=r[12],ae=r[13],ie=r[14],F=r[15];return t[i]=n*b+o*w+l*oe+h*Ce,t[i+1]=n*A+o*$+l*re+h*ae,t[i+2]=n*P+o*J+l*ce+h*ie,t[i+3]=n*L+o*ne+l*Se+h*F,t[i+4]=c*b+u*w+d*oe+f*Ce,t[i+5]=c*A+u*$+d*re+f*ae,t[i+6]=c*P+u*J+d*ce+f*ie,t[i+7]=c*L+u*ne+d*Se+f*F,t[i+8]=_*b+p*w+g*oe+x*Ce,t[i+9]=_*A+p*$+g*re+x*ae,t[i+10]=_*P+p*J+g*ce+x*ie,t[i+11]=_*L+p*ne+g*Se+x*F,t[i+12]=T*b+S*w+C*oe+v*Ce,t[i+13]=T*A+S*$+C*re+v*ae,t[i+14]=T*P+S*J+C*ce+v*ie,t[i+15]=T*L+S*ne+C*Se+v*F,this}divide(e){return this.divideToRef(e,new this.constructor)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]/s[n];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]/=i[s];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=-t[s];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let r=0;r<16;r++)if(!Ms(i[r],s[r],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new this.constructor)}floorToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=Math.floor(t[s]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new this.constructor)}fractToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=t[s]-Math.floor(t[s]);return e.markAsUpdated(),e}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ar(this._m[0]);for(let t=1;t<16;t++)e=e*397^ar(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Q,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),e=e||Oe.Vector3[0],e.x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const o=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,l=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,h=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=h}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const o=1/e._x,l=1/e._y,h=1/e._z;D.FromValuesToRef(n[0]*o,n[1]*o,n[2]*o,0,n[4]*l,n[5]*l,n[6]*l,0,n[8]*h,n[9]*h,n[10]*h,0,0,0,0,1,Oe.Matrix[0]),Q.FromRotationMatrixToRef(Oe.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new we(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new this.constructor;return D.TransposeToRef(this,e),e}transposeToRef(e){return D.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=e*4;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=Oe.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return D.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=Oe.Vector3[0];if(!this.decompose(t))return D.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return D.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new D;return D.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return D._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,l,h,c,u,d,f,_,p,g,x){const T=x._m;T[0]=e,T[1]=t,T[2]=i,T[3]=s,T[4]=r,T[5]=n,T[6]=o,T[7]=l,T[8]=h,T[9]=c,T[10]=u,T[11]=d,T[12]=f,T[13]=_,T[14]=p,T[15]=g,x.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,l,h,c,u,d,f,_,p,g){const x=new D,T=x._m;return T[0]=e,T[1]=t,T[2]=i,T[3]=s,T[4]=r,T[5]=n,T[6]=o,T[7]=l,T[8]=h,T[9]=c,T[10]=u,T[11]=d,T[12]=f,T[13]=_,T[14]=p,T[15]=g,x.markAsUpdated(),x}static Compose(e,t,i){const s=new D;return D.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,l=t._z,h=t._w,c=n+n,u=o+o,d=l+l,f=n*c,_=n*u,p=n*d,g=o*u,x=o*d,T=l*d,S=h*c,C=h*u,v=h*d,b=e._x,A=e._y,P=e._z;return r[0]=(1-(g+T))*b,r[1]=(_+v)*b,r[2]=(p-C)*b,r[3]=0,r[4]=(_-v)*A,r[5]=(1-(f+T))*A,r[6]=(x+S)*A,r[7]=0,r[8]=(p+C)*P,r[9]=(x-S)*P,r[10]=(1-(f+g))*P,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=D.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=D.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new D;return D.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationY(e){const t=new D;return D.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationZ(e){const t=new D;return D.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return D.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationAxis(e,t){const i=new D;return D.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=m.Dot(t,e),n=i._m;if(r<-1+rt)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const o=m.Cross(t,e),l=1/(1+r);n[0]=o._x*o._x*l+r,n[1]=o._y*o._x*l-o._z,n[2]=o._z*o._x*l+o._y,n[3]=0,n[4]=o._x*o._y*l+o._z,n[5]=o._y*o._y*l+r,n[6]=o._z*o._y*l-o._x,n[7]=0,n[8]=o._x*o._z*l-o._y,n[9]=o._y*o._z*l+o._x,n[10]=o._z*o._z*l+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new D;return D.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return Q.RotationYawPitchRollToRef(e,t,i,Oe.Quaternion[0]),Oe.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new D;return D.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return D.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(e===1&&t===1&&i===1),s}static Translation(e,t,i){const s=new D;return D.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return D.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(e===0&&t===0&&i===0),s}static Lerp(e,t,i){const s=new e.constructor;return D.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let l=0;l<16;l++)r[l]=n[l]*(1-i)+o[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return D.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=Oe.Vector3[0],n=Oe.Quaternion[0],o=Oe.Vector3[1];e.decompose(r,n,o);const l=Oe.Vector3[2],h=Oe.Quaternion[1],c=Oe.Vector3[3];t.decompose(l,h,c);const u=Oe.Vector3[4];m.LerpToRef(r,l,i,u);const d=Oe.Quaternion[2];Q.SlerpToRef(n,h,i,d);const f=Oe.Vector3[5];return m.LerpToRef(o,c,i,f),D.ComposeToRef(u,d,f,s),s}static LookAtLH(e,t,i){const s=new D;return D.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=Oe.Vector3[0],n=Oe.Vector3[1],o=Oe.Vector3[2];t.subtractToRef(e,o),o.normalize(),m.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),m.CrossToRef(o,r,n),n.normalize();const h=-m.Dot(r,e),c=-m.Dot(n,e),u=-m.Dot(o,e);return D.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,h,c,u,1,s),s}static LookAtRH(e,t,i){const s=new D;return D.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=Oe.Vector3[0],n=Oe.Vector3[1],o=Oe.Vector3[2];e.subtractToRef(t,o),o.normalize(),m.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),m.CrossToRef(o,r,n),n.normalize();const h=-m.Dot(r,e),c=-m.Dot(n,e),u=-m.Dot(o,e);return D.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new D;return D.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=Oe.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=Oe.Vector3[1];return m.CrossToRef(t,s,r),D.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new D;return D.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=Oe.Vector3[2];return m.CrossToRef(t,e,s),D.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new D;return D.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=i,l=s,h=2/e,c=2/t,u=2/(l-o),d=-(l+o)/(l-o);return D.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,d,1,r),n&&r.multiplyToRef(go,r),r._updateIdentityStatus(h===1&&c===1&&u===1&&d===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const l=new D;return D.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l){const h=r,c=n,u=2/(t-e),d=2/(s-i),f=2/(c-h),_=-(c+h)/(c-h),p=(e+t)/(e-t),g=(s+i)/(i-s);return D.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,f,0,p,g,_,1,o),l&&o.multiplyToRef(go,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,l,h,c,u){const d=-o*Math.cos(l),f=-o*Math.sin(l);return D.TranslationToRef(0,0,-h,Oe.Matrix[1]),D.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,Oe.Matrix[0]),Oe.Matrix[1].multiplyToRef(Oe.Matrix[0],Oe.Matrix[0]),D.TranslationToRef(0,0,h,Oe.Matrix[1]),Oe.Matrix[0].multiplyToRef(Oe.Matrix[1],Oe.Matrix[0]),D.OrthoOffCenterLHToRef(e,t,i,s,r,n,c,u),Oe.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,r,n,o){const l=new D;return D.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,l){return D.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,l,h,c,u){const d=o*Math.cos(l),f=o*Math.sin(l);return D.TranslationToRef(0,0,h,Oe.Matrix[1]),D.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,Oe.Matrix[0]),Oe.Matrix[1].multiplyToRef(Oe.Matrix[0],Oe.Matrix[0]),D.TranslationToRef(0,0,-h,Oe.Matrix[1]),Oe.Matrix[0].multiplyToRef(Oe.Matrix[1],Oe.Matrix[0]),D.OrthoOffCenterRHToRef(e,t,i,s,r,n,c,u),Oe.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,r,n=0){const o=new D,l=i,h=s,c=2*l/e,u=2*l/t,d=(h+l)/(h-l),f=-2*h*l/(h-l),_=Math.tan(n);return D.FromValuesToRef(c,0,0,0,0,u,0,_,0,0,d,1,0,0,f,0,o),r&&o.multiplyToRef(go,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const l=new D;return D.PerspectiveFovLHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,_=n?d:d*t,p=h&&c===0?-1:u!==0?(u+c)/(u-c):1,g=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,x=Math.tan(l);return D.FromValuesToRef(f,0,0,0,0,_,0,x,0,0,p,1,0,0,g,0,r),o&&r.multiplyToRef(go,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return D.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(go,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const l=new D;return D.PerspectiveFovRHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,_=n?d:d*t,p=h&&c===0?1:u!==0?-(u+c)/(u-c):-1,g=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,x=Math.tan(l);return D.FromValuesToRef(f,0,0,0,0,_,0,x,0,0,p,-1,0,0,g,0,r),o&&r.multiplyToRef(go,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return D.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(go,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,l=e.height,h=e.x,c=e.y,u=D.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,n-r,0,h+o/2,l/2+c,r,1),d=new t.constructor;return t.multiplyToRef(i,d),d.multiplyToRef(s,d),d.multiplyToRef(u,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return gs.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return gs.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return D.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],l=i[1],h=i[5],c=i[9],u=i[13],d=i[2],f=i[6],_=i[10],p=i[14],g=i[3],x=i[7],T=i[11],S=i[15],C=t._m;return C[0]=s,C[1]=r,C[2]=n,C[3]=o,C[4]=l,C[5]=h,C[6]=c,C[7]=u,C[8]=d,C[9]=f,C[10]=_,C[11]=p,C[12]=g,C[13]=x,C[14]=T,C[15]=S,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new D;return D.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,l=-2*r;return D.FromValuesToRef(n*i+1,o*i,l*i,0,n*s,o*s+1,l*s,0,n*r,o*r,l*r+1,0,n*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return D.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,l=e._z*e._x,h=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(l+h),t._m[9]=2*(c-u),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}D._UpdateFlagSeed=0;D._IdentityReadOnly=D.Identity();Object.defineProperties(D.prototype,{dimension:{value:[4,4]},rank:{value:2}});class Oe{}Oe.Vector3=Xi.BuildTuple(11,m.Zero);Oe.Matrix=Xi.BuildTuple(2,D.Identity);Oe.Quaternion=Xi.BuildTuple(3,Q.Zero);class U{}U.Vector2=Xi.BuildTuple(3,Z.Zero);U.Vector3=Xi.BuildTuple(13,m.Zero);U.Vector4=Xi.BuildTuple(3,we.Zero);U.Quaternion=Xi.BuildTuple(2,Q.Zero);U.Matrix=Xi.BuildTuple(8,D.Identity);V("BABYLON.Vector2",Z);V("BABYLON.Vector3",m);V("BABYLON.Vector4",we);V("BABYLON.Matrix",D);const go=D.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class ge{static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=e*2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=ge.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=ge.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=ge.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+ge.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=ge.DeltaAngle(e,t);let r=0;return-i<s&&s<i?r=t:(t=e+s,r=ge.MoveTowards(e,t,i)),r}static LerpAngle(e,t,i){let s=ge.Repeat(t-e,360);return s>180&&(s-=360),e+s*xi(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=xi((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n;return e*l+i*h+t*c+s*u}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return(n-r)*6*e+(3*n-4*r+1)*t+(-n+r)*6*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return i===0?t:ge.HCF(t,i)}}ge.TwoPi=Math.PI*2;ge.WithinEpsilon=Ms;ge.ToHex=dn;ge.Clamp=xi;ge.Lerp=_r;ge.RandomRange=Pt;ge.NormalizeRadians=hE;function Sl(a){return Math.pow(a,Ud)}function Cl(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function vl(a){return Math.pow(a,Kc)}function bl(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class q{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return q.FromArrayToRef(e,t,this),this}toColor4(e=1){return new xe(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new this.constructor(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=rt){return ge.WithinEpsilon(this.r,e.r,t)&&ge.WithinEpsilon(this.g,e.g,t)&&ge.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=xi(this.r,e,t),i.g=xi(this.g,e,t),i.b=xi(this.b,e,t),i}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new this.constructor(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this.r-e,this.g-t,this.b-i)}clone(){return new this.constructor(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+dn(e)+dn(t)+dn(i)}toHSV(){const e=new this.constructor;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,l=0;const h=r,c=r-n;r!==0&&(l=c/r),r!=n&&(r==t?(o=(i-s)/c,i<s&&(o+=6)):r==i?o=(s-t)/c+2:r==s&&(o=(t-i)/c+4),o*=60),e.r=o,e.g=l,e.b=h}toLinearSpace(e=!1){const t=new this.constructor;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Cl(this.r),e.g=Cl(this.g),e.b=Cl(this.b)):(e.r=Sl(this.r),e.g=Sl(this.g),e.b=Sl(this.b)),this}toGammaSpace(e=!1){const t=new this.constructor;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=bl(this.r),e.g=bl(this.g),e.b=bl(this.b)):(e.r=vl(this.r),e.g=vl(this.g),e.b=vl(this.b)),this}static HSVtoRGBToRef(e,t,i,s){const r=i*t,n=e/60,o=r*(1-Math.abs(n%2-1));let l=0,h=0,c=0;n>=0&&n<=1?(l=r,h=o):n>=1&&n<=2?(l=o,h=r):n>=2&&n<=3?(h=r,c=o):n>=3&&n<=4?(h=o,c=r):n>=4&&n<=5?(l=o,c=r):n>=5&&n<=6&&(l=r,c=o);const u=i-r;s.set(l+u,h+u,c+u)}static FromHSV(e,t,i){const s=new q(0,0,0);return q.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new q(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return q.FromInts(t,i,s)}static FromArray(e,t=0){return new q(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new q(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new q(0,0,0);return q.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.r*l+i.r*h+t.r*c+s.r*u,f=e.g*l+i.g*h+t.g*c+s.g*u,_=e.b*l+i.b*h+t.b*c+s.b*u;return new q(d,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=q.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b}static Red(){return new q(1,0,0)}static Green(){return new q(0,1,0)}static Blue(){return new q(0,0,1)}static Black(){return new q(0,0,0)}static get BlackReadOnly(){return q._BlackReadOnly}static White(){return new q(1,1,1)}static Purple(){return new q(.5,0,.5)}static Magenta(){return new q(1,0,1)}static Yellow(){return new q(1,1,0)}static Gray(){return new q(.5,.5,.5)}static Teal(){return new q(0,1,1)}static Random(){return new q(Math.random(),Math.random(),Math.random())}}q._BlackReadOnly=q.Black();Object.defineProperties(q.prototype,{dimension:{value:[3]},rank:{value:1}});class xe{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new this.constructor(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=xi(this.r,e,t),i.g=xi(this.g,e,t),i.b=xi(this.b,e,t),i.a=xi(this.a,e,t),i}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new this.constructor(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=rt){return ge.WithinEpsilon(this.r,e.r,t)&&ge.WithinEpsilon(this.g,e.g,t)&&ge.WithinEpsilon(this.b,e.b,t)&&ge.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new this.constructor().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),s=Math.round(this.b*255);if(e)return"#"+dn(t)+dn(i)+dn(s);const r=Math.round(this.a*255);return"#"+dn(t)+dn(i)+dn(s)+dn(r)}toLinearSpace(e=!1){const t=new xe;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Cl(this.r),e.g=Cl(this.g),e.b=Cl(this.b)):(e.r=Sl(this.r),e.g=Sl(this.g),e.b=Sl(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new xe;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=bl(this.r),e.g=bl(this.g),e.b=bl(this.b)):(e.r=vl(this.r),e.g=vl(this.g),e.b=vl(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new xe(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=e.length===9?parseInt(e.substring(7,9),16):255;return xe.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new xe(0,0,0,0);return xe.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.r*l+i.r*h+t.r*c+s.r*u,f=e.g*l+i.g*h+t.g*c+s.g*u,_=e.b*l+i.b*h+t.b*c+s.b*u,p=e.a*l+i.a*h+t.a*c+s.a*u;return new xe(d,f,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new xe;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b,n.a=(o-r)*6*e.a+(3*o-4*r+1)*t.a+(-o+r)*6*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new xe(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new xe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new xe(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;s<e.length;s+=3){const r=s/3*4;i[r]=e[s],i[r+1]=e[s+1],i[r+2]=e[s+2],i[r+3]=1}return i}return e}}Object.defineProperties(xe.prototype,{dimension:{value:[4]},rank:{value:1}});class gt{}gt.Color3=Xi.BuildArray(3,q.Black);gt.Color4=Xi.BuildArray(3,()=>new xe(0,0,0,0));V("BABYLON.Color3",q);V("BABYLON.Color4",xe);class Yt{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new G,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const s=this._condition.serialize();return s.children.push(i),t&&t.children.push(s),s}return t&&t.children.push(i),i}}Yt._SerializeValueAsString=a=>typeof a=="number"?a.toString():typeof a=="boolean"?a?"true":"false":a instanceof Z?a.x+", "+a.y:a instanceof m?a.x+", "+a.y+", "+a.z:a instanceof q?a.r+", "+a.g+", "+a.b:a instanceof xe?a.r+", "+a.g+", "+a.b+", "+a.a:a;Yt._GetTargetProperty=a=>({name:"target",targetType:a._isMesh?"MeshProperties":a._isLight?"LightProperties":a._isCamera?"CameraProperties":a._isMaterial?"MaterialProperties":"SceneProperties",value:a._isScene?"Scene":a.name});V("BABYLON.Action",Yt);class di{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 di(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new di(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new di(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new di(e,t.x,t.y,null,i,s)}}class Tu{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class ns extends Tu{static get IsEqual(){return ns._IsEqual}static get IsDifferent(){return ns._IsDifferent}static get IsGreater(){return ns._IsGreater}static get IsLesser(){return ns._IsLesser}constructor(e,t,i,s,r=ns.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ns.IsGreater:return this._effectiveTarget[this._property]>this.value;case ns.IsLesser:return this._effectiveTarget[this._property]<this.value;case ns.IsEqual:case ns.IsDifferent:{let e;return this.value.equals?e=this.value.equals(this._effectiveTarget[this._property]):e=this.value===this._effectiveTarget[this._property],this.operator===ns.IsEqual?e:!e}}return!1}serialize(){return this._serialize({name:"ValueCondition",properties:[Yt._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Yt._SerializeValueAsString(this.value)},{name:"operator",value:ns.GetOperatorName(this.operator)}]})}static GetOperatorName(e){switch(e){case ns._IsEqual:return"IsEqual";case ns._IsDifferent:return"IsDifferent";case ns._IsGreater:return"IsGreater";case ns._IsLesser:return"IsLesser";default:return""}}}ns._IsEqual=0;ns._IsDifferent=1;ns._IsGreater=2;ns._IsLesser=3;class JC extends Tu{constructor(e,t){super(e),this.predicate=t}isValid(){return this.predicate()}}class ev extends Tu{constructor(e,t,i){super(e),this.value=i,this._target=t}isValid(){return this._target.state===this.value}serialize(){return this._serialize({name:"StateCondition",properties:[Yt._GetTargetProperty(this._target),{name:"value",value:this.value}]})}}V("BABYLON.ValueCondition",ns);V("BABYLON.PredicateCondition",JC);V("BABYLON.StateCondition",ev);class O{static _CheckLimit(e,t){let i=O._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},O._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=O._LogLimitOutputs[e];if(!i||!O.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&O[s.name](O.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,s.name??""))}static _AddLogEntry(e){O._LogCache=e+O._LogCache,O.OnNewCacheEntry&&O.OnNewCacheEntry(e)}static _FormatMessage(e){const t=s=>s<10?"0"+s:""+s,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(i!==void 0&&!O._CheckLimit(s,i))return;const r=O._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const l=`<div style='color:${n.color}'>${r}</div><br>`;O._AddLogEntry(l),O._GenerateLimitMessage(s,e)}static get LogCache(){return O._LogCache}static ClearLogCache(){O._LogCache="",O._LogLimitOutputs={},O.errorsCount=0}static set LogLevels(e){O.Log=O._LogDisabled,O.Warn=O._LogDisabled,O.Error=O._LogDisabled,[O.MessageLogLevel,O.WarningLogLevel,O.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];O[i.name]=O._LogEnabled.bind(O,t)}})}}O.NoneLogLevel=0;O.MessageLogLevel=1;O.WarningLogLevel=2;O.ErrorLogLevel=4;O.AllLogLevel=7;O.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";O._LogCache="";O._LogLimitOutputs={};O._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];O.errorsCount=0;O.Log=O._LogEnabled.bind(O,O.MessageLogLevel);O.Warn=O._LogEnabled.bind(O,O.WarningLogLevel);O.Error=O._LogEnabled.bind(O,O.ErrorLogLevel);class tv extends Yt{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Yt._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class iv extends Yt{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Yt._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class sv extends Yt{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Yt._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Yt._SerializeValueAsString(this.value)}]},e)}}class rv extends Yt{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),typeof this._effectiveTarget[this._property]!="number"&&O.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Yt._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Yt._SerializeValueAsString(this.value)}]},e)}}class nv extends Yt{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Yt._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Yt._SerializeValueAsString(this.loop)||!1}]},e)}}class av extends Yt{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Yt._GetTargetProperty(this._target)]},e)}}class cE extends Yt{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class ov extends Yt{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()}execute(e){for(const t of this.children)(!this.enableChildrenConditions||t._evaluateConditionForCurrentFrame())&&t.execute(e)}serialize(e){const t=super._serialize({name:"CombineAction",properties:[],combine:[]},e);for(let i=0;i<this.children.length;i++)t.combine.push(this.children[i].serialize(null));return t}}class lv extends Yt{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}}class uE extends Yt{constructor(e,t,i,s){super(e,s),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;const e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=m.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[Yt._GetTargetProperty(this._target),Yt._GetTargetProperty(this._parent)]},e)}}V("BABYLON.SetParentAction",uE);V("BABYLON.ExecuteCodeAction",lv);V("BABYLON.DoNothingAction",cE);V("BABYLON.StopAnimationAction",av);V("BABYLON.PlayAnimationAction",nv);V("BABYLON.IncrementValueAction",rv);V("BABYLON.SetValueAction",sv);V("BABYLON.SetStateAction",iv);V("BABYLON.SetParentAction",uE);V("BABYLON.SwitchBooleanAction",tv);V("BABYLON.CombineAction",ov);const $g=(a,e,t)=>!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&(a.getClassName()==="SubMesh"||a.getClassName()==="PhysicsBody")?a.clone(e):a.clone?a.clone():Array.isArray(a)?a.slice():t&&typeof a=="object"?{...a}:null;function hv(a){const e=[];do Object.getOwnPropertyNames(a).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(a=Object.getPrototypeOf(a));return e}class Cs{static DeepCopy(e,t,i,s,r=!1){const n=hv(e);for(const o of n){if(o[0]==="_"&&(!s||s.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const l=e[o],h=typeof l;if(h!=="function")try{if(h==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let c=0;c<l.length;c++){const u=$g(l[c],t,r);t[o].indexOf(u)===-1&&t[o].push(u)}else t[o]=l.slice(0)}else t[o]=$g(l,t,r);else t[o]=l}catch(c){O.Warn(c.message)}}}}class It extends vr{constructor(e){super(),e=e||Ae.LastCreatedScene,e&&(this._scene=e,e.actionManagers.push(this))}dispose(){const e=this._scene.actionManagers.indexOf(this);for(let i=0;i<this.actions.length;i++){const s=this.actions[i];It.Triggers[s.trigger]--,It.Triggers[s.trigger]===0&&delete It.Triggers[s.trigger]}this.actions.length=0,e>-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter(i=>i.actionManager===this);for(const i of t)i.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t<this.actions.length;t++){const i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i<this.actions.length;i++){const s=this.actions[i];if(e==s.trigger||t==s.trigger)return!0}return!1}hasSpecificTrigger(e,t){for(let i=0;i<this.actions.length;i++){const s=this.actions[i];if(s.trigger===e)if(t){if(t(s.getTriggerParameter()))return!0}else return!0}return!1}get hasPointerTriggers(){for(let e=0;e<this.actions.length;e++){const t=this.actions[e];if(t.trigger>=It.OnPickTrigger&&t.trigger<=It.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e<this.actions.length;e++){const t=this.actions[e];if(t.trigger>=It.OnPickTrigger&&t.trigger<=It.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===It.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(O.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,It.Triggers[e.trigger]?It.Triggers[e.trigger]++:It.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return t!==-1?(this.actions.splice(t,1),It.Triggers[e.trigger]-=1,It.Triggers[e.trigger]===0&&delete It.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i<this.actions.length;i++){const s=this.actions[i];if(s.trigger===e){if(t&&(e===It.OnKeyUpTrigger||e===It.OnKeyDownTrigger)){const r=s.getTriggerParameter();if(typeof r=="function"){if(!r(t))continue}else if(r&&r!==t.sourceEvent.keyCode){if(!r.toLowerCase)continue;const n=r.toLowerCase();if(n!==t.sourceEvent.key){const o=t.sourceEvent.charCode?t.sourceEvent.charCode:t.sourceEvent.keyCode;if(String.fromCharCode(o).toLowerCase()!==n)continue}}}s._executeCurrent(t)}}}_getEffectiveTarget(e,t){const i=t.split(".");for(let s=0;s<i.length-1;s++)e=e[i[s]];return e}_getProperty(e){const t=e.split(".");return t[t.length-1]}serialize(e){const t={children:new Array,name:e,type:3,properties:new Array};for(let i=0;i<this.actions.length;i++){const s={type:0,children:new Array,name:It.GetTriggerName(this.actions[i].trigger),properties:new Array},r=this.actions[i].triggerOptions;if(r&&typeof r!="number")if(r.parameter instanceof Node)s.properties.push(Yt._GetTargetProperty(r.parameter));else if(typeof r.parameter=="object"){const n={};Cs.DeepCopy(r.parameter,n,["mesh"]),r.parameter&&r.parameter.mesh&&(n._meshId=r.parameter.mesh.id),s.properties.push({name:"parameter",targetType:null,value:n})}else s.properties.push({name:"parameter",targetType:null,value:r.parameter});this.actions[i].serialize(s),t.children.push(s)}return t}static Parse(e,t,i){const s=new It(i);t===null?i.actionManager=s:t.actionManager=s;const r=(l,h)=>{const c=Si("BABYLON."+l);return c&&new c(...h)},n=(l,h,c,u)=>{if(u===null){const p=parseFloat(h);return h==="true"||h==="false"?h==="true":isNaN(p)?h:p}const d=u.split("."),f=h.split(",");for(let p=0;p<d.length;p++)c=c[d[p]];if(typeof c=="boolean")return f[0]==="true";if(typeof c=="string")return f[0];const _=[];for(let p=0;p<f.length;p++)_.push(parseFloat(f[p]));return c instanceof m?m.FromArray(_):c instanceof we?we.FromArray(_):c instanceof q?q.FromArray(_):c instanceof xe?xe.FromArray(_):parseFloat(f[0])},o=(l,h,c,u,d=null)=>{if(l.detached)return;const f=[];let _=null,p=null;const g=l.combine&&l.combine.length>0;if(l.type===2?f.push(s):f.push(h),g){const T=[];for(let S=0;S<l.combine.length;S++)o(l.combine[S],It.NothingTrigger,c,u,T);f.push(T)}else for(let T=0;T<l.properties.length;T++){let S=l.properties[T].value;const C=l.properties[T].name,v=l.properties[T].targetType;C==="target"?v==="SceneProperties"?S=_=i:v==="MaterialProperties"?S=_=i.getMaterialByName(S):S=_=i.getNodeByName(S):C==="parent"?S=i.getNodeByName(S):C==="sound"?i.getSoundByName&&(S=i.getSoundByName(S)):C!=="propertyPath"?l.type===2&&C==="operator"?S=ns[S]:S=n(C,S,_,C==="value"?p:null):p=S,f.push(S)}if(d===null?f.push(c):f.push(null),l.name==="InterpolateValueAction"){const T=f[f.length-2];f[f.length-1]=T,f[f.length-2]=c}let x=r(l.name,f);if(x instanceof Tu&&c!==null){const T=new cE(h,c);u?u.then(T):s.registerAction(T),u=T}d===null?x instanceof Tu?(c=x,x=u):(c=null,u?u.then(x):s.registerAction(x)):d.push(x);for(let T=0;T<l.children.length;T++)o(l.children[T],h,c,x,null)};for(let l=0;l<e.children.length;l++){let h;const c=e.children[l];if(c.properties.length>0){const u=c.properties[0].value,d=c.properties[0].targetType===null?u:i.getMeshByName(u);d._meshId&&(d.mesh=i.getMeshById(d._meshId)),h={trigger:It[c.name],parameter:d}}else h=It[c.name];for(let u=0;u<c.children.length;u++)c.detached||o(c.children[u],h,null,null)}}static GetTriggerName(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnDoublePickTrigger";case 7:return"OnPickUpTrigger";case 8:return"OnLongPressTrigger";case 9:return"OnPointerOverTrigger";case 10:return"OnPointerOutTrigger";case 11:return"OnEveryFrameTrigger";case 12:return"OnIntersectionEnterTrigger";case 13:return"OnIntersectionExitTrigger";case 14:return"OnKeyDownTrigger";case 15:return"OnKeyUpTrigger";case 16:return"OnPickOutTrigger";default:return""}}}It.NothingTrigger=0;It.OnPickTrigger=1;It.OnLeftPickTrigger=2;It.OnRightPickTrigger=3;It.OnCenterPickTrigger=4;It.OnPickDownTrigger=5;It.OnDoublePickTrigger=6;It.OnPickUpTrigger=7;It.OnPickOutTrigger=16;It.OnLongPressTrigger=8;It.OnPointerOverTrigger=9;It.OnPointerOutTrigger=10;It.OnEveryFrameTrigger=11;It.OnIntersectionEnterTrigger=12;It.OnIntersectionExitTrigger=13;It.OnKeyDownTrigger=14;It.OnKeyUpTrigger=15;class cv extends Yt{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){this._sound!==void 0&&this._sound.play()}serialize(e){return super._serialize({name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}}class uv extends Yt{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){this._sound!==void 0&&this._sound.stop()}serialize(e){return super._serialize({name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}}V("BABYLON.PlaySoundAction",cv);V("BABYLON.StopSoundAction",uv);var Kd;(function(a){a[a.NONE=0]="NONE",a[a.STEP=1]="STEP"})(Kd||(Kd={}));class Nl{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new Nl(this.name,this.from,this.to)}}function E(a,e,t,i){var s=arguments.length,r=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(a,e,t,i);else for(var o=a.length-1;o>=0;o--)(n=a[o])&&(r=(s<3?n(r):s>3?n(e,t,r):n(e,t))||r);return s>3&&r&&Object.defineProperty(e,t,r),r}const bd={},Vd={};function dv(a){const e=a.getClassName();return Vd[e]||(Vd[e]={}),Vd[e]}function J_(a){const e=a.getClassName();if(bd[e])return bd[e];bd[e]={};const t=bd[e];let i=a,s=e;for(;s;){const r=Vd[s];for(const l in r)t[l]=r[l];let n,o=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){o=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(o)break;s=n.getClassName(),i=n}return t}function kr(a,e){return(t,i)=>{const s=dv(t);s[i]||(s[i]={type:a,sourceName:e})}}function fv(a,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(r){typeof this.equals=="function"&&this.equals(r)||this[s]!==r&&(this[s]=r,t[a].apply(this))},enumerable:!0,configurable:!0})}}function te(a,e=null){return fv(a,e)}function I(a){return kr(0,a)}function ht(a){return kr(1,a)}function li(a){return kr(2,a)}function zu(a){return kr(3,a)}function hm(a){return kr(4,a)}function bs(a){return kr(5,a)}function Wu(a){return kr(6,a)}function _v(a){return kr(7,a)}function cm(a){return kr(8,a)}function dE(a){return kr(9,a)}function pv(a){return kr(10,a)}function um(a){return kr(12,a)}function mv(a){return kr(11,a)}function Qa(a,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?n=(...l)=>i(...l)?o(...l):s(...l):n=o}return a[e]=n,n(...r)}}Qa.filter=function(a){return(e,t,i)=>Qa(e,t,i,a)};const Kg={};function Ge(a,e=!1){if(!(e&&Kg[a]))return Kg[a]=!0,`${a} needs to be imported before as it contains a side-effect required by your code.`}class To{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),To._HandleParenthesisContent(i,t))):e=To._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:To.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(r=>r==="true");let i;const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let n=To._SimplifyNegation(s[r].trim());const o=n.split("&&");if(o.length>1)for(let l=0;l<o.length;++l){const h=To._SimplifyNegation(o[l].trim());if(h!=="true"&&h!=="false"?h[0]==="!"?i=!t(h.substring(1)):i=t(h):i=h==="true",!i){n="false";break}}if(i||n==="true"){i=!0;break}n!=="true"&&n!=="false"?n[0]==="!"?i=!t(n.substring(1)):i=t(n):i=n==="true"}return i?"true":"false"}static _SimplifyNegation(e){return e=e.replace(/^[\s!]+/,t=>(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class ft{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ft.HasTags(e),e.addTags=t=>ft.AddTagsTo(e,t),e.removeTags=t=>ft.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ft.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const i=[];for(const s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&e._tags[s]===!0&&i.push(s);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(s){ft._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ft.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ft.HasTags(e))return;const i=t.split(" ");for(const s in i)ft._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?ft.HasTags(e):To.Eval(t,i=>ft.HasTags(e)&&e._tags[i])}}const jg=function(a,e,t,i={}){const s=a();ft&&ft.HasTags(e)&&ft.AddTagsTo(s,ft.GetTags(e,!0));const r=J_(s),n={};for(const o in r){const l=r[o],h=e[o],c=l.type;if(h!=null&&(o!=="uniqueId"||_e.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[o]=h;break;case 1:i.cloneTexturesOnlyOnce&&n[h.uniqueId]?s[o]=n[h.uniqueId]:(s[o]=t||h.isRenderTarget?h:h.clone(),n[h.uniqueId]=s[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[o]=t?h:h.clone();break}}return s};class _e{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){const s=e.animations[i];t.animations.push(s.serialize())}}}static Serialize(e,t){t||(t={}),ft&&(t.tags=ft.GetTags(e));const i=J_(e);for(const s in i){const r=i[s],n=r.sourceName||s,o=r.type,l=e[s];if(l!=null&&(s!=="uniqueId"||_e.AllowLoadingUniqueId))switch(o){case 0:t[n]=l;break;case 1:t[n]=l.serialize();break;case 2:t[n]=l.asArray();break;case 3:t[n]=l.serialize();break;case 4:t[n]=l.asArray();break;case 5:t[n]=l.asArray();break;case 6:t[n]=l.id;break;case 7:t[n]=l.serialize();break;case 8:t[n]=l.asArray();break;case 9:t[n]=l.serialize();break;case 10:t[n]=l.asArray();break;case 11:t[n]=l.id;break;case 12:t[n]=l.asArray();break}}return t}static ParseProperties(e,t,i,s){s||(s="");const r=J_(t);for(const n in r){const o=r[n],l=e[o.sourceName||n],h=o.type;if(l!=null&&(n!=="uniqueId"||_e.AllowLoadingUniqueId)){const c=t;switch(h){case 0:c[n]=l;break;case 1:i&&(c[n]=_e._TextureParser(l,i,s));break;case 2:c[n]=q.FromArray(l);break;case 3:c[n]=_e._FresnelParametersParser(l);break;case 4:c[n]=Z.FromArray(l);break;case 5:c[n]=m.FromArray(l);break;case 6:i&&(c[n]=i.getLastMeshById(l));break;case 7:c[n]=_e._ColorCurvesParser(l);break;case 8:c[n]=xe.FromArray(l);break;case 9:c[n]=_e._ImageProcessingConfigurationParser(l);break;case 10:c[n]=Q.FromArray(l);break;case 11:i&&(c[n]=i.getCameraById(l));break;case 12:c[n]=D.FromArray(l);break}}}}static Parse(e,t,i,s=null){const r=e();return ft&&ft.AddTagsTo(r,t.tags),_e.ParseProperties(t,r,i,s),r}static Clone(e,t,i={}){return jg(e,t,!1,i)}static Instanciate(e,t){return jg(e,t,!0)}}_e.AllowLoadingUniqueId=!1;_e._ImageProcessingConfigurationParser=a=>{throw Ge("ImageProcessingConfiguration")};_e._FresnelParametersParser=a=>{throw Ge("FresnelParameters")};_e._ColorCurvesParser=a=>{throw Ge("ColorCurves")};_e._TextureParser=(a,e,t)=>{throw Ge("Texture")};class gv{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new G,this._onClonedObservable=new G}}let Ct=class ep{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new gv,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new G,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=D.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new G,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Ae.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){const t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children&&this._children.forEach(e=>{e._syncParentEnabledState()})}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s<this._children.length;s++){const r=this._children[s];(!i||i(r))&&e.push(r),t||r._getDescendants(e,!1,i)}}getDescendants(e,t){const i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){const i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=ep._AnimationRangeFactory(e,t,i);for(let s=0,r=this.animations.length;s<r;s++)this.animations[s]&&this.animations[s].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,s=this.animations.length;i<s;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){const s=_e.Clone(()=>new ep(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n<r.length;n++){const o=r[n];o.clone(e+"."+o.name,s)}}return s}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,s){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,s):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.push(s)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=D.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const i=this.getDescendants(!0);for(const s of i)s.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const i of this._behaviors)i.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let s=0;s<t.ranges.length;s++){const r=t.ranges[s];e.createAnimationRange(r.name,r.from,r.to)}}getHierarchyBoundingVectors(e=!0,t=null){this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);let i,s;const r=this;if(r.getBoundingInfo&&r.subMeshes){const n=r.getBoundingInfo();i=n.boundingBox.minimumWorld.clone(),s=n.boundingBox.maximumWorld.clone()}else i=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const n=this.getDescendants(!1);for(const o of n){const l=o;if(l.computeWorldMatrix(!0),t&&!t(l)||!l.getBoundingInfo||l.getTotalVertices()===0)continue;const c=l.getBoundingInfo().boundingBox,u=c.minimumWorld,d=c.maximumWorld;m.CheckExtends(u,i,s),m.CheckExtends(d,i,s)}}return{min:i,max:s}}};Ct._AnimationRangeFactory=(a,e,t)=>{throw Ge("AnimationRange")};Ct._NodeConstructors={};E([I()],Ct.prototype,"name",void 0);E([I()],Ct.prototype,"id",void 0);E([I()],Ct.prototype,"uniqueId",void 0);E([I()],Ct.prototype,"state",void 0);E([I()],Ct.prototype,"metadata",void 0);class Dr{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Dr(this.width*e,this.height*t)}clone(){return new Dr(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new Dr(0,0)}add(e){return new Dr(this.width+e.width,this.height+e.height)}subtract(e){return new Dr(this.width-e.width,this.height-e.height)}scale(e){return new Dr(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Dr(s,r)}}function xv(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class yi{constructor(){this._xhr=xv(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(yi.CustomRequestHeaders).length>0||yi.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in yi.CustomRequestHeaders){const t=yi.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return yi.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){yi.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of yi.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}t=t.replace("file:http:","http:"),t=t.replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}yi.CustomRequestHeaders={};yi.CustomRequestModifiers=new Array;yi.SkipRequestModificationForBabylonCDN=!0;const fE=Object.freeze(new Q(0,0,0,0)),_E=Object.freeze(m.Zero()),pE=Object.freeze(Z.Zero()),mE=Object.freeze(Dr.Zero()),gE=Object.freeze(q.Black()),xE=Object.freeze(new xe(0,0,0,0)),on={key:0,repeatCount:0,loopMode:2};class K{static _PrepareAnimation(e,t,i,s,r,n,o,l){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=K.ANIMATIONTYPE_FLOAT:r instanceof Q?h=K.ANIMATIONTYPE_QUATERNION:r instanceof m?h=K.ANIMATIONTYPE_VECTOR3:r instanceof Z?h=K.ANIMATIONTYPE_VECTOR2:r instanceof q?h=K.ANIMATIONTYPE_COLOR3:r instanceof xe?h=K.ANIMATIONTYPE_COLOR4:r instanceof Dr&&(h=K.ANIMATIONTYPE_SIZE),h==null)return null;const c=new K(e,t,i,h,o),u=[{frame:0,value:r},{frame:s,value:n}];return c.setKeys(u),l!==void 0&&c.setEasingFunction(l),c}static CreateAnimation(e,t,i,s){const r=new K(e+"Animation",e,i,t,K.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,l,h,c,u){const d=K._PrepareAnimation(e,i,s,r,n,o,l,h);return!d||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[d],0,r,d.loopMode===1,1,c)}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,l,h,c,u){const d=K._PrepareAnimation(e,s,r,n,o,l,h,c);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,n,d.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,l,h,c){const u=K._PrepareAnimation(e,i,s,r,n,o,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,r,u.loopMode===1,1,c)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;typeof t=="object"?n=t:n={referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const l=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let h=0;const c=o._keys[0];let u=o._keys.length-1;const d=o._keys[u],f={referenceValue:c.value,referencePosition:U.Vector3[0],referenceQuaternion:U.Quaternion[0],referenceScaling:U.Vector3[1],keyPosition:U.Vector3[2],keyQuaternion:U.Quaternion[1],keyScaling:U.Vector3[3]};let _=c.frame,p=d.frame;if(n.range){const T=o.getRange(n.range);T&&(_=T.from,p=T.to)}else _=n.fromFrame??_,p=n.toFrame??p;if(_!==c.frame&&(h=o.createKeyForFrame(_)),p!==d.frame&&(u=o.createKeyForFrame(p)),o._keys.length===1){const T=o._getKeyValue(o._keys[0]);f.referenceValue=T.clone?T.clone():T}else if(l<=c.frame){const T=o._getKeyValue(c.value);f.referenceValue=T.clone?T.clone():T}else if(l>=d.frame){const T=o._getKeyValue(d.value);f.referenceValue=T.clone?T.clone():T}else{on.key=0;const T=o._interpolate(l,on);f.referenceValue=T.clone?T.clone():T}o.dataType===K.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():o.dataType===K.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE;const x=n.clipKeys?[]:null;for(let T=h;T<=u;T++){let S=o._keys[T];if(x&&(S={frame:S.frame,value:S.value.clone?S.value.clone():S.value,inTangent:S.inTangent,outTangent:S.outTangent,interpolation:S.interpolation,lockedTangent:S.lockedTangent},g===Number.MAX_VALUE&&(g=S.frame),S.frame-=g,x.push(S)),!(T&&o.dataType!==K.ANIMATIONTYPE_FLOAT&&S.value===c.value))switch(o.dataType){case K.ANIMATIONTYPE_MATRIX:S.value.decompose(f.keyScaling,f.keyQuaternion,f.keyPosition),f.keyPosition.subtractInPlace(f.referencePosition),f.keyScaling.divideInPlace(f.referenceScaling),f.referenceQuaternion.multiplyToRef(f.keyQuaternion,f.keyQuaternion),D.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,S.value);break;case K.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(S.value,S.value);break;case K.ANIMATIONTYPE_VECTOR2:case K.ANIMATIONTYPE_VECTOR3:case K.ANIMATIONTYPE_COLOR3:case K.ANIMATIONTYPE_COLOR4:S.value.subtractToRef(f.referenceValue,S.value);break;case K.ANIMATIONTYPE_SIZE:S.value.width-=f.referenceValue.width,S.value.height-=f.referenceValue.height;break;default:S.value-=f.referenceValue}}return x&&o.setKeys(x,!0),o}static TransitionTo(e,t,i,s,r,n,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const h=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const c=s.beginAnimation(i,0,h,!1);return c.onAnimationEnd=l,c}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=r===void 0?K.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=K._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const s in this._ranges)i&&(t+=", ",i=!1),t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new Nl(e,t,i))}deleteRange(e,t=!0){const i=this._ranges[e];if(i){if(t){const s=i.from,r=i.to;for(let n=this._keys.length-1;n>=0;n--)this._keys[n].frame>=s&&this._keys[n].frame<=r&&this._keys.splice(n,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return ge.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,s,r){return ge.Hermite(e,t,i,s,r)}quaternionInterpolateFunction(e,t,i){return Q.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,s,r){return Q.Hermite(e,t,i,s,r).normalize()}vector3InterpolateFunction(e,t,i){return m.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,s,r){return m.Hermite(e,t,i,s,r)}vector2InterpolateFunction(e,t,i){return Z.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,s,r){return Z.Hermite(e,t,i,s,r)}sizeInterpolateFunction(e,t,i){return Dr.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return q.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,s,r){return q.Hermite(e,t,i,s,r)}color4InterpolateFunction(e,t,i){return xe.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,s,r){return xe.Hermite(e,t,i,s,r)}_getKeyValue(e){return typeof e=="function"?e():e}evaluate(e){return on.key=0,this._interpolate(e,on)}_interpolate(e,t,i=!1){if(t.loopMode===K.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e<s[n].frame;)--n;for(;n+1<=r-1&&e>=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],l=s[n+1];if(i&&(e===o.frame||e===l.frame))return;const h=this._getKeyValue(o.value),c=this._getKeyValue(l.value);if(o.interpolation===Kd.STEP)return l.frame>e?h:c;const u=o.outTangent!==void 0&&l.inTangent!==void 0,d=l.frame-o.frame;let f=(e-o.frame)/d;const _=o.easingFunction||this.getEasingFunction();switch(_!==null&&(f=_.ease(f)),this.dataType){case K.ANIMATIONTYPE_FLOAT:{const p=u?this.floatInterpolateFunctionWithTangents(h,o.outTangent*d,c,l.inTangent*d,f):this.floatInterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+p}break}case K.ANIMATIONTYPE_QUATERNION:{const p=u?this.quaternionInterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.quaternionInterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.addInPlace((t.offsetValue||fE).scale(t.repeatCount))}return p}case K.ANIMATIONTYPE_VECTOR3:{const p=u?this.vector3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.vector3InterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||_E).scale(t.repeatCount))}break}case K.ANIMATIONTYPE_VECTOR2:{const p=u?this.vector2InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.vector2InterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||pE).scale(t.repeatCount))}break}case K.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,c,f);case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,c,f).add((t.offsetValue||mE).scale(t.repeatCount))}break}case K.ANIMATIONTYPE_COLOR3:{const p=u?this.color3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.color3InterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||gE).scale(t.repeatCount))}break}case K.ANIMATIONTYPE_COLOR4:{const p=u?this.color4InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.color4InterpolateFunction(h,c,f);switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return p;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||xE).scale(t.repeatCount))}break}case K.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case K.ANIMATIONLOOPMODE_CYCLE:case K.ANIMATIONLOOPMODE_CONSTANT:case K.ANIMATIONLOOPMODE_YOYO:return K.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,c,f,t.workValue):h;case K.ANIMATIONLOOPMODE_RELATIVE:case K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}break}}return 0}matrixInterpolateFunction(e,t,i,s){return K.AllowMatrixDecomposeForInterpolation?s?(D.DecomposeLerpToRef(e,t,i,s),s):D.DecomposeLerp(e,t,i):s?(D.LerpToRef(e,t,i,s),s):D.Lerp(e,t,i)}clone(){const e=new K(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){on.key=0;const t=this._interpolate(e,on,!0);if(!t)return this._keys[on.key].frame===e?on.key:on.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(on.key+1,0,i),on.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s<i.length;s++){const r=i[s],n={};switch(n.frame=r.frame,t){case K.ANIMATIONTYPE_FLOAT:n.values=[r.value],r.inTangent!==void 0&&n.values.push(r.inTangent),r.outTangent!==void 0&&(r.inTangent===void 0&&n.values.push(void 0),n.values.push(r.outTangent)),r.interpolation!==void 0&&(r.inTangent===void 0&&n.values.push(void 0),r.outTangent===void 0&&n.values.push(void 0),n.values.push(r.interpolation));break;case K.ANIMATIONTYPE_QUATERNION:case K.ANIMATIONTYPE_MATRIX:case K.ANIMATIONTYPE_VECTOR3:case K.ANIMATIONTYPE_COLOR3:case K.ANIMATIONTYPE_COLOR4:n.values=r.value.asArray(),r.inTangent!=null&&n.values.push(r.inTangent.asArray()),r.outTangent!=null&&(r.inTangent===void 0&&n.values.push(void 0),n.values.push(r.outTangent.asArray())),r.interpolation!==void 0&&(r.inTangent===void 0&&n.values.push(void 0),r.outTangent===void 0&&n.values.push(void 0),n.values.push(r.interpolation));break}e.keys.push(n)}e.ranges=[];for(const s in this._ranges){const r=this._ranges[s];if(!r)continue;const n={};n.name=s,n.from=r.from,n.to=r.to,e.ranges.push(n)}return e}static _UniversalLerp(e,t,i){const s=e.constructor;return s.Lerp?s.Lerp(e,t,i):s.Slerp?s.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){const t=new K(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),i=e.dataType,s=[];let r,n;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),n=0;n<e.keys.length;n++){const o=e.keys[n];let l,h,c;switch(i){case K.ANIMATIONTYPE_FLOAT:r=o.values[0],o.values.length>=2&&(l=o.values[1]),o.values.length>=3&&(h=o.values[2]),o.values.length>=4&&(c=o.values[3]);break;case K.ANIMATIONTYPE_QUATERNION:if(r=Q.FromArray(o.values),o.values.length>=8){const d=Q.FromArray(o.values.slice(4,8));d.equals(Q.Zero())||(l=d)}if(o.values.length>=12){const d=Q.FromArray(o.values.slice(8,12));d.equals(Q.Zero())||(h=d)}o.values.length>=13&&(c=o.values[12]);break;case K.ANIMATIONTYPE_MATRIX:r=D.FromArray(o.values),o.values.length>=17&&(c=o.values[16]);break;case K.ANIMATIONTYPE_COLOR3:r=q.FromArray(o.values),o.values[3]&&(l=q.FromArray(o.values[3])),o.values[4]&&(h=q.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break;case K.ANIMATIONTYPE_COLOR4:r=xe.FromArray(o.values),o.values[4]&&(l=xe.FromArray(o.values[4])),o.values[5]&&(h=xe.FromArray(o.values[5])),o.values[6]&&(c=xe.FromArray(o.values[6]));break;case K.ANIMATIONTYPE_VECTOR3:default:r=m.FromArray(o.values),o.values[3]&&(l=m.FromArray(o.values[3])),o.values[4]&&(h=m.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break}const u={};u.frame=o.frame,u.value=r,l!=null&&(u.inTangent=l),h!=null&&(u.outTangent=h),c!=null&&(u.interpolation=c),s.push(u)}if(t.setKeys(s),e.ranges)for(n=0;n<e.ranges.length;n++)r=e.ranges[n],t.createRange(r.name,r.from,r.to);return t}static AppendSerializedAnimations(e,t){_e.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise((i,s)=>{const r=new yi;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let n=JSON.parse(r.responseText);if(n.animations&&(n=n.animations),n.length){const o=[];for(const l of n)o.push(this.Parse(l));i(o)}else{const o=this.Parse(n);e&&(o.name=e),i(o)}}else s("Unable to load the animation")}),r.open("GET",t),r.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new yi;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){const r=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(r.animations){const n=JSON.parse(r.animations),o=[];for(const l of n.animations){const h=this.Parse(l);h.snippetId=e,o.push(h)}t(o)}else{const n=JSON.parse(r.animation),o=this.Parse(n);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}K._UniqueIdGenerator=0;K.AllowMatricesInterpolation=!1;K.AllowMatrixDecomposeForInterpolation=!0;K.SnippetUrl="https://snippet.babylonjs.com";K.ANIMATIONTYPE_FLOAT=0;K.ANIMATIONTYPE_VECTOR3=1;K.ANIMATIONTYPE_QUATERNION=2;K.ANIMATIONTYPE_MATRIX=3;K.ANIMATIONTYPE_COLOR3=4;K.ANIMATIONTYPE_COLOR4=7;K.ANIMATIONTYPE_VECTOR2=5;K.ANIMATIONTYPE_SIZE=6;K.ANIMATIONLOOPMODE_RELATIVE=0;K.ANIMATIONLOOPMODE_CYCLE=1;K.ANIMATIONLOOPMODE_CONSTANT=2;K.ANIMATIONLOOPMODE_YOYO=4;K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;K.CreateFromSnippetAsync=K.ParseFromSnippetAsync;V("BABYLON.Animation",K);Ct._AnimationRangeFactory=(a,e,t)=>new Nl(a,e,t);class Tv extends Yt{constructor(e,t,i,s,r=1e3,n,o,l){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new G,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=l,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if(typeof this.value=="number")i=K.ANIMATIONTYPE_FLOAT;else if(this.value instanceof q)i=K.ANIMATIONTYPE_COLOR3;else if(this.value instanceof m)i=K.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof D)i=K.ANIMATIONTYPE_MATRIX;else if(this.value instanceof Q)i=K.ANIMATIONTYPE_QUATERNION;else{O.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const s=new K("InterpolateValueAction",this._property,100*(1e3/this.duration),i,K.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const r=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,r)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Yt._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Yt._SerializeValueAsString(this.value)},{name:"duration",value:Yt._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Yt._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}V("BABYLON.InterpolateValueAction",Tv);class Ev{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===K.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=D.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,this._minFrame!==0){const n={frame:0,value:this._minValue};this._keys.splice(0,0,n)}if(this._target instanceof Array){let n=0;for(const o of this._target)this._preparePath(o,n),this._getOriginalValues(n),n++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach(n=>{this._events.push(n._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e[i[0]];for(let r=1;r<i.length-1;r++)s=s[i[r]];this._targetPath=i[i.length-1],this._activeTargets[t]=s}else this._targetPath=i[0],this._activeTargets[t]=e}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let t=0;for(const i of this._target)this._originalValue[t]!==void 0&&this._setValue(i,this._activeTargets[t],this._originalValue[t],-1,t),t++}else this._originalValue[0]!==void 0&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let t=0;t<this._events.length;t++)this._events[t].isDone=!1}isStopped(){return this._stopped}dispose(){const e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;i<this._target.length;i++){const s=this._target[i];this._setValue(s,this._activeTargets[i],e,t,i)}return}this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;const i=this._activeTargets[e];i.getLocalMatrix&&this._targetPath==="_matrix"?t=i.getLocalMatrix():t=i[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,s,r){if(this._currentActiveTarget=t,this._weight=s,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){const o=t[this._targetPath];o.clone?this._originalBlendValue=o.clone():this._originalBlendValue=o}this._originalBlendValue.m?K.AllowMatrixDecomposeForInterpolation?this._currentValue?D.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=D.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?D.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=D.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=K._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);const n=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=n}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:i!=null&&i.clone?this._currentValue=i.clone():this._currentValue=i;s!==-1?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[r]):this._animationState.loopMode===K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[r],t[this._targetPath]):t[this._targetPath]=this._originalValue[r]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e){const t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let r=0;r<i.length;r++)i[r].onlyOnce||(i[r].isDone=i[r].frame<e);this._currentFrame=e;const s=this._animation._interpolate(e,this._animationState);this.setValue(s,-1)}_prepareForSpeedRatioChange(e){const t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,s,r,n=-1){const o=this._animation,l=o.targetPropertyPath;if(!l||l.length<1)return this._stopped=!0,!1;let h=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,f=0;if(s&&this._animationState.loopMode===K.ANIMATIONLOOPMODE_YOYO){const x=(d-t)/c;d=Math.abs(Math.sin(x*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&(d>=c&&r>0||d<=0&&r<0))h=!1,f=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(d<=c&&r<0||d>=0&&r>0))h=!1,f=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==K.ANIMATIONLOOPMODE_CYCLE){const x=i.toString()+t.toString();if(!this._offsetsCache[x]){this._animationState.repeatCount=0,this._animationState.loopMode=K.ANIMATIONLOOPMODE_CYCLE;const T=o._interpolate(t,this._animationState),S=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case K.ANIMATIONTYPE_FLOAT:this._offsetsCache[x]=S-T;break;case K.ANIMATIONTYPE_QUATERNION:this._offsetsCache[x]=S.subtract(T);break;case K.ANIMATIONTYPE_VECTOR3:this._offsetsCache[x]=S.subtract(T);break;case K.ANIMATIONTYPE_VECTOR2:this._offsetsCache[x]=S.subtract(T);break;case K.ANIMATIONTYPE_SIZE:this._offsetsCache[x]=S.subtract(T);break;case K.ANIMATIONTYPE_COLOR3:this._offsetsCache[x]=S.subtract(T);break}this._highLimitsCache[x]=S}f=this._highLimitsCache[x],u=this._offsetsCache[x]}if(u===void 0)switch(o.dataType){case K.ANIMATIONTYPE_FLOAT:u=0;break;case K.ANIMATIONTYPE_QUATERNION:u=fE;break;case K.ANIMATIONTYPE_VECTOR3:u=_E;break;case K.ANIMATIONTYPE_VECTOR2:u=pE;break;case K.ANIMATIONTYPE_SIZE:u=mE;break;case K.ANIMATIONTYPE_COLOR3:u=gE;break;case K.ANIMATIONTYPE_COLOR4:u=xE;break}let _;if(this._host&&this._host.syncRoot){const x=this._host.syncRoot,T=(x.masterFrame-x.fromFrame)/(x.toFrame-x.fromFrame);_=t+c*T}else d>0&&t>i||d<0&&t<i?_=h&&c!==0?i+d%c:t:_=h&&c!==0?t+d%c:i;const p=this._events;if(r>0&&this.currentFrame>_||r<0&&this.currentFrame<_){this._onLoop();for(let x=0;x<p.length;x++)p[x].onlyOnce||(p[x].isDone=!1);this._animationState.key=r>0?0:o.getKeys().length-1}this._currentFrame=_,this._animationState.repeatCount=c===0?0:d/c>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const g=o._interpolate(_,this._animationState);if(this.setValue(g,n),p.length){for(let x=0;x<p.length;x++)if(c>=0&&_>=p[x].frame&&p[x].frame>=t||c<0&&_<=p[x].frame&&p[x].frame<=t){const T=p[x];T.isDone||(T.onlyOnce&&(p.splice(x,1),x--),T.isDone=!0,T.action(_))}}return h||(this._stopped=!0),h}}function ls(){return typeof window<"u"}function Hc(){return typeof navigator<"u"}function jc(){return typeof document<"u"}function dm(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}class Zi{static get Now(){return ls()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class qc{}qc.FilesToLoad={};class Sv{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>s.status!==0||r>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,r)*t}}class Fl extends Error{}Fl._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const ca={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Sn extends Fl{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Fl._setPrototypeOf(this,Sn.prototype)}}const Cv=a=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(a);let e="";for(let t=0;t<a.byteLength;t++)e+=String.fromCharCode(a[t]);return e},TE=a=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,o,l,h,c=0;const u=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);for(;c<u.length;)i=u[c++],s=c<u.length?u[c++]:Number.NaN,r=c<u.length?u[c++]:Number.NaN,n=i>>2,o=(i&3)<<4|s>>4,l=(s&15)<<2|r>>6,h=r&63,isNaN(s)?l=h=64:isNaN(r)&&(h=64),t+=e.charAt(n)+e.charAt(o)+e.charAt(l)+e.charAt(h);return t},EE=a=>atob(a),vv=a=>{const e=EE(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s<t;s++)i[s]=e.charCodeAt(s);return i.buffer},bv="attribute",Av="varying";class Qc{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var s,r,n,o,l,h;let i="";if(this.line){let c=this.line;const u=t.processor;if(u){u.lineProcessor&&(c=u.lineProcessor(c,t.isFragment,t.processingContext));const d=((s=t.processor)==null?void 0:s.attributeKeywordName)??bv,f=t.isFragment&&((r=t.processor)!=null&&r.varyingFragmentKeywordName)?(n=t.processor)==null?void 0:n.varyingFragmentKeywordName:!t.isFragment&&((o=t.processor)!=null&&o.varyingVertexKeywordName)?(l=t.processor)==null?void 0:l.varyingVertexKeywordName:Av;!t.isFragment&&u.attributeProcessor&&this.line.startsWith(d)?c=u.attributeProcessor(this.line,e,t.processingContext):u.varyingProcessor&&((h=u.varyingCheck)!=null&&h.call(u,this.line,t.isFragment)||!u.varyingCheck&&this.line.startsWith(f))?c=u.varyingProcessor(this.line,t.isFragment,e,t.processingContext):u.uniformProcessor&&u.uniformRegexp&&u.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&u.uniformBufferRegexp&&u.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):u.textureProcessor&&u.textureRegexp&&u.textureRegexp.test(this.line)?c=u.textureProcessor(this.line,t.isFragment,e,t.processingContext):(u.uniformProcessor||u.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?u.uniformProcessor&&(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,u.endOfUniformBufferProcessor&&(c=u.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=c+`
`}return this.children.forEach(c=>{i+=c.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class yv{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if(!t||t==="\r")continue;if(t[0]==="#"){this._lines.push(t);continue}const i=t.trim();if(!i)continue;if(i.startsWith("//")){this._lines.push(t);continue}const s=i.indexOf(";");if(s===-1)this._lines.push(i);else if(s===i.length-1)i.length>1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n<r.length;n++){let o=r[n];o&&(o=o.trim(),o&&this._lines.push(o+(n!==r.length-1?";":"")))}}}}}class A_ extends Qc{process(e,t){for(let i=0;i<this.children.length;i++){const s=this.children[i];if(s.isValid(e))return s.process(e,t)}return""}}class Rv extends Qc{isValid(e){return this.testExpression.isTrue(e)}}class bi{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const i of e)if(bi._OperatorPriority[i]===void 0)t.push(i);else{const s=t[t.length-1],r=t[t.length-2];t.length-=2,t.push(`(${r}${i}${s})`)}return t[t.length-1]}static infixToPostfix(e){const t=bi._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];const i=[];let s=-1;const r=()=>{c=c.trim(),c!==""&&(i.push(c),c="")},n=u=>{s<bi._Stack.length-1&&(bi._Stack[++s]=u)},o=()=>bi._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":bi._Stack[s--];let h=0,c="";for(;h<e.length;){const u=e.charAt(h),d=h<e.length-1?e.substr(h,2):"";if(u==="(")c="",n(u);else if(u===")"){for(r();s!==-1&&o()!=="(";)i.push(l());l()}else if(bi._OperatorPriority[d]>1){for(r();s!==-1&&bi._OperatorPriority[o()]>=bi._OperatorPriority[d];)i.push(l());n(d),h++}else c+=u;h++}for(r();s!==-1;)o()==="("?l():i.push(l());return bi._InfixToPostfixCache.size>=bi.InfixToPostfixCacheLimitSize&&bi.ClearCache(),bi._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(bi._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t<bi.InfixToPostfixCacheCleanupSize;t++)bi._InfixToPostfixCache.delete(e[t][0])}}bi.InfixToPostfixCacheLimitSize=5e4;bi.InfixToPostfixCacheCleanupSize=25e3;bi._InfixToPostfixCache=new Map;bi._OperatorPriority={")":0,"(":1,"||":2,"&&":3};bi._Stack=["","","","","","","","","","","","","","","","","","","",""];class Ad extends bi{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}class Iv extends bi{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class Pv extends bi{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class Mv extends bi{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];t===void 0&&(t=this.define);let i=!1;const s=parseInt(t),r=parseInt(this.testValue);switch(this.operand){case">":i=s>r;break;case"<":i=s<r;break;case"<=":i=s<=r;break;case">=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r;break}return i}}var Zt;(function(a){a[a.GLSL=0]="GLSL",a[a.WGSL=1]="WGSL"})(Zt||(Zt={}));const Dv=/defined\s*?\((.+?)\)/g,y_=/defined\s*?\[(.+?)\]/g,Ov=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Nv=/__decl__/,qg=/light\{X\}.(\w*)/g,Qg=/\{X\}/g,yd=[];class Fr{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,s){var r;(r=t.processor)!=null&&r.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,n=>{t.processCodeAfterIncludes&&(n=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",n));const o=this._ProcessShaderConversion(n,t,s);i(o,n)})}static PreProcess(e,t,i,s){var r;(r=t.processor)!=null&&r.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,n=>{t.processCodeAfterIncludes&&(n=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",n));const o=this._ApplyPreProcessing(n,t,s);i(o,n)})}static Finalize(e,t,i){return!i.processor||!i.processor.finalizeShaders?{vertexCode:e,fragmentCode:t}:i.processor.finalizeShaders(e,t,i.processingContext)}static _ProcessPrecision(e,t){var s;if((s=t.processor)!=null&&s.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return e.indexOf("precision highp float")===-1?i?e=`precision highp float;
`+e:e=`precision mediump float;
`+e:i||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const i=/defined\((.+)\)/.exec(e);if(i&&i.length)return new Ad(i[1].trim(),e[0]==="!");const s=["==","!=",">=","<=","<",">"];let r="",n=0;for(r of s)if(n=e.indexOf(r),n>-1)break;if(n===-1)return new Ad(e);const o=e.substring(0,n).trim(),l=e.substring(n+r.length).trim();return new Mv(o,r,l)}static _BuildSubExpression(e){e=e.replace(Dv,"defined[$1]");const t=bi.infixToPostfix(e),i=[];for(const r of t)if(r!=="||"&&r!=="&&")i.push(r);else if(i.length>=2){let n=i[i.length-1],o=i[i.length-2];i.length-=2;const l=r=="&&"?new Pv:new Iv;typeof n=="string"&&(n=n.replace(y_,"defined($1)")),typeof o=="string"&&(o=o.replace(y_,"defined($1)")),l.leftOperand=typeof o=="string"?this._ExtractOperation(o):o,l.rightOperand=typeof n=="string"?this._ExtractOperation(n):n,i.push(l)}let s=i[i.length-1];return typeof s=="string"&&(s=s.replace(y_,"defined($1)")),typeof s=="string"?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new Rv,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),s==="#ifdef"?i.testExpression=new Ad(r):s==="#ifndef"?i.testExpression=new Ad(r,!0):i.testExpression=this._BuildSubExpression(r),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if(r==="#else"){const n=new Qc;t.children.push(n),this._MoveCursor(e,n);return}else if(r==="#elif"){const n=this._BuildExpression(s,5);t.children.push(n),i=n}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const r=Fr._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const o=new A_;t.children.push(o);const l=this._BuildExpression(i,6);o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const o=new A_;t.children.push(o);const l=this._BuildExpression(i,7);o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}case"#if":{const o=new A_,l=this._BuildExpression(i,3);t.children.push(o),o.children.push(l),this._MoveCursorWithinIf(e,o,l);break}}continue}}const s=new Qc;if(s.line=i,t.children.push(s),i[0]==="#"&&i[1]==="d"){const r=i.replace(";","").split(" ");s.additionalDefineKey=r[1],r.length===3&&(s.additionalDefineValue=r[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const s=new Qc,r=new yv;return r.lineIndex=-1,r.lines=e.split(`
`),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){var r;const i=e.defines,s={};for(const n of i){const l=n.replace("#define","").replace(";","").trim().split(" ");s[l[0]]=l.length>1?l[1]:""}return((r=e.processor)==null?void 0:r.shaderLanguage)===Zt.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===Zt.GLSL&&s.indexOf("#version 3")!==-1&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ApplyPreProcessing(e,t,i){var o,l;let s=e;const r=t.defines,n=this._PreparePreProcessors(t,i);return(o=t.processor)!=null&&o.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),(l=t.processor)!=null&&l.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ProcessIncludes(e,t,i){yd.length=0;let s;for(;(s=Ov.exec(e))!==null;)yd.push(s);let r=String(e),n=[e],o=!1;for(const l of yd){let h=l[1];if(h.indexOf("__decl__")!==-1&&(h=h.replace(Nv,""),t.supportsUniformBuffers&&(h=h.replace("Vertex","Ubo").replace("Fragment","Ubo")),h=h+"Declaration"),t.includesShadersStore[h]){let c=t.includesShadersStore[h];if(l[2]){const d=l[3].split(",");for(let f=0;f<d.length;f+=2){const _=new RegExp(d[f],"g"),p=d[f+1];c=c.replace(_,p)}}if(l[4]){const d=l[5];if(d.indexOf("..")!==-1){const f=d.split(".."),_=parseInt(f[0]);let p=parseInt(f[1]),g=c.slice(0);c="",isNaN(p)&&(p=t.indexParameters[f[1]]);for(let x=_;x<p;x++)t.supportsUniformBuffers||(g=g.replace(qg,(T,S)=>S+"{X}")),c+=g.replace(Qg,x.toString())+`
`}else t.supportsUniformBuffers||(c=c.replace(qg,(f,_)=>_+"{X}")),c=c.replace(Qg,d)}const u=[];for(const d of n){const f=d.split(l[0]);for(let _=0;_<f.length-1;_++)u.push(f[_]),u.push(c);u.push(f[f.length-1])}n=u,o=o||c.indexOf("#include<")>=0||c.indexOf("#include <")>=0}else{const c=t.shadersRepository+"ShadersInclude/"+h+".fx";Fr._FileToolsLoadFile(c,u=>{t.includesShadersStore[h]=u,this._ProcessIncludes(n.join(""),t,i)});return}}yd.length=0,r=n.join(""),o?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw Ge("FileTools")}}Fr._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class W{static GetShadersRepository(e=Zt.GLSL){return e===Zt.GLSL?W.ShadersRepository:W.ShadersRepositoryWGSL}static GetShadersStore(e=Zt.GLSL){return e===Zt.GLSL?W.ShadersStore:W.ShadersStoreWGSL}static GetIncludesShadersStore(e=Zt.GLSL){return e===Zt.GLSL?W.IncludesShadersStore:W.IncludesShadersStoreWGSL}}W.ShadersRepository="src/Shaders/";W.ShadersStore={};W.IncludesShadersStore={};W.ShadersRepositoryWGSL="src/ShadersWGSL/";W.ShadersStoreWGSL={};W.IncludesShadersStoreWGSL={};class xt{static get ShadersRepository(){return W.ShadersRepository}static set ShadersRepository(e){W.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new G),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,l=null,h=null,c,u="",d=Zt.GLSL){if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new G,this.onErrorObservable=new G,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u,t.attributes){const f=t;if(this._engine=i,this._attributesNames=f.attributes,this._uniformsNames=f.uniformsNames.concat(f.samplers),this._samplerList=f.samplers.slice(),this.defines=f.defines,this.onError=f.onError,this.onCompiled=f.onCompiled,this._fallbacks=f.fallbacks,this._indexParameters=f.indexParameters,this._transformFeedbackVaryings=f.transformFeedbackVaryings||null,this._multiTarget=!!f.multiTarget,this._shaderLanguage=f.shaderLanguage??Zt.GLSL,f.uniformBuffersNames){this._uniformBuffersNamesList=f.uniformBuffersNames.slice();for(let _=0;_<f.uniformBuffersNames.length;_++)this._uniformBuffersNames[f.uniformBuffersNames[_]]=_}this._processFinalCode=f.processFinalCode??null,this._processCodeAfterIncludes=f.processCodeAfterIncludes??void 0}else this._engine=r,this.defines=n??"",this._uniformsNames=i.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=d,this.onError=h,this.onCompiled=l,this._indexParameters=c,this._fallbacks=o;this._attributeLocationByName={},this.uniqueId=xt._UniqueIdSeed++,this._processShaderCode()}_processShaderCode(e=null,t=!1){let i,s;const r=this.name,n=ls()?this._engine.getHostDocument():null;r.vertexSource?i="source:"+r.vertexSource:r.vertexElement?(i=n?n.getElementById(r.vertexElement):null,i||(i=r.vertexElement)):i=r.vertex||r,r.fragmentSource?s="source:"+r.fragmentSource:r.fragmentElement?(s=n?n.getElementById(r.fragmentElement):null,s||(s=r.fragmentElement)):s=r.fragment||r,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);let o={defines:this.defines.split(`
`),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:W.GetShadersRepository(this._shaderLanguage),includesShadersStore:W.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes};const l=[void 0,void 0],h=()=>{if(l[0]&&l[1]){o.isFragment=!0;const[c,u]=l;Fr.Process(u,o,(d,f)=>{this._fragmentSourceCodeBeforeMigration=f,this._processFinalCode&&(d=this._processFinalCode("fragment",d));const _=Fr.Finalize(c,d,o);o=null,this._useFinalCode(_.vertexCode,_.fragmentCode,r,t)},this._engine)}};this._loadShader(i,"Vertex","",c=>{Fr.Initialize(o),Fr.Process(c,o,(u,d)=>{this._rawVertexSourceCode=c,this._vertexSourceCodeBeforeMigration=d,this._processFinalCode&&(u=this._processFinalCode("vertex",u)),l[0]=u,h()},this._engine)}),this._loadShader(s,"Fragment","Pixel",c=>{this._rawFragmentSourceCode=c,l[1]=c,h()})}_useFinalCode(e,t,i,s=!1){if(i){const r=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===Zt.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+`
`+e,this._fragmentSourceCode=(this._shaderLanguage===Zt.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+`
`+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(s)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const o=dm(e);s(o);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const o=window.atob(e.substr(7));s(o);return}const r=W.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"]){s(r[e+t+"Shader"]);return}if(i&&r[e+i+"Shader"]){s(r[e+i+"Shader"]);return}let n;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?n=e:n=W.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())??this._vertexSourceCode}get fragmentSourceCode(){var e;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{var n,o;const r=this.getEngine().scenes;if(r)for(let l=0;l<r.length;l++)r[l].markAllMaterialsAsDirty(63);(o=(n=this._pipelineContext)._handlesSpectorRebuildCallback)==null||o.call(n,i)},this._fallbacks=null,this._prepareEffect()}_prepareEffect(e=!1){const t=this._attributesNames,i=this.defines,s=this._pipelineContext;this._isReady=!1;try{const r=this._engine;this._pipelineContext=(e?s:void 0)??r.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key.replace(/\r/g,"").replace(/\n/g,"|");const n=(o,l,h,c)=>this._rebuildProgram(o,l,h,c);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?r._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,null,this._transformFeedbackVaryings,this._key):r._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,i,this._transformFeedbackVaryings,this._key),r._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,t,this._attributes),t)for(let o=0;o<t.length;o++){const l=t[o];this._attributeLocationByName[l]=this._attributes[o]}r.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),s&&!e&&this.getEngine()._deletePipelineContext(s)}),this._pipelineContext.isAsync&&this._checkIsReady(s)}catch(r){this._processCompilationErrors(r,s)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&n.length===2){const o=parseInt(n[1]),l=e.split(`
`,-1);l.length>=o&&(r=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var n,o,l;this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(O.Error("Unable to compile effect:"),O.Error("Uniforms: "+this._uniformsNames.map(function(h){return" "+h})),O.Error("Attributes: "+i.map(function(h){return" "+h})),O.Error(`Defines:
`+this.defines),xt.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;(n=this._pipelineContext)!=null&&n._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(O.Error("Vertex code:"),O.Error(u))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),u&&(O.Error("Fragment code:"),O.Error(u))),h&&O.Error(h),c&&O.Error(c)}O.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,O.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const s=this._samplerList.indexOf(e);for(let n=1;n<t.length;n++){const o=i+(n-1).toString();this._samplerList.splice(s+n,0,o)}let r=0;for(const n of this._samplerList)this._samplers[n]=r,r+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}setTextureFromPostProcess(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)}setTextureFromPostProcessOutput(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)}bindUniformBuffer(e,t){const i=this._uniformBuffersNames[t];i===void 0||xt._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(xt._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,s){return this._pipelineContext.setInt3(e,t,i,s),this}setInt4(e,t,i,s,r){return this._pipelineContext.setInt4(e,t,i,s,r),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,s){return this._pipelineContext.setUInt3(e,t,i,s),this}setUInt4(e,t,i,s,r){return this._pipelineContext.setUInt4(e,t,i,s,r),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,s){return this._pipelineContext.setFloat3(e,t,i,s),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,s,r){return this._pipelineContext.setFloat4(e,t,i,s,r),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,s=Zt.GLSL){t&&(W.GetShadersStore(s)[`${e}PixelShader`]=t),i&&(W.GetShadersStore(s)[`${e}VertexShader`]=i)}static ResetCache(){xt._BaseCache={}}}xt.LogShaderCodeOnCompilationError=!0;xt._UniqueIdSeed=0;xt._BaseCache={};xt.ShadersStore=W.ShadersStore;xt.IncludesShadersStore=W.IncludesShadersStore;class SE{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class aa{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=aa.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=aa.KEEP,this.opDepthFail=aa.KEEP,this.opStencilDepthPass=aa.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}aa.ALWAYS=519;aa.KEEP=7680;aa.REPLACE=7681;class Fv{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,s){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===s||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,s){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===s||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=s,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}class CE{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,s=1,r=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=r,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var et;(function(a){a[a.Unknown=0]="Unknown",a[a.Url=1]="Url",a[a.Temp=2]="Temp",a[a.Raw=3]="Raw",a[a.Dynamic=4]="Dynamic",a[a.RenderTarget=5]="RenderTarget",a[a.MultiRenderTarget=6]="MultiRenderTarget",a[a.Cube=7]="Cube",a[a.CubeRaw=8]="CubeRaw",a[a.CubePrefiltered=9]="CubePrefiltered",a[a.Raw3D=10]="Raw3D",a[a.Raw2DArray=11]="Raw2DArray",a[a.DepthStencil=12]="DepthStencil",a[a.CubeRawRGBD=13]="CubeRawRGBD",a[a.Depth=14]="Depth"})(et||(et={}));class Tt extends CE{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new G,this.onErrorObservable=new G,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=et.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=Tt._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const t=this.onRebuildCallback(this),i=s=>{s._swapAndDie(this,!1),this.isReady=t.isReady};t.isAsync?t.proxy.then(i):i(t.proxy);return}let e;switch(this.source){case et.Temp:break;case et.Url:e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,t=>{t._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case et.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case et.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case et.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case et.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case et.Cube:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case et.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case et.CubeRawRGBD:return;case et.CubePrefiltered:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,t=>{t&&t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return;case et.DepthStencil:case et.Depth:break}}_swapAndDie(e,t=!0){var r;(r=this._hardwareTexture)==null||r.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);s!==-1&&i.splice(s,1),s=i.indexOf(e),s===-1&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Tt._Counter=0;class wv{constructor(){this.shaderLanguage=Zt.GLSL}postProcessor(e,t,i,s,r){if(!r.getCaps().drawBuffersExtension){const n=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(n,"")}return e}}const Lv=/(flat\s)?\s*varying\s*.*/;class vE{constructor(){this.shaderLanguage=Zt.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Lv.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,r=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(r,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const n=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(s||n?"":`layout(location = 0) out vec4 glFragColor;
`)+"void main(")}else if(t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
`+e;return e}}class ko{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=ko._Counter++}}ko._Counter=0;class Eu extends ko{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Bv{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,s,r,n,o,l){const h=this.engine;if(h.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,f)=>{s[i[f]]=d}),this._uniforms=s;let u;for(u=0;u<r.length;u++)e.getUniform(r[u])==null&&(r.splice(u,1),u--);r.forEach((d,f)=>{n[d]=f});for(const d of h.getAttributes(this,o))l.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||r.length!==3)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||n.length!==4)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}class Ec{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t;return((t=this._MSAARenderBuffers)==null?void 0:t[e])??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Bi{static IsWrapper(e){return e.getPipelineContext===void 0}static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var s;this.effect=e,t!==void 0&&(this.defines=t),i&&((s=this.drawContext)==null||s.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}class bE{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;const t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class Uv{}class pe{static get NpmPackage(){return"babylonjs@6.49.0"}static get Version(){return"6.49.0"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return xt.ShadersRepository}static set ShadersRepository(e){xt.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if(typeof document>"u")return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return pe._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){var h,c;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new G,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new G,this.onContextRestoredObservable=new G,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new SE,this._stencilStateComposer=new bE,this._stencilState=new aa,this._alphaState=new Fv,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._boundRenderFunction=()=>this._renderLoop(),this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._frameHandler=0,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new G,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=Zi.Now;let r=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,gs.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=i.deterministicLockstep??!1,i.lockstepMaxSteps=i.lockstepMaxSteps??4,i.timeStep=i.timeStep??1/60,i.audioEngine=i.audioEngine??!0,i.stencil=i.stencil??!0,this._audioContext=((h=i.audioEngineOptions)==null?void 0:h.audioContext)??null,this._audioDestination=((c=i.audioEngineOptions)==null?void 0:c.audioDestination)??null,this.premultipliedAlpha=i.premultipliedAlpha??!0,this.useExactSrgbConversions=i.useExactSrgbConversions??!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const n=ls()&&window.devicePixelRatio||1,o=i.limitDeviceRatio||n;if(this._hardwareScalingLevel=s?1/Math.min(o,n):1,this._lastDevicePixelRatio=n,!e)return;if(e.getContext){if(r=e,this._renderingCanvas=r,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const u=navigator.userAgent;for(const d of pe.ExceptionList){const f=d.key,_=d.targets;if(new RegExp(f).test(u)){if(d.capture&&d.captureConstraint){const g=d.capture,x=d.captureConstraint,S=new RegExp(g).exec(u);if(S&&S.length>0&&parseInt(S[S.length-1])>=x)continue}for(const g of _)switch(g){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost||(this._onContextLost=u=>{u.preventDefault(),this._contextWasLost=!0,O.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch{throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const u=this._gl.getContextAttributes();u&&(i.stencil=u.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let u=0;u<this._caps.maxVertexAttribs;u++)this._currentBufferPointers[u]=new Uv;this._shaderProcessor=this.webGLVersion>1?new vE:new wv,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const l=`Babylon.js v${pe.Version}`;O.Log(l+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",l)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&jc()&&"ontouchend"in document},this._checkForMobile(),ls()&&window.addEventListener("resize",this._checkForMobile))}_clearEmptyResources(){this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){O.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}xt.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const t=this._gl.getExtension("WEBGL_draw_buffers");if(t!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const t=this._gl.getExtension("WEBGL_depth_texture");t!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=t.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const t=this._gl.getExtension("OES_vertex_array_object");t!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=t.createVertexArrayOES.bind(t),this._gl.bindVertexArray=t.bindVertexArrayOES.bind(t),this._gl.deleteVertexArray=t.deleteVertexArrayOES.bind(t))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const t=this._gl.getExtension("ANGLE_instanced_arrays");t!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=t.drawArraysInstancedANGLE.bind(t),this._gl.drawElementsInstanced=t.drawElementsInstancedANGLE.bind(t),this._gl.vertexAttribDivisor=t.vertexAttribDivisorANGLE.bind(t)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const t=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),i=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);t&&i&&(this._caps.highPrecisionShaderSupported=t.precision!==0&&i.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const t=this._gl.getExtension("EXT_blend_minmax");t!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=t.MAX_EXT,this._gl.MIN=t.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const t=this._gl.getExtension("EXT_sRGB");t!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:t.SRGB_EXT,SRGB8:t.SRGB_ALPHA_EXT,SRGB8_ALPHA8:t.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let t=0;t<this._maxSimultaneousTextures;t++)this._nextFreeTextureSlots.push(t);this._glRenderer==="Mali-G72"&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:typeof HTMLImageElement>"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,ls()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t<this._activeRenderLoops.length;t++){const i=this._activeRenderLoops[t];i()}this.endFrame()}}this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return ls()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}_queueNewFrame(e,t){return pe.QueueNewFrame(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._activeRenderLoops.length===1&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,s=!1){var o,l;const r=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=r;let n=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const c=(o=this._currentRenderTarget.texture)==null?void 0:o.format;if(c===8||c===9||c===10||c===11){const u=(l=this._currentRenderTarget.texture)==null?void 0:l.type;u===7||u===5?(pe._TempClearColorUint32[0]=e.r*255,pe._TempClearColorUint32[1]=e.g*255,pe._TempClearColorUint32[2]=e.b*255,pe._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,pe._TempClearColorUint32),h=!1):(pe._TempClearColorInt32[0]=e.r*255,pe._TempClearColorInt32[1]=e.g*255,pe._TempClearColorInt32[2]=e.b*255,pe._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,pe._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),n|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)}_viewport(e,t,i,s){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}setViewport(e,t,i){const s=t||this.getRenderWidth(),r=i||this.getRenderHeight(),n=e.x||0,o=e.y||0;this._cachedViewport=e,this._viewport(n*s,o*r,s*e.width,r*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=ls()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(ls()&&jc())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||s.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||s.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){return!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)?!1:(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0)}bindFramebuffer(e,t=0,i,s,r,n=0,o=0){var u,d,f,_,p,g;const l=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(l._MSAAFramebuffer?l._MSAAFramebuffer:l._framebuffer);const h=this._gl;e.isMulti||(e.is2DArray?h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,(u=e.texture._hardwareTexture)==null?void 0:u.underlyingResource,n,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,n):l._currentLOD!==n&&(h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,(f=e.texture._hardwareTexture)==null?void 0:f.underlyingResource,n),l._currentLOD=n));const c=e._depthStencilTexture;if(c){const x=e._depthStencilTextureWithStencil?h.DEPTH_STENCIL_ATTACHMENT:h.DEPTH_ATTACHMENT;e.is2DArray?h.framebufferTextureLayer(h.FRAMEBUFFER,x,(_=c._hardwareTexture)==null?void 0:_.underlyingResource,n,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,x,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(p=c._hardwareTexture)==null?void 0:p.underlyingResource,n):h.framebufferTexture2D(h.FRAMEBUFFER,x,h.TEXTURE_2D,(g=c._hardwareTexture)==null?void 0:g.underlyingResource,n)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,n&&(i=i/Math.pow(2,n))),s||(s=e.height,n&&(s=s/Math.pow(2,n))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,r,n,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=this.cullBackFaces??r??!0?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const h=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==h||i)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var n;const s=e;this._currentRenderTarget=null;const r=this._gl;if(s._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}r.bindFramebuffer(r.READ_FRAMEBUFFER,s._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,s._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}(n=e.texture)!=null&&n.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const s=new Eu(i);return this.bindArrayBuffer(s),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),r=new Eu(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=n.BYTES_PER_ELEMENT===4,r}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i<e.length;i++)if(e[i]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const l=this._currentBufferPointers[t];if(!l)return;let h=!1;l.active?(l.buffer!==e&&(l.buffer=e,h=!0),l.size!==i&&(l.size=i,h=!0),l.type!==s&&(l.type=s,h=!0),l.normalized!==r&&(l.normalized=r,h=!0),l.stride!==n&&(l.stride=n,h=!0),l.offset!==o&&(l.offset=o,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=r,l.stride=n,l.offset=o,l.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r<s.length;r++){const n=t.getAttributeLocation(r);if(n>=0){const o=s[r];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const h=l.getBuffer();h&&(this._vertexAttribPointer(h,n,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(h))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const n=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l<n;l++)if(l<i.length){const h=r.getAttributeLocation(l);h>=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,i[l],this._gl.FLOAT,!1,s,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){const s=this._currentInstanceBuffers[t];e!=s&&s.references&&(e=s,this.bindArrayBuffer(s));const r=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(r,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,e.references===0?(this._deleteBuffer(e),!0):!1}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),i[0].index!==void 0)this.bindInstancesBuffer(e,i,!0);else for(let s=0;s<4;s++){const r=i[s];this._vertexAttribArraysEnabled[r]||(this._gl.enableVertexAttribArray(r),this._vertexAttribArraysEnabled[r]=!0),this._vertexAttribPointer(e,r,4,this._gl.FLOAT,!1,64,s*16),this._gl.vertexAttribDivisor(r,1),this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let s=0;if(i)for(let r=0;r<t.length;r++){const n=t[r];s+=n.attributeSize*4}for(let r=0;r<t.length;r++){const n=t[r];n.index===void 0&&(n.index=this._currentEffect.getAttributeLocationByName(n.attributeName)),!(n.index<0)&&(this._vertexAttribArraysEnabled[n.index]||(this._gl.enableVertexAttribArray(n.index),this._vertexAttribArraysEnabled[n.index]=!0),this._vertexAttribPointer(e,n.index,n.attributeSize,n.attributeType||this._gl.FLOAT,n.normalized||!1,s,n.offset),this._gl.vertexAttribDivisor(n.index,n.divisor===void 0?1:n.divisor),this._currentInstanceLocations.push(n.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t=!1,i;for(;(i=this._currentInstanceLocations.indexOf(e))!==-1;)this._currentInstanceLocations.splice(i,1),this._currentInstanceBuffers.splice(i,1),t=!0,i=this._currentInstanceLocations.indexOf(e);t&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,s){this.drawElementsType(e?0:1,t,i,s)}drawPointClouds(e,t,i){this.drawArraysType(2,e,t,i)}drawUnIndexed(e,t,i,s){this.drawArraysType(e?0:1,t,i,s)}drawElementsType(e,t,i,s){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;s?this._gl.drawElementsInstanced(r,i,n,t*o,s):this._gl.drawElements(r,i,n,t*o)}drawArraysType(e,t,i,s){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e);s?this._gl.drawArraysInstanced(r,t,i,s):this._gl.drawArrays(r,t,i)}_drawMode(e){switch(e){case 0:return this._gl.TRIANGLES;case 2:return this._gl.POINTS;case 1:return this._gl.LINES;case 3:return this._gl.POINTS;case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_reportDrawCall(){}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(t.program))}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=`
`),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+=`
`),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}createEffect(e,t,i,s,r,n,o,l,h,c=Zt.GLSL){const u=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,f=this._getGlobalDefines();let _=r??t.defines??"";f&&(_+=f);const p=u+"+"+d+"@"+_;if(this._compiledEffects[p]){const x=this._compiledEffects[p];return o&&x.isReady()&&o(x),x}const g=new xt(e,t,i,s,this,r,n,o,l,h,p,c);return this._compiledEffects[p]=g,g}static _ConcatenateShader(e,t,i=""){return i+(t?t+`
`:"")+e}_compileShader(e,t,i,s){return this._compileRawShader(pe._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"),o=this._compileRawShader(i,"fragment");return this._createShaderProgram(e,n,o,s,r)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl;const o=this._webGLVersion>1?`#version 300 es
#define WEBGL2 
`:"",l=this._compileShader(t,"vertex",s,o),h=this._compileShader(i,"fragment",s,o);return this._createShaderProgram(e,l,h,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new Bv;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 l=this._gl.getShaderInfoLog(i);if(l)throw e.vertexCompilationError=l,new Error("VERTEX SHADER "+l)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const l=this._gl.getShaderInfoLog(s);if(l)throw e.fragmentCompilationError=l,new Error("FRAGMENT SHADER "+l)}const o=t.getProgramInfoLog(r);if(o)throw e.programLinkError=o,new Error(o)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const l=t.getProgramInfoLog(r);if(l)throw e.programValidationError=l,new Error(l)}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,o,l,h,c){const u=e;s?u.program=this.createRawShaderProgram(u,t,i,void 0,h):u.program=this.createShaderProgram(u,t,i,l,void 0,h),u.program.__SPECTOR_rebuildProgram=o}_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&&Bi.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 Ec(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,s=et.Unknown){let r=!1,n=0,o=3,l=5,h=!1,c=1,u;t!==void 0&&typeof t=="object"?(r=!!t.generateMipMaps,n=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,l=t.format===void 0?5:t.format,h=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,c=t.samples??1,u=t.label):r=!!t,h&&(h=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(n===1&&!this._caps.textureFloatLinearFiltering||n===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),n===1&&!this._caps.textureFloat&&(n=0,O.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,f=new Tt(this,s),_=e.width||e,p=e.height||e,g=e.layers||0,x=this._getSamplingParameters(o,r),T=g!==0?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(n,l,h),C=this._getInternalFormat(l),v=this._getWebGLTextureType(n);return this._bindTextureDirectly(T,f),g!==0?(f.is2DArray=!0,d.texImage3D(T,0,S,_,p,g,0,C,v,null)):d.texImage2D(T,0,S,_,p,0,C,v,null),d.texParameteri(T,d.TEXTURE_MAG_FILTER,x.mag),d.texParameteri(T,d.TEXTURE_MIN_FILTER,x.min),d.texParameteri(T,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(T,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),r&&this._gl.generateMipmap(T),this._bindTextureDirectly(T,null),f._useSRGBBuffer=h,f.baseWidth=_,f.baseHeight=p,f.width=_,f.height=p,f.depth=g,f.isReady=!0,f.samples=c,f.generateMipMaps=r,f.samplingMode=o,f.type=n,f.format=l,f.label=u,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,o=null,l,h,c=null,u=null,d=null,f=null,_,p,g){e=e||"";const x=e.substr(0,5)==="data:",T=e.substr(0,5)==="blob:",S=x&&e.indexOf(";base64,")!==-1,C=u||new Tt(this,et.Url);C!==u&&(C.label=e.substring(0,60));const v=e;this._transformTextureUrl&&!S&&!u&&!c&&(e=this._transformTextureUrl(e)),v!==e&&(C._originalUrl=v);const b=e.lastIndexOf(".");let A=f||(b>-1?e.substring(b).toLowerCase():""),P=null;A.indexOf("?")>-1&&(A=A.split("?")[0]);for(const J of pe._TextureLoaders)if(J.canLoad(A,_)){P=J;break}s&&s.addPendingData(C),C.url=e,C.generateMipMaps=!t,C.samplingMode=r,C.invertY=i,C._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(C._buffer=c);let w=null;n&&!u&&(w=C.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(C);const $=(J,ne)=>{s&&s.removePendingData(C),e===v?(w&&C.onLoadedObservable.remove(w),Ae.UseFallbackTexture&&e!==Ae.FallbackTexture&&this._createTextureBase(Ae.FallbackTexture,t,C.invertY,s,r,null,o,l,h,c,C),J=(J||"Unknown error")+(Ae.UseFallbackTexture?" - Fallback texture was used":""),C.onErrorObservable.notifyObservers({message:J,exception:ne}),o&&o(J,ne)):(O.Warn(`Failed to load ${e}, falling back to ${v}`),this._createTextureBase(v,t,C.invertY,s,r,n,o,l,h,c,C,d,f,_,p,g))};if(P){const J=ne=>{P.loadData(ne,C,(oe,re,ce,Se,Ce,ae)=>{ae?$("TextureLoader failed to load data"):l(C,A,s,{width:oe,height:re},C.invertY,!ce,Se,()=>(Ce(),!1),r)},p)};c?c instanceof ArrayBuffer?J(new Uint8Array(c)):ArrayBuffer.isView(c)?J(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,ne=>J(new Uint8Array(ne)),void 0,s?s.offlineProvider:void 0,!0,(ne,oe)=>{$("Unable to load "+(ne&&ne.responseURL,oe))})}else{const J=ne=>{T&&!this._doNotHandleContextLost&&(C._buffer=ne),l(C,A,s,ne,C.invertY,t,!1,h,r)};!x||S?c&&(typeof c.decoding=="string"||c.close)?J(c):pe._FileToolsLoadImage(e,J,$,s?s.offlineProvider:null,_,C.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?pe._FileToolsLoadImage(c,J,$,s?s.offlineProvider:null,_,C.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&J(c)}return C}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,_,p){return this._createTextureBase(e,t,i,s,r,n,o,this._prepareWebGLTexture.bind(this),(g,x,T,S,C,v)=>{const b=this._gl,A=T.width===g&&T.height===x;C._creationFlags=_??0;const P=this._getTexImageParametersForCreateTexture(c,S,C._useSRGBBuffer);if(A)return b.texImage2D(b.TEXTURE_2D,0,P.internalFormat,P.format,P.type,T),!1;const L=this._caps.maxTextureSize;if(T.width>L||T.height>L||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=x,this._workingContext.drawImage(T,0,0,T.width,T.height,0,0,g,x),b.texImage2D(b.TEXTURE_2D,0,P.internalFormat,P.format,P.type,this._workingCanvas),C.width=g,C.height=x),!1;{const w=new Tt(this,et.Temp);this._bindTextureDirectly(b.TEXTURE_2D,w,!0),b.texImage2D(b.TEXTURE_2D,0,P.internalFormat,P.format,P.type,T),this._rescaleTexture(w,C,s,P.format,()=>{this._releaseTexture(w),this._bindTextureDirectly(b.TEXTURE_2D,C,!0),v()})}return!0},l,h,c,u,d,f,p)}_getTexImageParametersForCreateTexture(e,t,i){e==null&&(e=t===".jpg"&&!i?4:5);let s,r;return this.webGLVersion===1?(s=this._getInternalFormat(e,i),r=s):(s=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:r,format:s,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,s,r,n){throw Ge("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,o,l=null,h=0,c=0,u=!1){throw Ge("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,o,l=null){throw Ge("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,o,l,h=null,c=0){throw Ge("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,o,l,h=null,c=0){throw Ge("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 o=t.width||t,l=t.height||t,h=t.layers||0;e.baseWidth=o,e.baseHeight=l,e.width=o,e.height=l,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),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(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,o=0){const l=this._gl;let h=l.TEXTURE_2D;if(e.isCube&&(h=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(h,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,l=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=o.TEXTURE_2D;e.isCube&&(u=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),f=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(d-s,0)),p=n?e.height:Math.pow(2,Math.max(f-s,0));o.texImage2D(u,s,c,_,p,0,h,l,t)}updateTextureData(e,t,i,s,r,n,o=0,l=0,h=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let f=c.TEXTURE_2D,_=c.TEXTURE_2D;e.isCube&&(_=c.TEXTURE_CUBE_MAP_POSITIVE_X+o,f=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),c.texSubImage2D(_,l,i,s,r,n,d,u,t),h&&this._gl.generateMipmap(_),this._bindTextureDirectly(f,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 o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.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,o,l,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?pe.GetExponentOfTwo(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?pe.GetExponentOfTwo(s.height,c):s.height),f=this._gl;if(f){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(f.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:t===".jpg"&&!e._useSRGBBuffer?4:5,!l(u,d,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,o,h)})&&this._prepareWebGLTextureContinuation(e,i,n,o,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 o=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,o,o,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,o=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,l=!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,o,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var i;this._deleteTexture((i=e._hardwareTexture)==null?void 0:i.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_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 l;let r=!1;const n=t&&t._associatedChannel>-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw O.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,((l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_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 o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(l,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(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,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,t;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.call(this),this.unbindAllAttributes(),this._boundUniforms={},ls()&&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,xt.ResetCache();for(const i of this._activeRequests)i.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&((t=this._gl.getExtension("WEBGL_lose_context"))==null||t.loseContext())}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 o=t.RGBA,l=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(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}_loadFile(e,t,i,s,r,n){const o=pe._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),o}static _FileToolsLoadFile(e,t,i,s,r,n){throw Ge("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=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=pe.CeilingPOT(e),i=pe.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=pe.FloorPOT(e);break;case 2:s=pe.NearestPOT(e);break;case 3:default:s=pe.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(ls()){const{requestAnimationFrame:i}=t||window;if(typeof i=="function")return i(e)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:jc()?document:null}}pe._TempClearColorUint32=new Uint32Array(4);pe._TempClearColorInt32=new Int32Array(4);pe.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];pe._TextureLoaders=[];pe.CollisionsEpsilon=.001;pe._IsSupported=null;pe._HasMajorPerformanceCaveat=null;class wl{static SetImmediate(e){ls()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const AE=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Su extends Sn{constructor(e,t){super(e,ca.LoadFileError),this.name="LoadFileError",Fl._setPrototypeOf(this,Su.prototype),t instanceof yi?this.request=t:this.file=t}}class jd extends Sn{constructor(e,t){super(e,ca.RequestFileError),this.request=t,this.name="RequestFileError",Fl._setPrototypeOf(this,jd.prototype)}}class fm extends Sn{constructor(e,t){super(e,ca.ReadFileError),this.file=t,this.name="ReadFileError",Fl._setPrototypeOf(this,fm.prototype)}}const ji={DefaultRetryStrategy:Sv.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:a=>a,ScriptBaseUrl:"",ScriptPreprocessUrl:a=>a},yE=a=>(a=a.replace(/#/gm,"%23"),a),_m=(a,e)=>{if(!(a&&a.indexOf("data:")===0)&&ji.CorsBehavior)if(typeof ji.CorsBehavior=="string"||ji.CorsBehavior instanceof String)e.crossOrigin=ji.CorsBehavior;else{const t=ji.CorsBehavior(a);t&&(e.crossOrigin=t)}},Hu=(a,e,t,i,s="",r)=>{const n=Ae.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(n!=null&&n._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([a],{type:s})),l=!0):o=`data:${s};base64,`+TE(a):a instanceof Blob?(o=URL.createObjectURL(a),l=!0):(o=yE(a),o=ji.PreprocessUrl(a));const h=v=>{if(t){const b=o||a.toString();t(`Error while trying to load image: ${b.indexOf("http")===0||b.length<=128?b:b.slice(0,128)+"..."}`,v)}};if(n!=null&&n._features.forceBitmapOverHTMLImageElement)return Za(o,v=>{n.createImageBitmap(new Blob([v],{type:s}),{premultiplyAlpha:"none",...r}).then(b=>{e(b),l&&URL.revokeObjectURL(o)}).catch(b=>{t&&t("Error while trying to load image: "+a,b)})},void 0,i||void 0,!0,(v,b)=>{h(b)}),null;const c=new Image;_m(o,c);const u=[],d=()=>{u.forEach(v=>{v.target.addEventListener(v.name,v.handler)})},f=()=>{u.forEach(v=>{v.target.removeEventListener(v.name,v.handler)}),u.length=0},_=()=>{f(),e(c),l&&c.src&&URL.revokeObjectURL(c.src)},p=v=>{f(),h(v),l&&c.src&&URL.revokeObjectURL(c.src)},g=v=>{if(v.blockedURI!==c.src)return;f();const b=new Error(`CSP violation of policy ${v.effectiveDirective} ${v.blockedURI}. Current policy is ${v.originalPolicy}`);Ae.UseFallbackTexture=!1,h(b),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:_}),u.push({target:c,name:"error",handler:p}),u.push({target:document,name:"securitypolicyviolation",handler:g}),d();const x=o.substring(0,5)==="blob:",T=o.substring(0,5)==="data:",S=()=>{x||T||!yi.IsCustomRequestAvailable?c.src=o:Za(o,(v,b,A)=>{const P=!s&&A?A:s,L=new Blob([v],{type:P}),w=URL.createObjectURL(L);l=!0,c.src=w},void 0,i||void 0,!0,(v,b)=>{h(b)})},C=()=>{i&&i.loadImage(o,c)};if(!x&&!T&&i&&i.enableTexturesOffline)i.open(C,S);else{if(o.indexOf("file:")!==-1){const v=decodeURIComponent(o.substring(5).toLowerCase());if(qc.FilesToLoad[v]&&typeof URL<"u"){try{let b;try{b=URL.createObjectURL(qc.FilesToLoad[v])}catch{b=URL.createObjectURL(qc.FilesToLoad[v])}c.src=b,l=!0}catch{c.src=""}return c}}S()}return c},Cu=(a,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new G,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new fm(`Unable to read ${a.name}`,a))}),r.onload=o=>{e(o.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(a):r.readAsText(a),n},Za=(a,e,t,i,s,r,n)=>{if(a.name)return Cu(a,e,t,s,r?c=>{r(void 0,c)}:void 0);const o=a;if(o.indexOf("file:")!==-1){let c=decodeURIComponent(o.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=qc.FilesToLoad[c];if(u)return Cu(u,e,t,s,r?d=>r(void 0,new Su(d.message,d.file)):void 0)}const{match:l,type:h}=Vv(o);if(l){const c={onCompleteObservable:new G,abort:()=>()=>{}};try{const u=s?Xu(o):IE(o);e(u,void 0,h)}catch(u){r?r(void 0,u):O.Error(u.message||"Failed to parse the Data URL")}return wl.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return pm(o,(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 Su(c.message,c.request))}:void 0,n)},pm=(a,e,t,i,s,r,n)=>{a=yE(a),a=ji.PreprocessUrl(a);const o=ji.BaseUrl+a;let l=!1;const h={onCompleteObservable:new G,abort:()=>l=!0},c=()=>{let u=new yi,d=null,f;const _=()=>{u&&(t&&u.removeEventListener("progress",t),f&&u.removeEventListener("readystatechange",f),u.removeEventListener("loadend",p))};let p=()=>{_(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,f=null,p=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{l=!0,p&&p(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const g=T=>{const S=T.message||"Unknown error";r&&u?r(new jd(S,u)):O.Error(S)},x=T=>{if(u){if(u.open("GET",o),n)try{n(u)}catch(S){g(S);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),p&&u.addEventListener("loadend",p),f=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(f&&u.removeEventListener("readystatechange",f),u.status>=200&&u.status<300||u.status===0&&(!ls()||RE())){try{e&&e(s?u.response:u.responseText,u)}catch(v){g(v)}return}const S=ji.DefaultRetryStrategy;if(S){const v=S(o,u,T);if(v!==-1){_(),u=new yi,d=setTimeout(()=>x(T+1),v);return}}const C=new jd("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);r&&r(C)}},u.addEventListener("readystatechange",f),u.send()}};x(0)};if(i&&i.enableSceneOffline){const u=f=>{f&&f.status>400?r&&r(f):c()},d=()=>{i&&i.loadFile(ji.BaseUrl+a,f=>{!l&&e&&e(f),h.onCompleteObservable.notifyObservers(h)},t?f=>{!l&&t&&t(f)}:void 0,u,s)};i.open(d,u)}else c();return h},RE=()=>typeof location<"u"&&location.protocol==="file:",Sf=a=>AE.test(a),Vv=a=>{const e=AE.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Xu(a){return vv(a.split(",")[1])}const IE=a=>EE(a.split(",")[1]),kv=()=>{pe._FileToolsLoadImage=Hu,pe._FileToolsLoadFile=Za,Fr._FileToolsLoadFile=Za};kv();let kc;const Gv=(a,e,t,i,s,r,n,o,l,h)=>{kc={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(kc,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(kc,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(kc,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(kc,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};Gv(Xu,IE,ji,Sf,RE,Za,Hu,Cu,pm,_m);class Zc{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Si(e);if(t)return t;O.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}}Zc.RegisteredExternalClasses={};function en(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}function vu(a){let e=1;do e*=2;while(e<a);return e===a}function tp(a,e,t){return a*(1-t)+e*t}class X{static get BaseUrl(){return ji.BaseUrl}static set BaseUrl(e){ji.BaseUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://")<e.indexOf(".")||e.indexOf("data:")===0||e.indexOf("blob:")===0}static set ScriptBaseUrl(e){ji.ScriptBaseUrl=e}static get ScriptBaseUrl(){return ji.ScriptBaseUrl}static set ScriptPreprocessUrl(e){ji.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return ji.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return ji.DefaultRetryStrategy}static set DefaultRetryStrategy(e){ji.DefaultRetryStrategy=e}static get CorsBehavior(){return ji.CorsBehavior}static set CorsBehavior(e){ji.CorsBehavior=e}static get UseFallbackTexture(){return Ae.UseFallbackTexture}static set UseFallbackTexture(e){Ae.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Zc.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Zc.RegisteredExternalClasses=e}static get fallbackTexture(){return Ae.FallbackTexture}static set fallbackTexture(e){Ae.FallbackTexture=e}static FetchToRef(e,t,i,s,r,n){const o=Math.abs(e)*i%i|0,l=Math.abs(t)*s%s|0,h=(o+l*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 0}static Instantiate(e){return Zc.Instantiate(e)}static SetImmediate(e){wl.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 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 ls()&&!window.PointerEvent&&(t="mouse"),e._badDesktopOS&&!e._badOS&&!(document&&"ontouchend"in document)&&(t="mouse"),t}static SetCorsBehavior(e,t){_m(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23"),e}static get PreprocessUrl(){return ji.PreprocessUrl}static set PreprocessUrl(e){ji.PreprocessUrl=e}static LoadImage(e,t,i,s,r,n){return Hu(e,t,i,s,r,n)}static LoadFile(e,t,i,s,r,n){return Za(e,t,i,s,r,n)}static LoadFileAsync(e,t=!0){return new Promise((i,s)=>{Za(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(X.ScriptBaseUrl&&e.startsWith(X._DefaultCdnUrl)){const i=X.ScriptBaseUrl[X.ScriptBaseUrl.length-1]==="/"?X.ScriptBaseUrl.substring(0,X.ScriptBaseUrl.length-1):X.ScriptBaseUrl;e=e.replace(X._DefaultCdnUrl,i)}return e=X.ScriptPreprocessUrl(e),t&&(e=X.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=X.GetBabylonScriptURL(e),X.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=X.GetBabylonScriptURL(e),X.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i(`Unable to load script '${e}' in worker`,o)}return}else if(!ls()){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=o=>{i&&i(`Unable to load script '${e}'`,o)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise((i,s)=>{this.LoadScript(e,()=>{i()},(r,n)=>{s(n||new Error(r))},t)})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new G,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 Cu(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){Cs.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,o){throw Ge("DumpTools")}static DumpData(e,t,i,s,r="image/png",n,o=!1,l=!1,h){throw Ge("DumpTools")}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,l){throw Ge("DumpTools")}static _IsOffScreenCanvas(e){return e.convertToBlob!==void 0}static ToBlob(e,t,i="image/png",s){!X._IsOffScreenCanvas(e)&&!e.toBlob&&(e.toBlob=function(r,n,o){setTimeout(()=>{const l=atob(this.toDataURL(n,o).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;u<h;u++)c[u]=l.charCodeAt(u);r(new Blob([c]))})}),X._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"}X.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&&X.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(X._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const h=l.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,o){throw Ge("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw Ge("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,l,h=!1,c=!1,u=!0,d){throw Ge("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,l=!1,h=!1,c=!0,u){throw Ge("ScreenshotTools")}static RandomId(){return en()}static IsBase64(e){return Sf(e)}static DecodeBase64(e){return Xu(e)}static get errorsCount(){return O.errorsCount}static Log(e){O.Log(e)}static Warn(e){O.Warn(e)}static Error(e){O.Error(e)}static get LogCache(){return O.LogCache}static ClearLogCache(){O.ClearLogCache()}static set LogLevels(e){O.LogLevels=e}static set PerformanceLogLevel(e){if((e&X.PerformanceUserMarkLogLevel)===X.PerformanceUserMarkLogLevel){X.StartPerformanceCounter=X._StartUserMark,X.EndPerformanceCounter=X._EndUserMark;return}if((e&X.PerformanceConsoleLogLevel)===X.PerformanceConsoleLogLevel){X.StartPerformanceCounter=X._StartPerformanceConsole,X.EndPerformanceCounter=X._EndPerformanceConsole;return}X.StartPerformanceCounter=X._StartPerformanceCounterDisabled,X.EndPerformanceCounter=X._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!X._Performance){if(!ls())return;X._Performance=window.performance}!t||!X._Performance.mark||X._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!X._Performance.mark||(X._Performance.mark(e+"-End"),X._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(X._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(X._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Zi.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 Hc()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}X.UseCustomRequestHeaders=!1;X.CustomRequestHeaders=yi.CustomRequestHeaders;X.GetDOMTextContent=dm;X._DefaultCdnUrl="https://cdn.babylonjs.com";X.GetAbsoluteUrl=typeof document=="object"?a=>{const e=document.createElement("a");return e.href=a,e.href}:typeof URL=="function"&&typeof location=="object"?a=>new URL(a,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};X.NoneLogLevel=O.NoneLogLevel;X.MessageLogLevel=O.MessageLogLevel;X.WarningLogLevel=O.WarningLogLevel;X.ErrorLogLevel=O.ErrorLogLevel;X.AllLogLevel=O.AllLogLevel;X.IsWindowObjectExist=ls;X.PerformanceNoneLogLevel=0;X.PerformanceUserMarkLogLevel=1;X.PerformanceConsoleLogLevel=2;X.StartPerformanceCounter=X._StartPerformanceCounterDisabled;X.EndPerformanceCounter=X._EndPerformanceCounterDisabled;class Jr{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 Jr(e,t,i,s);return r.executeNext(),r}static SyncAsyncForLoop(e,t,i,s,r,n=0){return Jr.Run(Math.ceil(e/t),o=>{r&&r()?o.breakLoop():setTimeout(()=>{for(let l=0;l<t;++l){const h=o.index*t+l;if(h>=e)break;if(i(h),r&&r()){o.breakLoop();break}}o.executeNext()},n)},s)}}X.Mix=tp;X.IsExponentOfTwo=vu;Ae.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Wi{constructor(e){this.length=0,this.data=new Array(e),this._id=Wi._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}}Wi._GlobalId=0;class Ia extends Wi{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 ip{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}}function PE(a){a.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class mi{constructor(){this._dirty=!0,this._tempColor=new xe(0,0,0,0),this._globalCurve=new xe(0,0,0,0),this._highlightsCurve=new xe(0,0,0,0),this._midtonesCurve=new xe(0,0,0,0),this._shadowsCurve=new xe(0,0,0,0),this._positiveCurve=new xe(0,0,0,0),this._negativeCurve=new xe(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))}_getColorGradingDataToRef(e,t,i,s,r){e!=null&&(e=mi._Clamp(e,0,360),t=mi._Clamp(t,-100,100),i=mi._Clamp(i,-100,100),s=mi._Clamp(s,-100,100),t=mi._ApplyColorGradingSliderNonlinear(t),t*=.5,s=mi._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),mi._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=mi._Clamp(e,0,360);const n=mi._Clamp(t/100,0,1),o=mi._Clamp(i/100,0,1);if(n===0)s.r=o,s.g=o,s.b=o;else{r/=60;const l=Math.floor(r),h=r-l,c=o*(1-n),u=o*(1-n*h),d=o*(1-n*(1-h));switch(l){case 0:s.r=o,s.g=d,s.b=c;break;case 1:s.r=u,s.g=o,s.b=c;break;case 2:s.r=c,s.g=o,s.b=d;break;case 3:s.r=c,s.g=u,s.b=o;break;case 4:s.r=d,s.g=c,s.b=o;break;default:s.r=o,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return _e.Clone(()=>new mi,this)}serialize(){return _e.Serialize(this)}static Parse(e){return _e.Parse(()=>new mi,e,null,null)}}mi.PrepareUniforms=PE;E([I()],mi.prototype,"_globalHue",void 0);E([I()],mi.prototype,"_globalDensity",void 0);E([I()],mi.prototype,"_globalSaturation",void 0);E([I()],mi.prototype,"_globalExposure",void 0);E([I()],mi.prototype,"_highlightsHue",void 0);E([I()],mi.prototype,"_highlightsDensity",void 0);E([I()],mi.prototype,"_highlightsSaturation",void 0);E([I()],mi.prototype,"_highlightsExposure",void 0);E([I()],mi.prototype,"_midtonesHue",void 0);E([I()],mi.prototype,"_midtonesDensity",void 0);E([I()],mi.prototype,"_midtonesSaturation",void 0);E([I()],mi.prototype,"_midtonesExposure",void 0);_e._ColorCurvesParser=mi.Parse;function ME(a,e){e.EXPOSURE&&a.push("exposureLinear"),e.CONTRAST&&a.push("contrast"),e.COLORGRADING&&a.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&a.push("vInverseScreenSize"),e.VIGNETTE&&(a.push("vignetteSettings1"),a.push("vignetteSettings2")),e.COLORCURVES&&PE(a),e.DITHER&&a.push("ditherIntensity")}function DE(a,e){e.COLORGRADING&&a.push("txColorTransform")}class lt{constructor(){this.colorCurves=new mi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=lt.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new xe(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=lt.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new G}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){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===lt._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case lt.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&&mi.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),o=n*r;const l=Math.sqrt(o*n);o=tp(o,l,this.vignetteStretch),n=tp(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*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 _e.Clone(()=>new lt,this)}serialize(){return _e.Serialize(this)}static Parse(e){const t=_e.Parse(()=>new lt,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}}lt.TONEMAPPING_STANDARD=0;lt.TONEMAPPING_ACES=1;lt.PrepareUniforms=ME;lt.PrepareSamplers=DE;lt._VIGNETTEMODE_MULTIPLY=0;lt._VIGNETTEMODE_OPAQUE=1;E([_v()],lt.prototype,"colorCurves",void 0);E([I()],lt.prototype,"_colorCurvesEnabled",void 0);E([ht("colorGradingTexture")],lt.prototype,"_colorGradingTexture",void 0);E([I()],lt.prototype,"_colorGradingEnabled",void 0);E([I()],lt.prototype,"_colorGradingWithGreenDepth",void 0);E([I()],lt.prototype,"_colorGradingBGR",void 0);E([I()],lt.prototype,"_exposure",void 0);E([I()],lt.prototype,"_toneMappingEnabled",void 0);E([I()],lt.prototype,"_toneMappingType",void 0);E([I()],lt.prototype,"_contrast",void 0);E([I()],lt.prototype,"vignetteStretch",void 0);E([I()],lt.prototype,"vignetteCenterX",void 0);E([I()],lt.prototype,"vignetteCenterY",void 0);E([I()],lt.prototype,"vignetteWeight",void 0);E([cm()],lt.prototype,"vignetteColor",void 0);E([I()],lt.prototype,"vignetteCameraFov",void 0);E([I()],lt.prototype,"_vignetteBlendMode",void 0);E([I()],lt.prototype,"_vignetteEnabled",void 0);E([I()],lt.prototype,"_ditheringEnabled",void 0);E([I()],lt.prototype,"_ditheringIntensity",void 0);E([I()],lt.prototype,"_skipFinalColorClamp",void 0);E([I()],lt.prototype,"_applyByPostProcess",void 0);E([I()],lt.prototype,"_isEnabled",void 0);_e._ImageProcessingConfigurationParser=lt.Parse;pe.prototype.createUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new Eu(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};pe.prototype.createDynamicUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new Eu(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};pe.prototype.updateUniformBuffer=function(a,e,t,i){this.bindUniformBuffer(a),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};pe.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};pe.prototype.bindUniformBufferBase=function(a,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,a?a.underlyingResource:null)};pe.prototype.bindUniformBlock=function(a,e,t){const i=a.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class be{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.asArray()))}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)}_getNames(){const e=[];let t=0;for(const i in this._uniformLocations)if(e.push(i),++t===10)break;return e.join(",")}_rebuild(){this._noUBO||!this._bufferData||(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._engine._features.trackUbosInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){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&&(be._UpdatedUbosInFrame[this._name]||(be._UpdatedUbosInFrame[this._name]=0),be._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){O.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let 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]!==Math.fround(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){O.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,o=0,l=0;for(let h=0;h<i;h++)if(this._bufferData[s+l*4+o]!==X.FloatRound(t[h])&&(n=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+l*4+o]=t[h]),o++,o===r.strideSize){for(;o<4;o++)this._bufferData[s+l*4+o]=0;o=0,l++}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++)be._TempBuffer[i*4]=t[i*3],be._TempBuffer[i*4+1]=t[i*3+1],be._TempBuffer[i*4+2]=t[i*3+2],be._TempBuffer[i*4+3]=0;this.updateUniform(e,be._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++)be._TempBuffer[i*4]=t[i*2],be._TempBuffer[i*4+1]=t[i*2+1],be._TempBuffer[i*4+2]=0,be._TempBuffer[i*4+3]=0;this.updateUniform(e,be._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){be._TempBuffer[0]=t,this.updateUniform(e,be._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,s=""){this._currentEffect.setFloat2(e+s,t,i)}_updateFloat2ForUniform(e,t,i){be._TempBuffer[0]=t,be._TempBuffer[1]=i,this.updateUniform(e,be._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,s,r=""){this._currentEffect.setFloat3(e+r,t,i,s)}_updateFloat3ForUniform(e,t,i,s){be._TempBuffer[0]=t,be._TempBuffer[1]=i,be._TempBuffer[2]=s,this.updateUniform(e,be._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setFloat4(e+n,t,i,s,r)}_updateFloat4ForUniform(e,t,i,s,r){be._TempBuffer[0]=t,be._TempBuffer[1]=i,be._TempBuffer[2]=s,be._TempBuffer[3]=r,this.updateUniform(e,be._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){be._TempBufferInt32View.set(t),this.updateUniformArray(e,be._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){be._TempBufferUInt32View.set(t),this.updateUniformArray(e,be._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){be._TempBuffer[0]=t.x,be._TempBuffer[1]=t.y,be._TempBuffer[2]=t.z,this.updateUniform(e,be._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){be._TempBuffer[0]=t.x,be._TempBuffer[1]=t.y,be._TempBuffer[2]=t.z,be._TempBuffer[3]=t.w,this.updateUniform(e,be._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){be._TempBuffer[0]=t.r,be._TempBuffer[1]=t.g,be._TempBuffer[2]=t.b,this.updateUniform(e,be._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){be._TempBuffer[0]=t.r,be._TempBuffer[1]=t.g,be._TempBuffer[2]=t.b,be._TempBuffer[3]=i,this.updateUniform(e,be._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){be._TempBuffer[0]=t.r,be._TempBuffer[1]=t.g,be._TempBuffer[2]=t.b,be._TempBuffer[3]=t.a,this.updateUniform(e,be._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){be._TempBufferInt32View[0]=t,this.updateUniform(e,be._TempBuffer,1)}_updateInt2ForEffect(e,t,i,s=""){this._currentEffect.setInt2(e+s,t,i)}_updateInt2ForUniform(e,t,i){be._TempBufferInt32View[0]=t,be._TempBufferInt32View[1]=i,this.updateUniform(e,be._TempBuffer,2)}_updateInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setInt3(e+r,t,i,s)}_updateInt3ForUniform(e,t,i,s){be._TempBufferInt32View[0]=t,be._TempBufferInt32View[1]=i,be._TempBufferInt32View[2]=s,this.updateUniform(e,be._TempBuffer,3)}_updateInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setInt4(e+n,t,i,s,r)}_updateInt4ForUniform(e,t,i,s,r){be._TempBufferInt32View[0]=t,be._TempBufferInt32View[1]=i,be._TempBufferInt32View[2]=s,be._TempBufferInt32View[3]=r,this.updateUniform(e,be._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){be._TempBufferUInt32View[0]=t,this.updateUniform(e,be._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,s=""){this._currentEffect.setUInt2(e+s,t,i)}_updateUInt2ForUniform(e,t,i){be._TempBufferUInt32View[0]=t,be._TempBufferUInt32View[1]=i,this.updateUniform(e,be._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setUInt3(e+r,t,i,s)}_updateUInt3ForUniform(e,t,i,s){be._TempBufferUInt32View[0]=t,be._TempBufferUInt32View[1]=i,be._TempBufferUInt32View[2]=s,this.updateUniform(e,be._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setUInt4(e+n,t,i,s,r)}_updateUInt4ForUniform(e,t,i,s,r){be._TempBufferUInt32View[0]=t,be._TempBufferUInt32View[1]=i,be._TempBufferUInt32View[2]=s,be._TempBufferUInt32View[3]=r,this.updateUniform(e,be._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0;return!1}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(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)}}be._UpdatedUbosInFrame={};be._MAX_UNIFORM_SIZE=256;be._TempBuffer=new Float32Array(be._MAX_UNIFORM_SIZE);be._TempBufferInt32View=new Int32Array(be._TempBuffer.buffer);be._TempBufferUInt32View=new Uint32Array(be._TempBuffer.buffer);class Ji{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,r=!1,n=!1,o=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=n,this._divisor=l||1,this._label=h,t instanceof ko?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,s,r,n=!1,o){const l=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?n?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new y(this._engine,this,e,this._updatable,!0,h,r===void 0?this._instanced:r,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}O.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class y{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,l,h,c,u=!1,d=!1,f=1,_=!1){this._isDisposed=!1;let p=!1;if(this.engine=e,typeof s=="object"&&s!==null?(p=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,l=s.offset,h=s.size,c=s.type,u=s.normalized??!1,d=s.useBytes??!1,f=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):p=!!s,t instanceof Ji?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Ji(e,t,p,n,r,o,d,f,this._label),this._ownsBuffer=!0),this.uniqueId=y._Counter++,this._kind=i,c===void 0){const x=this.getData();this.type=x?y.GetDataType(x):y.FLOAT}else this.type=c;const g=y.GetTypeByteLength(this.type);d?(this._size=h||(n?n/g:y.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*g,this.byteOffset=l||0):(this._size=h||n||y.DeduceStride(i),this.byteStride=n?n*g:this._buffer.byteStride||this._size*g,this.byteOffset=(l||0)*g),this.normalized=u,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?f:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?y.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/y.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/y.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*y.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){y.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case y.UVKind:case y.UV2Kind:case y.UV3Kind:case y.UV4Kind:case y.UV5Kind:case y.UV6Kind:return 2;case y.NormalKind:case y.PositionKind:return 3;case y.ColorKind:case y.ColorInstanceKind:case y.MatricesIndicesKind:case y.MatricesIndicesExtraKind:case y.MatricesWeightsKind:case y.MatricesWeightsExtraKind:case y.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?y.BYTE:e instanceof Uint8Array?y.UNSIGNED_BYTE:e instanceof Int16Array?y.SHORT:e instanceof Uint16Array?y.UNSIGNED_SHORT:e instanceof Int32Array?y.INT:e instanceof Uint32Array?y.UNSIGNED_INT:y.FLOAT}static GetTypeByteLength(e){switch(e){case y.BYTE:case y.UNSIGNED_BYTE:return 1;case y.SHORT:case y.UNSIGNED_SHORT:return 2;case y.INT:case y.UNSIGNED_INT:case y.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,l){if(e instanceof Array){let h=t/4;const c=i/4;for(let u=0;u<n;u+=s){for(let d=0;d<s;d++)l(e[h+d],u+d);h+=c}}else{const h=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),c=y.GetTypeByteLength(r);for(let u=0;u<n;u+=s){let d=t;for(let f=0;f<s;f++){const _=y._GetFloatValue(h,r,d,o);l(_,u+f),d+=c}t+=i}}}static _GetFloatValue(e,t,i,s){switch(t){case y.BYTE:{let r=e.getInt8(i);return s&&(r=Math.max(r/127,-1)),r}case y.UNSIGNED_BYTE:{let r=e.getUint8(i);return s&&(r=r/255),r}case y.SHORT:{let r=e.getInt16(i,!0);return s&&(r=Math.max(r/32767,-1)),r}case y.UNSIGNED_SHORT:{let r=e.getUint16(i,!0);return s&&(r=r/65535),r}case y.INT:return e.getInt32(i,!0);case y.UNSIGNED_INT:return e.getUint32(i,!0);case y.FLOAT:return e.getFloat32(i,!0);default:throw new Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,i,s,r,n,o,l){const h=t*y.GetTypeByteLength(i),c=o*t;if(i!==y.FLOAT||r!==h){const u=new Float32Array(c);return y.ForEach(e,s,r,t,i,c,n,(d,f)=>u[f]=d),u}if(!(e instanceof Array||e instanceof Float32Array)||s!==0||e.length!==c)if(e instanceof Array){const u=s/4;return e.slice(u,u+c)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,s,c);{let u=e.byteOffset+s;if(l){const f=new Float32Array(c),_=new Float32Array(e.buffer,u,c);return f.set(_),f}const d=u%4;return d&&(u=Math.max(0,u-d)),new Float32Array(e.buffer,u,c)}}return l?e.slice():e}}y._Counter=0;y.BYTE=5120;y.UNSIGNED_BYTE=5121;y.SHORT=5122;y.UNSIGNED_SHORT=5123;y.INT=5124;y.UNSIGNED_INT=5125;y.FLOAT=5126;y.PositionKind="position";y.NormalKind="normal";y.TangentKind="tangent";y.UVKind="uv";y.UV2Kind="uv2";y.UV3Kind="uv3";y.UV4Kind="uv4";y.UV5Kind="uv5";y.UV6Kind="uv6";y.ColorKind="color";y.ColorInstanceKind="instanceColor";y.MatricesIndicesKind="matricesIndices";y.MatricesWeightsKind="matricesWeights";y.MatricesIndicesExtraKind="matricesIndicesExtra";y.MatricesWeightsExtraKind="matricesWeightsExtra";class es{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(y.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(y.NormalKind);let c=i?m.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?m.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]),d=i?m.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),d=d.scale(1-this.bu-this.bv),s=new m(c.x+u.x+d.x,c.y+u.y+d.y,c.z+u.z+d.z)}else{const h=this.pickedMesh.getVerticesData(y.PositionKind),c=i?m.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?m.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]),d=i?m.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]),f=c.subtract(u),_=d.subtract(u);s=m.Cross(f,_)}const l=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(U.Matrix[0].copyFrom(u),u=U.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(U.Matrix[1]),u=U.Matrix[1]),m.TransformNormalToRef(c,u,c)};if(e&&l(this.pickedMesh,s),this.ray){const h=U.Vector3[0].copyFrom(s);e||l(this.pickedMesh,h),m.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=y.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=Z.FromArray(i,t[this.faceId*3]*2),r=Z.FromArray(i,t[this.faceId*3+1]*2),n=Z.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 Z(s.x+r.x+n.x,s.y+r.y+n.y)}}class qd{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[y.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[y.PositionKind]=new y(this._scene.getEngine(),e,y.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[y.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 l;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(),(l=o._debugInsertMarker)==null||l.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 l;const n=this._scene.activeCamera;if(!n||(s=s||n._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(n,t==null?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,r),u._outputTexture=t):(o.restoreDefaultFramebuffer(),u._outputTexture=null),(l=o._debugInsertMarker)==null||l.call(o,`post process ${s[h].name} output`)),e)break;const d=u.apply();d&&(u.onBeforeRenderObservable.notifyObservers(d),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,d),o.drawElementsType(0,0,6),u.onAfterRenderObservable.notifyObservers(d))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){const e=this._vertexBuffers[y.PositionKind];e&&(e.dispose(),this._vertexBuffers[y.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class un{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=un.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=un.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=un.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,r=null){this.index=e,this._opaqueSubMeshes=new Wi(256),this._transparentSubMeshes=new Wi(256),this._alphaTestSubMeshes=new Wi(256),this._depthOnlySubMeshes=new Wi(256),this._particleSystems=new Wi(256),this._spriteManagers=new Wi(256),this._empty=!0,this._edgesRenderers=new Ia(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 o=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);o.length&&this._renderTransparent(o)}else this._renderTransparent(this._transparentSubMeshes);r.setAlphaMode(0)}if(r.setStencilBuffer(!1),this._edgesRenderers.length){for(let o=0;o<this._edgesRenderers.length;o++)this._edgesRenderers.data[o].render();r.setAlphaMode(0)}r.setStencilBuffer(n)}_renderOpaqueSorted(e){un._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){un._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){un._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,s){let r=0,n;const o=i?i.globalPosition:un._ZeroVector;if(s)for(;r<e.length;r++)n=e.data[r],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=m.Distance(n.getBoundingInfo().boundingSphere.centerWorld,o);const l=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&l.sort(t);const h=l[0].getMesh().getScene();for(r=0;r<l.length;r++)if(n=l[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:un.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)}}un._ZeroVector=m.Zero();class zv{}class Ts{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new zv,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=Ts.MIN_RENDERINGGROUPS;t<Ts.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 o=this._scene.spriteManagers[n];this.dispatchSprites(o)}for(let n=Ts.MIN_RENDERINGGROUPS;n<Ts.MAX_RENDERINGGROUPS;n++){this._depthStencilBufferAlreadyCleaned=n===Ts.MIN_RENDERINGGROUPS;const o=this._renderingGroups[n];if(!o||o._empty)continue;const l=1<<n;if(r.renderingGroupId=n,this._scene.onBeforeRenderingGroupObservable.notifyObservers(r,l),Ts.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);o.render(e,s,i,t);for(const h of this._scene._afterRenderingGroupDrawStage)h.action(n);this._scene.onAfterRenderingGroupObservable.notifyObservers(r,l)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=Ts.MIN_RENDERINGGROUPS;e<Ts.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=Ts.MIN_RENDERINGGROUPS;e<Ts.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=Ts.MIN_RENDERINGGROUPS;e<Ts.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){this._renderingGroups[e]===void 0&&(this._renderingGroups[e]=new un(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]}}Ts.MAX_RENDERINGGROUPS=4;Ts.MIN_RENDERINGGROUPS=0;Ts.AUTOCLEAR=!0;class he{}he.NAME_EFFECTLAYER="EffectLayer";he.NAME_LAYER="Layer";he.NAME_LENSFLARESYSTEM="LensFlareSystem";he.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";he.NAME_PARTICLESYSTEM="ParticleSystem";he.NAME_GAMEPAD="Gamepad";he.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";he.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";he.NAME_PREPASSRENDERER="PrePassRenderer";he.NAME_DEPTHRENDERER="DepthRenderer";he.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";he.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";he.NAME_SPRITE="Sprite";he.NAME_SUBSURFACE="SubSurface";he.NAME_OUTLINERENDERER="Outline";he.NAME_PROCEDURALTEXTURE="ProceduralTexture";he.NAME_SHADOWGENERATOR="ShadowGenerator";he.NAME_OCTREE="Octree";he.NAME_PHYSICSENGINE="PhysicsEngine";he.NAME_AUDIO="Audio";he.NAME_FLUIDRENDERER="FluidRenderer";he.STEP_ISREADYFORMESH_EFFECTLAYER=0;he.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;he.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;he.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;he.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;he.STEP_BEFORECAMERADRAW_PREPASS=0;he.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;he.STEP_BEFORECAMERADRAW_LAYER=2;he.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;he.STEP_BEFORERENDERTARGETDRAW_LAYER=1;he.STEP_BEFORERENDERINGMESH_PREPASS=0;he.STEP_BEFORERENDERINGMESH_OUTLINE=1;he.STEP_AFTERRENDERINGMESH_PREPASS=0;he.STEP_AFTERRENDERINGMESH_OUTLINE=1;he.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;he.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;he.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;he.STEP_BEFORECAMERAUPDATE_GAMEPAD=1;he.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;he.STEP_BEFORECLEAR_PREPASS=1;he.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;he.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;he.STEP_AFTERRENDERTARGETDRAW_LAYER=1;he.STEP_AFTERCAMERADRAW_PREPASS=0;he.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;he.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;he.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;he.STEP_AFTERCAMERADRAW_LAYER=4;he.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;he.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;he.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;he.STEP_AFTERRENDER_AUDIO=0;he.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;he.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;he.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;he.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;he.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;he.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;he.STEP_POINTERMOVE_SPRITE=0;he.STEP_POINTERDOWN_SPRITE=0;he.STEP_POINTERUP_SPRITE=0;class Pi extends Array{constructor(e){super(...e)}static Create(){return Object.create(Pi.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 Re{}Re.POINTERDOWN=1;Re.POINTERUP=2;Re.POINTERMOVE=4;Re.POINTERWHEEL=8;Re.POINTERPICK=16;Re.POINTERTAP=32;Re.POINTERDOUBLETAP=64;class OE{constructor(e,t){this.type=e,this.event=t}}class Wv extends OE{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new Z(i,s)}}class Zr extends OE{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 Ja{}Ja.KEYDOWN=1;Ja.KEYUP=2;class sp{constructor(e,t){this.type=e,this.event=t}}class Zg extends sp{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 Ve;(function(a){a[a.Generic=0]="Generic",a[a.Keyboard=1]="Keyboard",a[a.Mouse=2]="Mouse",a[a.Touch=3]="Touch",a[a.DualShock=4]="DualShock",a[a.Xbox=5]="Xbox",a[a.Switch=6]="Switch",a[a.DualSense=7]="DualSense"})(Ve||(Ve={}));var Qe;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.Move=12]="Move"})(Qe||(Qe={}));var Qd;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.DeltaHorizontal=10]="DeltaHorizontal",a[a.DeltaVertical=11]="DeltaVertical"})(Qd||(Qd={}));var Jg;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(Jg||(Jg={}));var ex;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Create=8]="Create",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(ex||(ex={}));var tx;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.LT=6]="LT",a[a.RT=7]="RT",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.LStickXAxis=17]="LStickXAxis",a[a.LStickYAxis=18]="LStickYAxis",a[a.RStickXAxis=19]="RStickXAxis",a[a.RStickYAxis=20]="RStickYAxis"})(tx||(tx={}));var ix;(function(a){a[a.B=0]="B",a[a.A=1]="A",a[a.Y=2]="Y",a[a.X=3]="X",a[a.L=4]="L",a[a.R=5]="R",a[a.ZL=6]="ZL",a[a.ZR=7]="ZR",a[a.Minus=8]="Minus",a[a.Plus=9]="Plus",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.Capture=17]="Capture",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(ix||(ix={}));var sx;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(sx||(sx={}));class Sc{}Sc.DOM_DELTA_PIXEL=0;Sc.DOM_DELTA_LINE=1;Sc.DOM_DELTA_PAGE=2;class xo{static CreateDeviceEvent(e,t,i,s,r,n,o){switch(e){case Ve.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case Ve.Mouse:if(i===Qe.MouseWheelX||i===Qe.MouseWheelY||i===Qe.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case Ve.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,o);default:throw`Unable to generate event for device ${Ve[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,o){const l=this._CreateMouseEvent(e,t,i,s,r,n);e===Ve.Mouse?(l.deviceType=Ve.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=Ve.Touch,l.pointerId=o??t,l.pointerType="touch");let h=0;return h+=r.pollInput(e,t,Qe.LeftClick),h+=r.pollInput(e,t,Qe.RightClick)*2,h+=r.pollInput(e,t,Qe.MiddleClick)*4,l.buttons=h,i===Qe.Move?l.type="pointermove":i>=Qe.LeftClick&&i<=Qe.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Sc.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case Qe.MouseWheelX:o.deltaX=s;break;case Qe.MouseWheelY:o.deltaY=s;break;case Qe.MouseWheelZ:o.deltaZ=s;break}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),l=r.pollInput(e,t,Qe.Horizontal),h=r.pollInput(e,t,Qe.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,Qd.DeltaHorizontal),o.movementY=r.pollInput(e,t,Qd.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Ve.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(Ve.Keyboard),s=i&&t.pollInput(Ve.Keyboard,0,18)===1,r=i&&t.pollInput(Ve.Keyboard,0,17)===1,n=i&&(t.pollInput(Ve.Keyboard,0,91)===1||t.pollInput(Ve.Keyboard,0,92)===1||t.pollInput(Ve.Keyboard,0,93)===1),o=i&&t.pollInput(Ve.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class Hv{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,o)=>{const l=xo.CreateDeviceEvent(s,r,n,o,this);i(s,r,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Ve.Mouse||e===Ve.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const rx=255,nx=Object.keys(Qe).length/2;class Xv{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=X.IsSafari(),this._usingMacOS=Hc()&&/(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._pointerMacOSChromeOutEvent=r=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Hc()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Hc()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=X.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 ${Ve[e]}`;e>=Ve.DualShock&&e<=Ve.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${Ve[e]} in slot ${t}`;return i===Qe.Move&&X.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?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),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}typeof matchMedia=="function"&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(Ve.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,nx);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 ${Ve[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(Ve.Keyboard,0,rx));const t=this._inputs[Ve.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(Ve.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ve.Keyboard,0,rx));const t=this._inputs[Ve.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=xo.CreateDeviceEvent(Ve.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(Ve.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Ve.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Ve.Keyboard][0];for(let t=0;t<e.length;t++)if(e[t]!==0){e[t]=0;const i=xo.CreateDeviceEvent(Ve.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ve.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=Hc()&&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);let r=s===Ve.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===Ve.Touch&&r===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(s,r);else{X.Warn(`Max number of touches exceeded.  Ignoring touches in excess of ${this._maxTouchPoints}`);return}}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 o=i;o.inputIndex=Qe.Move,n[Qe.Horizontal]=i.clientX,n[Qe.Vertical]=i.clientY,s===Ve.Touch&&n[Qe.LeftClick]===0&&(n[Qe.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,o))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===Ve.Mouse?0:i.pointerId;if(s===Ve.Touch){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId;else{X.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===Ve.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const o=n[Qe.Horizontal],l=n[Qe.Vertical];if(s===Ve.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[Qe.Horizontal]=i.clientX,n[Qe.Vertical]=i.clientY,n[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,r,h),(o!==i.clientX||l!==i.clientY)&&(h.inputIndex=Qe.Move,this._onInputChanged(s,r,h))}},this._pointerUpEvent=i=>{var o,l,h,c,u;const s=this._getPointerType(i),r=s===Ve.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===Ve.Touch){if(r===-1)return;this._activeTouchIds[r]=-1}const n=(o=this._inputs[s])==null?void 0:o[r];if(n&&n[i.button+2]!==0){const d=n[Qe.Horizontal],f=n[Qe.Vertical];n[Qe.Horizontal]=i.clientX,n[Qe.Vertical]=i.clientY,n[i.button+2]=0;const _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(_.inputIndex=Qe.Move,this._onInputChanged(s,r,_)),_.inputIndex=i.button+2,s===Ve.Mouse&&this._mouseId>=0&&((h=(l=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(l,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(c=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(c,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(s,r,_),s===Ve.Touch&&this._onDeviceDisconnected(s,r)}},this._pointerCancelEvent=i=>{var s,r,n,o;if(i.pointerType==="mouse"){const l=this._inputs[Ve.Mouse][0];this._mouseId>=0&&((r=(s=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Qe.LeftClick;h<=Qe.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=xo.CreateDeviceEvent(Ve.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(Ve.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;(o=(n=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[Ve.Touch][l][Qe.LeftClick]=0;const h=xo.CreateDeviceEvent(Ve.Touch,l,Qe.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(Ve.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(Ve.Touch,l)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch{}this._pointerBlurEvent=()=>{var i,s,r,n,o;if(this.isDeviceAvailable(Ve.Mouse)){const l=this._inputs[Ve.Mouse][0];this._mouseId>=0&&((s=(i=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Qe.LeftClick;h<=Qe.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=xo.CreateDeviceEvent(Ve.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(Ve.Mouse,0,c)}}if(this.isDeviceAvailable(Ve.Touch)){const l=this._inputs[Ve.Touch];for(let h=0;h<this._activeTouchIds.length;h++){const c=this._activeTouchIds[h];if((n=(r=this._elementToAttachTo).hasPointerCapture)!=null&&n.call(r,c)&&this._elementToAttachTo.releasePointerCapture(c),c!==-1&&((o=l[h])==null?void 0:o[Qe.LeftClick])===1){l[h][Qe.LeftClick]=0;const u=xo.CreateDeviceEvent(Ve.Touch,h,Qe.LeftClick,0,this,this._elementToAttachTo,c);this._onInputChanged(Ve.Touch,h,u),this._activeTouchIds[h]=-1,this._onDeviceDisconnected(Ve.Touch,h)}}}},this._pointerWheelEvent=i=>{const s=Ve.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,nx));const n=this._inputs[s][r];if(n){n[Qe.MouseWheelX]=i.deltaX||0,n[Qe.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[Qe.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[Qe.MouseWheelX]!==0&&(o.inputIndex=Qe.MouseWheelX,this._onInputChanged(s,r,o)),n[Qe.MouseWheelY]!==0&&(o.inputIndex=Qe.MouseWheelY,this._onInputChanged(s,r,o)),n[Qe.MouseWheelZ]!==0&&(o.inputIndex=Qe.MouseWheelZ,this._onInputChanged(s,r,o))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(Ve.Mouse)){const i=this._inputs[Ve.Mouse][0];i[Qe.MouseWheelX]=0,i[Qe.MouseWheelY]=0,i[Qe.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?Ve.DualSense:Ve.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?Ve.Xbox:e.indexOf("057e")!==-1?Ve.Switch:Ve.Generic}_getPointerType(e){let t=Ve.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=Ve.Touch),t}}class ax{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new G,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Yv{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let o=0;o<this._devices.length;o++){const l=this._devices[o];for(const h in l){const c=+h;n._addDevice(new ax(this._deviceInputSystem,o,c))}}this._registeredManagers.push(n)},this.unregisterManager=n=>{const o=this._registeredManagers.indexOf(n);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(Ve).length/2;this._devices=new Array(t);const i=(n,o)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][o]||(this._devices[n][o]=o);for(const l of this._registeredManagers){const h=new ax(this._deviceInputSystem,n,o);l._addDevice(h)}},s=(n,o)=>{var l;(l=this._devices[n])!=null&&l[o]&&delete this._devices[n][o];for(const h of this._registeredManagers)h._removeDevice(n,o)},r=(n,o,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(n,o,l)};typeof _native<"u"?this._deviceInputSystem=new Hv(i,s,r):this._deviceInputSystem=new Xv(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class $v{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(Ve).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Yv(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new G(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new G,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var s,r;const i=(s=this._devices[e])==null?void 0:s[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(r=this._devices[e])!=null&&r[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])==null?void 0:s[t])==null||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Ve.Keyboard:case Ve.Mouse:this._firstDevice[e]=0;break;case Ve.Touch:case Ve.DualSense:case Ve.DualShock:case Ve.Xbox:case Ve.Switch:case Ve.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 ox{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 Ni{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 Z(0,0),this._previousStartingPointerPosition=new Z(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||Ae.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 Z(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 l of i._pointerMoveStage){e=e||this._pickMove(t);const h=!!(e!=null&&e.pickedMesh);e=l.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,h,r)}const n=t.inputIndex>=Qe.MouseWheelX&&t.inputIndex<=Qe.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let o;e?(o=new Zr(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new Zr(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,D.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 Wv(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,t.pointerType==="xr-near"&&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=Qe.Move,!this._checkPrePointerObservable(e,i,Re.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Re.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,di.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,di.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(4,di.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(3,di.CreateNew(e.pickedMesh,t,e));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>Ni.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,di.CreateNew(o.pickedMesh,t)))},Ni.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Re.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Zr(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Zr(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=Qe.Move;const r=new ox;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,Re.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=Re.POINTERPICK,o=new Zr(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,di.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,di.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,di.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,di.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Zr(Re.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Re.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Re.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=Re.POINTERTAP:i.doubleClick&&(n=Re.POINTERDOUBLETAP),n){const o=new Zr(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(o,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 $v(n),this._initActionManager=o=>{if(!this._meshPickProceed){const l=r.skipPointerUpPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,h)=>{if((Date.now()-this._previousStartingPointerTime>Ni.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const c=this._delayedClicks[o].evt,u=Re.POINTERTAP,d=new Zr(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(d,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,h,c)=>{var p,g;const u=new ox;this._currentPickResult=null;let d=null,f=o.hasSpecificMask(Re.POINTERPICK)||l.hasSpecificMask(Re.POINTERPICK)||o.hasSpecificMask(Re.POINTERTAP)||l.hasSpecificMask(Re.POINTERTAP)||o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!f&&vr&&(d=this._initActionManager(d,u),d&&(f=d.hasPickTriggers));let _=!1;if(f){const x=h.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let T=!Ni.ExclusiveDoubleClickMode;if(T||(T=!o.hasSpecificMask(Re.POINTERDOUBLETAP)&&!l.hasSpecificMask(Re.POINTERDOUBLETAP),T&&!vr.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(T=!d.hasSpecificTrigger(6)))),T)(Date.now()-this._previousStartingPointerTime>Ni.DoubleClickDelay||x!==this._previousButtonPressed)&&(u.singleClick=!0,c(u,this._currentPickResult),_=!0);else{const C={evt:h,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,x,u,c),Ni.DoubleClickDelay)};this._delayedClicks[x]=C}let S=o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!S&&vr.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(S=d.hasSpecificTrigger(6))),S&&(x===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<Ni.DoubleClickDelay&&!this._doubleClickOccured?(!u.hasSwiped&&!this._isPointerSwiping()?(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,u.doubleClick=!0,u.ignore=!1,Ni.ExclusiveDoubleClickMode&&this._delayedClicks[x]&&(clearTimeout((p=this._delayedClicks[x])==null?void 0:p.timeoutId),this._delayedClicks[x]=null),c(u,this._currentPickResult)):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=x,Ni.ExclusiveDoubleClickMode?(this._delayedClicks[x]&&(clearTimeout((g=this._delayedClicks[x])==null?void 0:g.timeoutId),this._delayedClicks[x]=null),c(u,this._previousPickResult)):c(u,this._currentPickResult)),_=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=x))}}_||c(u,this._currentPickResult)},this._onPointerMove=o=>{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Ni.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Ni.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=Qe.MouseWheelX&&o.inputIndex<=Qe.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new es,o);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 l=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var h;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Ni.ExclusiveDoubleClickMode){for(let c=0;c<this._delayedClicks.length;c++)if(this._delayedClicks[c])if(o.button===c)clearTimeout((h=this._delayedClicks[c])==null?void 0:h.timeoutId);else{const u=this._delayedClicks[c].clickInfo;this._doubleClickOccured=!1,u.singleClick=!0,u.ignore=!1;const d=this._delayedClicks[c].evt,f=Re.POINTERTAP,_=new Zr(f,d,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(f)&&r.onPointerObservable.notifyObservers(_,f),this._delayedClicks[c]=null}}if(this._updatePointerPosition(o),this._swipeButtonPressed===-1&&(this._swipeButtonPressed=o.button),r.preventDefaultOnPointerDown&&s&&(o.preventDefault(),s.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,o,Re.POINTERDOWN)||!r.cameraToUseForPointers&&!r.activeCamera)return;this._pointerCaptures[o.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 l;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?l=new es:l=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),r.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,o,(l,h)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Re.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(Re.POINTERTAP)&&this._checkPrePointerObservable(null,o,Re.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Re.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Re.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!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&&(vr&&vr.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=Ja.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const h=new Zg(l,o);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new sp(l,o);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(14,di.CreateNewFromScene(r,o))},this._onKeyUp=o=>{const l=Ja.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const h=new Zg(l,o);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new sp(l,o);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(15,di.CreateNewFromScene(r,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===Ve.Mouse?o.onInputChangedObservable.add(l=>{l.inputIndex===Qe.LeftClick||l.inputIndex===Qe.MiddleClick||l.inputIndex===Qe.RightClick||l.inputIndex===Qe.BrowserBack||l.inputIndex===Qe.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===Qe.Move?this._onPointerMove(l):(l.inputIndex===Qe.MouseWheelX||l.inputIndex===Qe.MouseWheelY||l.inputIndex===Qe.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===Ve.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===Qe.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===Qe.Move&&this._onPointerMove(l)}):o.deviceType===Ve.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,di.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,di.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]}}Ni.DragMovementThreshold=10;Ni.LongPressDelay=500;Ni.DoubleClickDelay=300;Ni.ExclusiveDoubleClickMode=!1;class wr{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){wr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){wr.Enabled&&(this._startMonitoringTime=Zi.Now)}endMonitoring(e=!0){if(!wr.Enabled)return;e&&this.fetchNewFrame();const t=Zi.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=Zi.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}wr.Enabled=!0;class Ks{constructor(e,t,i,s){this.normal=new m(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Ks(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=Ks._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,l=s*i[0]+r*i[1]+n*i[2]+o*i[3],h=s*i[4]+r*i[5]+n*i[6]+o*i[7],c=s*i[8]+r*i[9]+n*i[10]+o*i[11],u=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Ks(l,h,c,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=r*h-n*l,u=n*o-s*h,d=s*l-r*o,f=Math.sqrt(c*c+u*u+d*d);let _;return f!==0?_=1/f:_=0,this.normal.x=c*_,this.normal.y=u*_,this.normal.z=d*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return m.Dot(this.normal,e)<=t}signedDistanceTo(e){return m.Dot(e,this.normal)+this.d}static FromArray(e){return new Ks(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Ks(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Ks(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return m.Dot(i,t)+s}}Ks._TmpMatrix=D.Identity();class Or{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Ks(0,0,0,0));return Or.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){Or.GetNearPlaneToRef(e,t[0]),Or.GetFarPlaneToRef(e,t[1]),Or.GetLeftPlaneToRef(e,t[2]),Or.GetRightPlaneToRef(e,t[3]),Or.GetTopPlaneToRef(e,t[4]),Or.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 Yu{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Yu._UniqueIdCounter=1;class Nt{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Nt.FALLOFF_DEFAULT=0;Nt.FALLOFF_PHYSICAL=1;Nt.FALLOFF_GLTF=2;Nt.FALLOFF_STANDARD=3;Nt.LIGHTMAP_DEFAULT=0;Nt.LIGHTMAP_SPECULAR=1;Nt.LIGHTMAP_SHADOWSONLY=2;Nt.INTENSITYMODE_AUTOMATIC=0;Nt.INTENSITYMODE_LUMINOUSPOWER=1;Nt.INTENSITYMODE_LUMINOUSINTENSITY=2;Nt.INTENSITYMODE_ILLUMINANCE=3;Nt.INTENSITYMODE_LUMINANCE=4;Nt.LIGHTTYPEID_POINTLIGHT=0;Nt.LIGHTTYPEID_DIRECTIONALLIGHT=1;Nt.LIGHTTYPEID_SPOTLIGHT=2;Nt.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Kv{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Gn;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(Gn||(Gn={}));class Ee extends wi{static DefaultMaterialFactory(e){throw Ge("StandardMaterial")}static CollisionCoordinatorFactory(){throw Ge("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 Gn.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Gn.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Gn.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 Ni.DragMovementThreshold}static set DragMovementThreshold(e){Ni.DragMovementThreshold=e}static get LongPressDelay(){return Ni.LongPressDelay}static set LongPressDelay(e){Ni.LongPressDelay=e}static get DoubleClickDelay(){return Ni.DoubleClickDelay}static set DoubleClickDelay(e){Ni.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Ni.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Ni.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return U.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,U.Vector4[0].x,U.Vector4[0].y,U.Vector4[0].z):e.setVector4(t,U.Vector4[0])),U.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=oE(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=Ee.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=Ee.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 Ni(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new xe(.2,.2,.3,1),this.ambientColor=new q(0,0,0),this.environmentIntensity=1,this._performancePriority=Gn.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new G,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new G,this._onDisposeObserver=null,this.onBeforeRenderObservable=new G,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new G,this.onAfterRenderCameraObservable=new G,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new G,this.onAfterAnimationsObservable=new G,this.onBeforeDrawPhaseObservable=new G,this.onAfterDrawPhaseObservable=new G,this.onReadyObservable=new G,this.onBeforeCameraRenderObservable=new G,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new G,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new G,this.onAfterActiveMeshesEvaluationObservable=new G,this.onBeforeParticlesRenderingObservable=new G,this.onAfterParticlesRenderingObservable=new G,this.onDataLoadedObservable=new G,this.onNewCameraAddedObservable=new G,this.onCameraRemovedObservable=new G,this.onNewLightAddedObservable=new G,this.onLightRemovedObservable=new G,this.onNewGeometryAddedObservable=new G,this.onGeometryRemovedObservable=new G,this.onNewTransformNodeAddedObservable=new G,this.onTransformNodeRemovedObservable=new G,this.onNewMeshAddedObservable=new G,this.onMeshRemovedObservable=new G,this.onNewSkeletonAddedObservable=new G,this.onSkeletonRemovedObservable=new G,this.onNewMaterialAddedObservable=new G,this.onNewMultiMaterialAddedObservable=new G,this.onMaterialRemovedObservable=new G,this.onMultiMaterialRemovedObservable=new G,this.onNewTextureAddedObservable=new G,this.onTextureRemovedObservable=new G,this.onBeforeRenderTargetsRenderObservable=new G,this.onAfterRenderTargetsRenderObservable=new G,this.onBeforeStepObservable=new G,this.onAfterStepObservable=new G,this.onActiveCameraChanged=new G,this.onActiveCamerasChanged=new G,this.onBeforeRenderingGroupObservable=new G,this.onAfterRenderingGroupObservable=new G,this.onMeshImportedObservable=new G,this.onAnimationFileImportedObservable=new G,this._registeredForLateAnimationBindings=new Ia(256),this._pointerPickingConfiguration=new Kv,this.onPrePointerObservable=new G,this.onPointerObservable=new G,this.onPreKeyboardObservable=new G,this.onKeyboardObservable=new G,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Ee.FOGMODE_NONE,this.fogColor=new q(.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 m(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Ia(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new wr,this._activeIndices=new wr,this._activeParticles=new wr,this._activeBones=new wr,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 Wi(256),this._processedMaterials=new Wi(256),this._renderTargets=new Ia(256),this._materialsRenderTargets=new Ia(256),this._activeParticleSystems=new Wi(256),this._activeSkeletons=new Ia(32),this._softwareSkinnedMeshes=new Ia(32),this._activeAnimatables=new Array,this._transformMatrix=D.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Pi.Create(),this._beforeClearStage=Pi.Create(),this._beforeRenderTargetClearStage=Pi.Create(),this._gatherRenderTargetsStage=Pi.Create(),this._gatherActiveCameraRenderTargetsStage=Pi.Create(),this._isReadyForMeshStage=Pi.Create(),this._beforeEvaluateActiveMeshStage=Pi.Create(),this._evaluateSubMeshStage=Pi.Create(),this._preActiveMeshStage=Pi.Create(),this._cameraDrawRenderTargetStage=Pi.Create(),this._beforeCameraDrawStage=Pi.Create(),this._beforeRenderTargetDrawStage=Pi.Create(),this._beforeRenderingGroupDrawStage=Pi.Create(),this._beforeRenderingMeshStage=Pi.Create(),this._afterRenderingMeshStage=Pi.Create(),this._afterRenderingGroupDrawStage=Pi.Create(),this._afterCameraDrawStage=Pi.Create(),this._afterCameraPostProcessStage=Pi.Create(),this._afterRenderTargetDrawStage=Pi.Create(),this._afterRenderTargetPostProcessStage=Pi.Create(),this._afterRenderStage=Pi.Create(),this._pointerMoveStage=Pi.Create(),this._pointerDownStage=Pi.Create(),this._pointerUpStage=Pi.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||Ae.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Ae._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Ts(this),qd&&(this.postProcessManager=new qd(this)),ls()&&this.attachControl(),this._createUbo(),lt&&(this._imageProcessingConfiguration=new lt),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var n,o;if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=((n=this.activeCamera)==null?void 0:n.renderPassId)??s;let r=!0;for(this._pendingData.length>0&&(r=!1),(o=this.prePassRenderer)==null||o.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const l=this.meshes[t];if(!l.subMeshes||l.subMeshes.length===0)continue;if(!l.isReady(!0)){r=!1;continue}const h=l.hasThinInstances||l.getClassName()==="InstancedMesh"||l.getClassName()==="InstancedLinesMesh"||i.getCaps().instancedArrays&&l.instances.length>0;for(const u of this._isReadyForMeshStage)u.action(l,h)||(r=!1);if(!e)continue;const c=l.material||this.defaultMaterial;if(c)if(c._storeEffectOnSubMeshes)for(const u of l.subMeshes){const d=u.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else c.hasRenderTargetTextures&&c.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(c)===-1&&(this._processedMaterials.push(c),this._materialsRenderTargets.concatWithNoDuplicate(c.getRenderTargetTextures()))}if(e)for(t=0;t<this._materialsRenderTargets.length;++t)this._materialsRenderTargets.data[t].isReadyForRendering()||(r=!1);for(t=0;t<this.geometries.length;t++)this.geometries[t].delayLoadState===2&&(r=!1);if(this.activeCameras&&this.activeCameras.length>0)for(const l of this.activeCameras)l.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const l of this.particleSystems)l.isReady()||(r=!1);if(this.layers)for(const l of this.layers)l.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}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=Zi.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?Or.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Or.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 be(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 Yu.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(Nt.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=X.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new ip),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new ip),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 i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const s=this._activeMeshes.length;for(let 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 e=this.getActiveMeshCandidates(),t=e.length;for(let s=0;s<t;s++){const r=e.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 o of this._preActiveMeshStage)o.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 o=s.data[n];this._evaluateSubMesh(o,t,e,i)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const i=t._rigCameras[0],s=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),s.getViewMatrix(),s.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(!(e&&e._multiviewTexture))if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):!t.skipInitialClear&&!e.isRightCamera&&(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){var n;if(e&&e._skipRendering)return;const s=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(s.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let o=!0;e._renderingMultiview&&e.outputRenderTarget&&(o=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=o)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let o=0;o<this._softwareSkinnedMeshes.length;o++){const l=this._softwareSkinnedMeshes.data[o];l.applySkeleton(l.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 o of this._gatherActiveCameraRenderTargetsStage)o.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){X.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let o=0;o<this._renderTargets.length;o++){const l=this._renderTargets.data[o];if(l._shouldRender()){this._renderId++;const h=l.activeCamera&&l.activeCamera!==this.activeCamera;l.render(h,this.dumpNextRenderTargets),r=!0}}X.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const o of this._cameraDrawRenderTargetStage)r=o.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=((n=e.outputRenderTarget)==null?void 0:n.renderPassId)??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const o of this._beforeCameraDrawStage)o.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&s.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const o of this._afterCameraDrawStage)o.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const o=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,o)}for(const o of this._afterCameraPostProcessStage)o.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,o=n.intersectsMesh(t,r.usePreciseIntersection),l=t._intersectionsInProgress.indexOf(n);o&&l===-1?s.trigger===12?(s._executeCurrent(di.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):s.trigger===13&&t._intersectionsInProgress.push(n):!o&&l>-1&&(s.trigger===13&&s._executeCurrent(di.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(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Ee.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ee.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(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,s++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(Ee.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ee.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.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 r,n;if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&this._executeWhenReadyTimeoutId===null&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(r=this.activeCameras)!=null&&r.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 l=this.activeCameras[o];if(l.update(),l.cameraRigMode!==0)for(let h=0;h<l._rigCameras.length;h++)l._rigCameras[h].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 i=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const s=(n=this.activeCameras)!=null&&n.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){X.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let o=0;o<this.customRenderTargets.length;o++){const l=this.customRenderTargets[o];if(l._shouldRender()){if(this._renderId++,this.activeCamera=l.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");i.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),l.render(s!==this.activeCamera,this.dumpNextRenderTargets)}}X.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(s==null?void 0:s.renderPassId)??0,this.activeCamera=s,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 l=this._toBeDisposed[o];l&&l.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach(r=>{r.onAnimationEndObservable.clear(),r.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const r of e)r.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(r){O.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),Ae._LastCreatedScene===this&&(this._engine.scenes.length>0?Ae._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ae._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 m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new m(-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,o=r.boundingBox.maximumWorld;m.CheckExtends(n,t,i),m.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw Ge("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw Ge("Ray")}createPickingRayInCameraSpace(e,t,i){throw Ge("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw Ge("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=Ge("Ray",!0);return o&&O.Warn(o),new es}pickWithBoundingInfo(e,t,i,s,r){const n=Ge("Ray",!0);return n&&O.Warn(n),new es}pickWithRay(e,t,i,s){throw Ge("Ray")}multiPick(e,t,i,s,r){throw Ge("Ray")}multiPickWithRay(e,t,i){throw Ge("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const r in e){const n=e[r];ft&&ft.MatchesQuery(n,t)&&(!i||i(n))&&s.push(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)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const l=Za(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_loadFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._loadFile(e,l=>{n(l)},t,i,s,(l,h)=>{o(h)},r)})}_requestFile(e,t,i,s,r,n,o){const l=pm(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_requestFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._requestFile(e,l=>{n(l)},t,i,s,l=>{o(l)},r)})}_readFile(e,t,i,s,r){const n=Cu(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw Ge("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)}}Ee.FOGMODE_NONE=0;Ee.FOGMODE_EXP=1;Ee.FOGMODE_EXP2=2;Ee.FOGMODE_LINEAR=3;Ee.MinDeltaTime=1;Ee.MaxDeltaTime=1e3;var pt;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(pt||(pt={}));class Bs{}Bs.X=new m(1,0,0);Bs.Y=new m(0,1,0);Bs.Z=new m(0,0,1);var Eo;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(Eo||(Eo={}));class Ut extends Ct{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=(s==null?void 0:s.clone())??D.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new D,this._absoluteBindMatrix=new D,this._absoluteInverseBindMatrix=new D,this._finalMatrix=new D,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=U.Vector3[0],t=U.Quaternion[0],i=U.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??Q.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=m.Zero(),this._localRotation=Q.Zero(),this._localPosition=m.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,D.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i<this.children.length;i++)this.children[i]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=pt.LOCAL,i,s=!0){const r=this.getLocalMatrix();if(t==pt.LOCAL)s?(r.addAtIndex(12,e.x),r.addAtIndex(13,e.y),r.addAtIndex(14,e.z)):r.setTranslationFromFloats(e.x,e.y,e.z);else{let n=null;i&&(n=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const o=Ut._TmpMats[0],l=Ut._TmpVecs[0];this.parent?i&&n?(o.copyFrom(this.parent.getAbsoluteMatrix()),o.multiplyToRef(n,o)):o.copyFrom(this.parent.getAbsoluteMatrix()):D.IdentityToRef(o),s&&o.setTranslationFromFloats(0,0,0),o.invert(),m.TransformCoordinatesToRef(e,o,l),s?(r.addAtIndex(12,l.x),r.addAtIndex(13,l.y),r.addAtIndex(14,l.z)):r.setTranslationFromFloats(l.x,l.y,l.z)}this._markAsDirtyAndDecompose()}translate(e,t=pt.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=pt.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,pt.WORLD,t)}scale(e,t,i,s=!1){const r=this.getLocalMatrix(),n=Ut._TmpMats[0];D.ScalingToRef(e,t,i,n),n.multiplyToRef(r,r),n.invert();for(const o of this.children){const l=o.getLocalMatrix();l.multiplyToRef(n,l),l.multiplyAtIndex(12,e),l.multiplyAtIndex(13,t),l.multiplyAtIndex(14,i),o._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),s)for(const o of this.children)o.scale(e,t,i,s)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,s=pt.LOCAL,r){if(s===pt.LOCAL){const l=Ut._TmpQuat;Q.RotationYawPitchRollToRef(e,t,i,l),this.setRotationQuaternion(l,s,r);return}const n=Ut._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,r))return;const o=Ut._TmpMats[1];D.RotationYawPitchRollToRef(e,t,i,o),n.multiplyToRef(o,o),this._rotateWithMatrix(o,s,r)}rotate(e,t,i=pt.LOCAL,s){const r=Ut._TmpMats[0];r.setTranslationFromFloats(0,0,0),D.RotationAxisToRef(e,t,r),this._rotateWithMatrix(r,i,s)}setAxisAngle(e,t,i=pt.LOCAL,s){if(i===pt.LOCAL){const o=Ut._TmpQuat;Q.RotationAxisToRef(e,t,o),this.setRotationQuaternion(o,i,s);return}const r=Ut._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,s))return;const n=Ut._TmpMats[1];D.RotationAxisToRef(e,t,n),r.multiplyToRef(n,n),this._rotateWithMatrix(n,i,s)}setRotation(e,t=pt.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=pt.LOCAL,i){if(t===pt.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}const s=Ut._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,i))return;const r=Ut._TmpMats[1];D.FromQuaternionToRef(e,r),s.multiplyToRef(r,r),this._rotateWithMatrix(r,t,i)}setRotationMatrix(e,t=pt.LOCAL,i){if(t===pt.LOCAL){const n=Ut._TmpQuat;Q.FromRotationMatrixToRef(e,n),this.setRotationQuaternion(n,t,i);return}const s=Ut._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,i))return;const r=Ut._TmpMats[1];r.copyFrom(e),s.multiplyToRef(e,r),this._rotateWithMatrix(r,t,i)}_rotateWithMatrix(e,t=pt.LOCAL,i){const s=this.getLocalMatrix(),r=s.m[12],n=s.m[13],o=s.m[14],l=this.getParent(),h=Ut._TmpMats[3],c=Ut._TmpMats[4];l&&t==pt.WORLD?(i?(h.copyFrom(i.getWorldMatrix()),l.getAbsoluteMatrix().multiplyToRef(h,h)):h.copyFrom(l.getAbsoluteMatrix()),c.copyFrom(h),c.invert(),s.multiplyToRef(h,s),s.multiplyToRef(e,s),s.multiplyToRef(c,s)):t==pt.WORLD&&i?(h.copyFrom(i.getWorldMatrix()),c.copyFrom(h),c.invert(),s.multiplyToRef(h,s),s.multiplyToRef(e,s),s.multiplyToRef(c,s)):s.multiplyToRef(e,s),s.setTranslationFromFloats(r,n,o),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){const i=Ut._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),D.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):D.IdentityToRef(i),e.invert(),isNaN(e.m[0])?!1:(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=pt.LOCAL,t=null){const i=m.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=pt.LOCAL,t,i){if(e==pt.LOCAL){const s=this.getLocalMatrix();i.x=s.m[12],i.y=s.m[13],i.z=s.m[14]}else{let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=Ut._TmpMats[0];t&&s?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(s,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){const t=m.Zero();return this.getPositionToRef(pt.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(pt.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);const i=this._skeleton.getPoseMatrix();i&&this._absoluteMatrix.multiplyToRef(i,this._absoluteMatrix)}const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){const i=m.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=Ut._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&s&&r.multiplyToRef(s,r),m.TransformNormalToRef(e,r,i),i.normalize()}getRotation(e=pt.LOCAL,t=null){const i=m.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=pt.LOCAL,t=null,i){const s=Ut._TmpQuat;this.getRotationQuaternionToRef(e,t,s),s.toEulerAnglesToRef(i)}getRotationQuaternion(e=pt.LOCAL,t=null){const i=Q.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=pt.LOCAL,t=null,i){if(e==pt.LOCAL)this._decompose(),i.copyFrom(this._localRotation);else{const s=Ut._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),s):s.copyFrom(r),s.multiplyAtIndex(0,this._scalingDeterminant),s.multiplyAtIndex(1,this._scalingDeterminant),s.multiplyAtIndex(2,this._scalingDeterminant),s.decompose(void 0,i,void 0)}}getRotationMatrix(e=pt.LOCAL,t){const i=D.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=pt.LOCAL,t,i){if(e==pt.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(i);else{const s=Ut._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),s):s.copyFrom(r),s.multiplyAtIndex(0,this._scalingDeterminant),s.multiplyAtIndex(1,this._scalingDeterminant),s.multiplyAtIndex(2,this._scalingDeterminant),s.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){const i=m.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=Ut._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&s&&r.multiplyToRef(s,r),m.TransformCoordinatesToRef(e,r,i)}getLocalPositionFromAbsolute(e,t=null){const i=m.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=Ut._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&s&&r.multiplyToRef(s,r),r.invert(),m.TransformCoordinatesToRef(e,r,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}}Ut._TmpVecs=Xi.BuildArray(2,m.Zero);Ut._TmpQuat=Q.Identity();Ut._TmpMats=Xi.BuildArray(5,D.Identity);class NE{get syncRoot(){return this._syncRoot}get masterFrame(){return this._runtimeAnimations.length===0?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(e===-1){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++)this._runtimeAnimations[t]._prepareForSpeedRatioChange(e);this._speedRatio=e,this._goToFrame!==null&&this.goToFrame(this._goToFrame)}get elapsedTime(){return this._localDelayOffset===null?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,s=100,r=!1,n=1,o,l,h,c=!1,u=0){this.target=t,this.fromFrame=i,this.toFrame=s,this.loopAnimation=r,this.onAnimationEnd=o,this.onAnimationLoop=h,this.isAdditive=c,this.playOrder=u,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new G,this.onAnimationLoopObservable=new G,this._scene=e,l&&this.appendAnimations(t,l),this._speedRatio=n,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){const t=this._scene._activeAnimatables.indexOf(this);t>-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){const s=t[i],r=new Ev(e,s,this._scene,this);r._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){const t=this._runtimeAnimations;if(t[0]){const i=t[0].animation.framePerSecond;this._frameToSyncFromJump=this._frameToSyncFromJump??t[0].currentFrame;const s=this.speedRatio===0?0:(e-this._frameToSyncFromJump)/i*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let i=0;i<t.length;i++)t[i].goToFrame(e);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1){if(e||t){const s=this._scene._activeAnimatables.indexOf(this);if(s>-1){const r=this._runtimeAnimations;for(let n=r.length-1;n>=0;n--){const o=r[n];e&&o.animation.name!=e||t&&!t(o.target)||(o.dispose(),r.splice(n,1))}r.length==0&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);const r=this._runtimeAnimations;for(let n=0;n<r.length;n++)r[n].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise(e=>{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,this._weight===0)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s<i.length;s++){const n=i[s].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||n}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(s=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(s,1),s=0;s<i.length;s++)i[s].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}}Ee.prototype._animate=function(a){if(!this.animationsEnabled)return;const e=Zi.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=a!==void 0?a:this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(t.length===0)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let s=0;s<t.length;s++){const r=t[s];!r._animate(i)&&r.disposeOnEnd&&s--}this._processLateAnimationBindings()};Ee.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((a,e)=>a.playOrder-e.playOrder)};Ee.prototype.beginWeightedAnimation=function(a,e,t,i=1,s,r=1,n,o,l,h,c=!1){const u=this.beginAnimation(a,e,t,s,r,n,o,!1,l,h,c);return u.weight=i,u};Ee.prototype.beginAnimation=function(a,e,t,i,s=1,r,n,o=!0,l,h,c=!1){e>t&&s>0&&(s*=-1),o&&this.stopAnimation(a,void 0,l),n||(n=new NE(this,a,e,t,i,s,r,void 0,h,c));const u=l?l(a):!0;if(a.animations&&u&&n.appendAnimations(a,a.animations),a.getAnimatables){const d=a.getAnimatables();for(let f=0;f<d.length;f++)this.beginAnimation(d[f],e,t,i,s,r,n,o,l,h)}return n.reset(),n};Ee.prototype.beginHierarchyAnimation=function(a,e,t,i,s,r=1,n,o,l=!0,h,c,u=!1){const d=a.getDescendants(e),f=[];f.push(this.beginAnimation(a,t,i,s,r,n,o,l,h,void 0,u));for(const _ of d)f.push(this.beginAnimation(_,t,i,s,r,n,o,l,h,void 0,u));return f};Ee.prototype.beginDirectAnimation=function(a,e,t,i,s,r,n,o,l=!1){if(r===void 0&&(r=1),t>i&&r>0)r*=-1;else if(i>t&&r<0){const c=i;i=t,t=c}return new NE(this,a,t,i,s,r,n,e,o,l)};Ee.prototype.beginDirectHierarchyAnimation=function(a,e,t,i,s,r,n,o,l,h=!1){const c=a.getDescendants(e),u=[];u.push(this.beginDirectAnimation(a,t,i,s,r,n,o,l,h));for(const d of c)u.push(this.beginDirectAnimation(d,t,i,s,r,n,o,l,h));return u};Ee.prototype.getAnimatableByTarget=function(a){for(let e=0;e<this._activeAnimatables.length;e++)if(this._activeAnimatables[e].target===a)return this._activeAnimatables[e];return null};Ee.prototype.getAllAnimatablesByTarget=function(a){const e=[];for(let t=0;t<this._activeAnimatables.length;t++)this._activeAnimatables[t].target===a&&e.push(this._activeAnimatables[t]);return e};Ee.prototype.stopAnimation=function(a,e,t){const i=this.getAllAnimatablesByTarget(a);for(const s of i)s.stop(e,t)};Ee.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let a=0;a<this._activeAnimatables.length;a++)this._activeAnimatables[a].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(const a of this.animationGroups)a.stop()};Ee.prototype._registerTargetForLateAnimationBinding=function(a,e){const t=a.target;this._registeredForLateAnimationBindings.pushNoDuplicate(t),t._lateAnimationHolders||(t._lateAnimationHolders={}),t._lateAnimationHolders[a.targetPath]||(t._lateAnimationHolders[a.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:e}),a.isAdditive?(t._lateAnimationHolders[a.targetPath].additiveAnimations.push(a),t._lateAnimationHolders[a.targetPath].totalAdditiveWeight+=a.weight):(t._lateAnimationHolders[a.targetPath].animations.push(a),t._lateAnimationHolders[a.targetPath].totalWeight+=a.weight)};Ee.prototype._processLateAnimationBindingsForMatrices=function(a){if(a.totalWeight===0&&a.totalAdditiveWeight===0)return a.originalValue;let e=1;const t=U.Vector3[0],i=U.Vector3[1],s=U.Quaternion[0];let r=0;const n=a.animations[0],o=a.originalValue;let l=1,h=!1;if(a.totalWeight<1)l=1-a.totalWeight,o.decompose(i,s,t);else{if(r=1,e=a.totalWeight,l=n.weight/e,l==1)if(a.totalAdditiveWeight)h=!0;else return n.currentValue;n.currentValue.decompose(i,s,t)}if(!h){i.scaleInPlace(l),t.scaleInPlace(l),s.scaleInPlace(l);for(let u=r;u<a.animations.length;u++){const d=a.animations[u];if(d.weight===0)continue;l=d.weight/e;const f=U.Vector3[2],_=U.Vector3[3],p=U.Quaternion[1];d.currentValue.decompose(_,p,f),_.scaleAndAddToRef(l,i),p.scaleAndAddToRef(Q.Dot(s,p)>0?l:-l,s),f.scaleAndAddToRef(l,t)}s.normalize()}for(let u=0;u<a.additiveAnimations.length;u++){const d=a.additiveAnimations[u];if(d.weight===0)continue;const f=U.Vector3[2],_=U.Vector3[3],p=U.Quaternion[1];d.currentValue.decompose(_,p,f),_.multiplyToRef(i,_),m.LerpToRef(i,_,d.weight,i),s.multiplyToRef(p,p),Q.SlerpToRef(s,p,d.weight,s),f.scaleAndAddToRef(d.weight,t)}const c=n?n._animationState.workValue:U.Matrix[0].clone();return D.ComposeToRef(i,s,t,c),c};Ee.prototype._processLateAnimationBindingsForQuaternions=function(a,e){if(a.totalWeight===0&&a.totalAdditiveWeight===0)return e;const t=a.animations[0],i=a.originalValue;let s=e;if(a.totalWeight===0&&a.totalAdditiveWeight>0)s.copyFrom(i);else if(a.animations.length===1){if(Q.SlerpToRef(i,t.currentValue,Math.min(1,a.totalWeight),s),a.totalAdditiveWeight===0)return s}else if(a.animations.length>1){let r=1,n,o;if(a.totalWeight<1){const h=1-a.totalWeight;n=[],o=[],n.push(i),o.push(h)}else{if(a.animations.length===2&&(Q.SlerpToRef(a.animations[0].currentValue,a.animations[1].currentValue,a.animations[1].weight/a.totalWeight,e),a.totalAdditiveWeight===0))return e;n=[],o=[],r=a.totalWeight}for(let h=0;h<a.animations.length;h++){const c=a.animations[h];n.push(c.currentValue),o.push(c.weight/r)}let l=0;for(let h=0;h<n.length;){if(!h){Q.SlerpToRef(n[h],n[h+1],o[h+1]/(o[h]+o[h+1]),e),s=e,l=o[h]+o[h+1],h+=2;continue}l+=o[h],Q.SlerpToRef(s,n[h],o[h]/l,s),h++}}for(let r=0;r<a.additiveAnimations.length;r++){const n=a.additiveAnimations[r];n.weight!==0&&(s.multiplyToRef(n.currentValue,U.Quaternion[0]),Q.SlerpToRef(s,U.Quaternion[0],n.weight,s))}return s};Ee.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let a=0;a<this._registeredForLateAnimationBindings.length;a++){const e=this._registeredForLateAnimationBindings.data[a];for(const t in e._lateAnimationHolders){const i=e._lateAnimationHolders[t],s=i.animations[0],r=i.originalValue;if(r==null)continue;const n=K.AllowMatrixDecomposeForInterpolation&&r.m;let o=e[t];if(n)o=this._processLateAnimationBindingsForMatrices(i);else if(r.w!==void 0)o=this._processLateAnimationBindingsForQuaternions(i,o||Q.Identity());else{let h=0,c=1;const u=s&&s._animationState.loopMode===K.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;if(i.totalWeight<1)u?o=r.clone?r.clone():r:s&&r.scale?o=r.scale(1-i.totalWeight):s?o=r*(1-i.totalWeight):r.clone?o=r.clone():o=r;else if(s){c=i.totalWeight;const d=s.weight/c;d!==1?s.currentValue.scale?o=s.currentValue.scale(d):o=s.currentValue*d:o=s.currentValue,u&&(o.addToRef?o.addToRef(r,o):o+=r),h=1}for(let d=h;d<i.animations.length;d++){const f=i.animations[d],_=f.weight/c;if(_)f.currentValue.scaleAndAddToRef?f.currentValue.scaleAndAddToRef(_,o):o+=f.currentValue*_;else continue}for(let d=0;d<i.additiveAnimations.length;d++){const f=i.additiveAnimations[d],_=f.weight;if(_)f.currentValue.scaleAndAddToRef?f.currentValue.scaleAndAddToRef(_,o):o+=f.currentValue*_;else continue}}e[t]=o}e._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}};Ut.prototype.copyAnimationRange=function(a,e,t,i=!1,s=null){this.animations.length===0&&(this.animations.push(new K(this.name,"_matrix",a.animations[0].framePerSecond,K.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));const r=a.animations[0].getRange(e);if(!r)return!1;const n=r.from,o=r.to,l=a.animations[0].getKeys(),h=a.length,c=a.getParent(),u=this.getParent(),d=i&&c&&h&&this.length&&h!==this.length,f=d&&u&&c?u.length/c.length:1,_=i&&!u&&s&&(s.x!==1||s.y!==1||s.z!==1),p=this.animations[0].getKeys();let g,x,T;for(let S=0,C=l.length;S<C;S++)g=l[S],g.frame>=n&&g.frame<=o&&(i?(T=g.value.clone(),d?(x=T.getTranslation(),T.setTranslation(x.scaleInPlace(f))):_&&s?(x=T.getTranslation(),T.setTranslation(x.multiplyInPlace(s))):T=g.value):T=g.value,p.push({frame:g.frame+t,value:T}));return this.animations[0].createRange(e,n+t,o+t),!0};var Al;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(Al||(Al={}));class Bn{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new Bn(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new Bn(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=ge.Clamp(s,-1,1);const r=Math.acos(s);return new Bn(r)}static FromRadians(e){return new Bn(e)}static FromDegrees(e){return new Bn(e*Math.PI/180)}}class jv{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new Z((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Bn.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=Bn.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=Bn.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?Al.CW:Al.CCW,this.angle=Bn.FromDegrees(this.orientation===Al.CW?l-c:c-l)}}class Cf{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Z(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new Z(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new Z(e,t),l=new Z(i,s),h=new jv(n,o,l);let c=h.angle.radians()/r;h.orientation===Al.CW&&(c*=-1);let u=h.startAngle.radians()+c;for(let d=0;d<r;d++){const f=Math.cos(u)*h.radius+h.centerPoint.x,_=Math.sin(u)*h.radius+h.centerPoint.y;this.addLineTo(f,_),u+=c}return this}addQuadraticCurveTo(e,t,i,s,r=36){if(this.closed)return this;const n=(l,h,c,u)=>(1-l)*(1-l)*h+2*l*(1-l)*c+l*l*u,o=this._points[this._points.length-1];for(let l=0;l<=r;l++){const h=l/r,c=n(h,o.x,e,i),u=n(h,o.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const l=(c,u,d,f,_)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*d+3*c*c*(1-c)*f+c*c*c*_,h=this._points[this._points.length-1];for(let c=0;c<=o;c++){const u=c/o,d=l(u,h.x,e,i,r),f=l(u,h.y,t,s,n);this.addLineTo(d,f)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;r<i;s=r++){let n=this._points[s],o=this._points[r],l=o.x-n.x,h=o.y-n.y;if(Math.abs(h)>Number.EPSILON){if(h<0&&(n=this._points[r],l=-l,o=this._points[s],h=-h),e.y<n.y||e.y>o.y)continue;if(e.y===n.y&&e.x===n.x)return!0;{const c=h*(e.x-n.x)-l*(e.y-n.y);if(c===0)return!0;if(c<0)continue;t=!t}}else{if(e.y!==n.y)continue;if(o.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s<e;i=s++)t+=this._points[i].x*this._points[s].y-this._points[s].x*this._points[i].y;return t*.5}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return Z.Zero();const t=e*this.length();let i=0;for(let s=0;s<this._points.length;s++){const r=(s+1)%this._points.length,n=this._points[s],l=this._points[r].subtract(n),h=l.length()+i;if(t>=i&&t<=h){const c=l.normalize(),u=t-i;return new Z(n.x+c.x*u,n.y+c.y*u)}i=h}return Z.Zero()}static StartingAt(e,t){return new Cf(e,t)}}class bu{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:m.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:D.Identity()};for(let r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._alignTangentsWithPath=s,this._compute(t,s)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?m.TransformCoordinates(m.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?m.TransformCoordinates(m.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?m.TransformCoordinates(m.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let s=0;s<this._curve.length-1;s++){const r=this._curve[s+0],n=this._curve[s+1].subtract(r).normalize(),o=this._distances[s+1]-this._distances[s+0],l=Math.min(Math.max(m.Dot(n,e.subtract(r).normalize()),0)*m.Distance(r,e)/o,1),h=m.Distance(r.add(n.scale(l*o)),e);h<t&&(t=h,i=(this._distances[s+0]+o*l)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1-e*-1%1),t<0&&(t=1-t*-1%1),e>t){const h=e;e=t,t=h}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(r++,l.push(s)),l.push(...i.slice(r,o)),(t!==1||e===1)&&l.push(n),new bu(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;s<e.length;s++)this._curve[s].x=e[s].x,this._curve[s].y=e[s].y,this._curve[s].z=e[s].z;return this._compute(t,i),this}_compute(e,t=!1){const i=this._curve.length;if(i<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();const s=this._tangents[0],r=this._normalVector(s,e);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=m.Cross(s,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;let n,o,l,h,c;for(let u=1;u<i;u++)n=this._getLastNonNullVector(u),u<i-1&&(o=this._getFirstNonNullVector(u),this._tangents[u]=t?o:n.add(o),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+this._curve[u].subtract(this._curve[u-1]).length(),l=this._tangents[u],c=this._binormals[u-1],this._normals[u]=m.Cross(c,l),this._raw||(this._normals[u].length()===0?(h=this._normals[u-1],this._normals[u]=h.clone()):this._normals[u].normalize()),this._binormals[u]=m.Cross(l,this._normals[u]),this._raw||this._binormals[u].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;i.length()===0&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;i.length()===0&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;ge.WithinEpsilon(Math.abs(e.y)/s,1,rt)?ge.WithinEpsilon(Math.abs(e.x)/s,1,rt)?ge.WithinEpsilon(Math.abs(e.z)/s,1,rt)?r=m.Zero():r=new m(0,0,1):r=new m(1,0,0):r=new m(0,-1,0),i=m.Cross(e,r)}else i=m.Cross(e,t),m.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s=i[0],r,n=0;const o=e*this.length();for(let l=1;l<i.length;l++){r=i[l];const h=m.Distance(s,r);if(n+=h,n===o)return this._setPointAtData(e,1,r,l,t);if(n>o){const u=(n-o)/h,d=s.subtract(r),f=r.add(d.scaleInPlace(u));return this._setPointAtData(e,1-u,f,l-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=D.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),h=Q.RotationQuaternionFromAxis(s,r,i),c=Q.RotationQuaternionFromAxis(o,l,n);Q.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class On{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(o,l,h,c)=>(1-o)*(1-o)*l+2*o*(1-o)*h+o*o*c;for(let o=0;o<=s;o++)r.push(new m(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new On(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(l,h,c,u,d)=>(1-l)*(1-l)*(1-l)*h+3*l*(1-l)*(1-l)*c+3*l*l*(1-l)*u+l*l*l*d;for(let l=0;l<=r;l++)n.push(new m(o(l/r,e.x,t.x,i.x,s.x),o(l/r,e.y,t.y,i.y,s.y),o(l/r,e.z,t.z,i.z,s.z)));return new On(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let l=0;l<=r;l++)n.push(m.Hermite(e,t,i,s,l*o));return new On(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const o=e.length;for(let l=0;l<o;l++){n=0;for(let h=0;h<t;h++)s.push(m.CatmullRom(e[l%o],e[(l+1)%o],e[(l+2)%o],e[(l+3)%o],n)),n+=r}s.push(s[0])}else{const o=[];o.push(e[0].clone()),Array.prototype.push.apply(o,e),o.push(e[e.length-1].clone());let l=0;for(;l<o.length-3;l++){n=0;for(let h=0;h<t;h++)s.push(m.CatmullRom(o[l],o[l+1],o[l+2],o[l+3],n)),n+=r}l--,s.push(m.CatmullRom(o[l],o[l+1],o[l+2],o[l+3],n))}return new On(s)}static ArcThru3Points(e,t,i,s=32,r=!1,n=!1){const o=[],l=t.subtract(e),h=i.subtract(t),c=e.subtract(i),u=m.Cross(l,h),d=u.length();if(d<Math.pow(10,-8))return new On(o);const f=l.lengthSquared(),_=h.lengthSquared(),p=c.lengthSquared(),g=u.lengthSquared(),x=l.length(),T=h.length(),S=c.length(),C=.5*x*T*S/d,v=m.Dot(l,c),b=m.Dot(l,h),A=m.Dot(h,c),P=-.5*_*v/g,L=-.5*p*b/g,w=-.5*f*A/g,$=e.scale(P).add(t.scale(L)).add(i.scale(w)),ne=e.subtract($).normalize(),oe=m.Cross(u,ne).normalize();if(n){const re=2*Math.PI/s;for(let ce=0;ce<=2*Math.PI;ce+=re)o.push($.add(ne.scale(C*Math.cos(ce)).add(oe.scale(C*Math.sin(ce)))));o.push(e)}else{const re=1/s;let ce=0,Se=m.Zero();do Se=$.add(ne.scale(C*Math.cos(ce)).add(oe.scale(C*Math.sin(ce)))),o.push(Se),ce+=re;while(!Se.equalsWithEpsilon(i,C*re*1.1));o.push(i),r&&o.push(e)}return new On(o)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){const t=this._points[this._points.length-1],i=this._points.slice(),s=e.getPoints();for(let n=1;n<s.length;n++)i.push(s[n].subtract(s[0]).add(t));return new On(i)}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}}class Us{constructor(){this._easingMode=Us.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case Us.EASINGMODE_EASEIN:return this.easeInCore(e);case Us.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}Us.EASINGMODE_EASEIN=0;Us.EASINGMODE_EASEOUT=1;Us.EASINGMODE_EASEINOUT=2;class qv extends Us{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Qv extends Us{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class Zv extends Us{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class Jv extends Us{easeInCore(e){return e*e}}class FE extends Us{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class mm{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new mm(this.frame,this.action,this.onlyOnce)}}class eb{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Nn{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t<this._animatables.length;++t){const i=this._animatables[t];!this.mask||this.mask.disabled||this.mask.retainsTarget(i.target.name)?(this._numActiveAnimatables++,i.paused&&i.restart()):i.paused||i.pause()}}removeUnmaskedAnimations(){if(!(!this.mask||this.mask.disabled)){for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){const t=this._targetedAnimations[e];this.mask.retainsTarget(t.target.name)||(this._targetedAnimations.splice(e,1),--e)}}}get from(){return this._from}set from(e){if(this._from!==e){this._from=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.fromFrame=this._from}}}get to(){return this._to}set to(e){if(this._to!==e){this._to=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.toFrame=this._to}}}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let 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()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,e!==null))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,e!==null))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=e??this._from,t=t??this._to;const i=this.targetedAnimations[0].animation.framePerSecond*this._speedRatio;return(t-e)/i}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.MAX_VALUE;if(i)for(const l of e)l.from<r&&(r=l.from),l.to>n&&(n=l.to);const o=new Nn(e[0].name+"_merged",e[0]._scene,s);for(const l of e){i&&l.normalize(r,n);for(const h of l.targetedAnimations)o.addTargetedAnimation(h.animation,h.target);t&&l.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new G,this.onAnimationLoopObservable=new G,this.onAnimationGroupLoopObservable=new G,this.onAnimationGroupEndObservable=new G,this.onAnimationGroupPauseObservable=new G,this.onAnimationGroupPlayObservable=new G,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||Ae.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new eb;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._enableBlending!==null&&(e.enableBlending=this._enableBlending),this._blendingSpeed!==null&&(e.blendingSpeed=this._blendingSpeed),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],o=r[r.length-1];if(n.frame>e){const l={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,l)}if(o.frame<t){const l={frame:t,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation};r.push(l)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,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 o=this._targetedAnimations[n],l=this._scene.beginDirectAnimation(o.target,[o.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);l.weight=this._weight,l.playOrder=this._playOrder,l.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,n),this._animatables.push(l)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._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.syncWithMask(),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 Nn(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const 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.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return ft&&ft.HasTags(this)&&(e.tags=ft.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new Nn(e.name,t,e.weight,e.playOrder);for(let s=0;s<e.targetedAnimations.length;s++){const r=e.targetedAnimations[s],n=K.Parse(r.animation),o=r.targetId;if(r.animation.property==="influence"){const l=t.getMorphTargetById(o);l&&i.addTargetedAnimation(n,l)}else{const l=t.getNodeById(o);l!=null&&i.addTargetedAnimation(n,l)}}return ft&&ft.AddTagsTo(i,e.tags),e.from!==null&&e.to!==null&&i.normalize(e.from,e.to),e.speedRatio!==void 0&&(i._speedRatio=e.speedRatio),e.loopAnimation!==void 0&&(i._loopAnimation=e.loopAnimation),e.isAdditive!==void 0&&(i._isAdditive=e.isAdditive),e.weight!==void 0&&(i._weight=e.weight),e.playOrder!==void 0&&(i._playOrder=e.playOrder),e.enableBlending!==void 0&&(i._enableBlending=e.enableBlending),e.blendingSpeed!==void 0&&(i._blendingSpeed=e.blendingSpeed),e.metadata!==void 0&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;typeof t=="object"?n=t:n={referenceFrame:t,range:i,cloneOriginalAnimationGroup:s,clonedAnimationName:r};let o=e;n.cloneOriginalAnimationGroup&&(o=e.clone(n.clonedAnimationGroupName||o.name));const l=o.targetedAnimations;for(let h=0;h<l.length;h++){const c=l[h];c.animation=K.MakeAnimationAdditive(c.animation,n)}if(o.isAdditive=!0,n.clipKeys){let h=Number.MAX_VALUE,c=-Number.MAX_VALUE;const u=o.targetedAnimations;for(let d=0;d<u.length;d++){const p=u[d].animation.getKeys();h>p[0].frame&&(h=p[0].frame),c<p[p.length-1].frame&&(c=p[p.length-1].frame)}o._from=h,o._to=c}return o}static ClipKeys(e,t,i,s,r){const n=e.clone(s||e.name);return Nn.ClipKeysInPlace(n,t,i,r)}static ClipKeysInPlace(e,t,i,s){return Nn.ClipInPlace(e,t,i,s,!1)}static ClipFrames(e,t,i,s,r){const n=e.clone(s||e.name);return Nn.ClipFramesInPlace(n,t,i,r)}static ClipFramesInPlace(e,t,i,s){return Nn.ClipInPlace(e,t,i,s,!0)}static ClipInPlace(e,t,i,s,r=!1){let n=Number.MAX_VALUE,o=-Number.MAX_VALUE;const l=e.targetedAnimations;for(let h=0;h<l.length;h++){const c=l[h],u=s?c.animation:c.animation.clone();r&&(u.createKeyForFrame(t),u.createKeyForFrame(i));const d=u.getKeys(),f=[];let _=Number.MAX_VALUE;for(let p=0;p<d.length;p++){const g=d[p];if(!r&&p>=t&&p<=i||r&&g.frame>=t&&g.frame<=i){const x={frame:g.frame,value:g.value.clone?g.value.clone():g.value,inTangent:g.inTangent,outTangent:g.outTangent,interpolation:g.interpolation,lockedTangent:g.lockedTangent};_===Number.MAX_VALUE&&(_=x.frame),x.frame-=_,f.push(x)}}if(f.length===0){l.splice(h,1),h--;continue}n>f[0].frame&&(n=f[0].frame),o<f[f.length-1].frame&&(o=f[f.length-1].frame),u.setKeys(f,!0),c.animation=u}return e._from=n,e._to=o,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}var lx;(function(a){a[a.Include=0]="Include",a[a.Exclude=1]="Exclude"})(lx||(lx={}));function Zd(a,e,t){try{const i=a.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function tb(a=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>a?(e=r,setTimeout(()=>{Zd(t,i,s)},0)):Zd(t,i,s)}}function wE(a,e,t,i,s){const r=()=>{let n;const o=l=>{l.done?t(l.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(a,o,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function gm(a,e){let t;return wE(a,Zd,i=>t=i,i=>{throw i},e),t}function LE(a,e,t){return new Promise((i,s)=>{wE(a,e,i,s,t)})}function ib(a,e){return(...t)=>gm(a(...t),e)}class Vr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Vr(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 Vr(this.x,this.y,this.width,this.height)}}class ve extends Ct{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===ve.PERSPECTIVE_CAMERA)this.fovMode===ve.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i),this._position=m.Zero(),this._upVector=m.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ve.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Vr(0,0,1,1),this.layerMask=268435455,this.fovMode=ve.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ve.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new G,this.onProjectionMatrixChangedObservable=new G,this.onAfterCheckInputsObservable=new G,this.onRestoreStateObservable=new G,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new D,this._postProcesses=new Array,this._activeMeshes=new Wi(256),this._globalPosition=m.Zero(),this._computedViewMatrix=D.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=D.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Q.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 m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return super._isSynchronized()?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!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===ve.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==ve.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?(O.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 D.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var r,n,o;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===ve.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let l;i.useRightHandedSystem?l=D.PerspectiveFovRHToRef:l=D.PerspectiveFovLHToRef,l(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ve.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const l=t.getRenderWidth()/2,h=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?D.ObliqueOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):D.OrthoOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?D.ObliqueOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):D.OrthoOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(r=this.oblique)==null?void 0:r.angle,this._cache.obliqueLength=(n=this.oblique)==null?void 0:n.length,this._cache.obliqueOffset=(o=this.oblique)==null?void 0:o.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?m.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Or.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Or.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 Ge("Ray")}getForwardRayToRef(e,t=100,i,s){throw Ge("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){const s=this._parentContainer.cameras.indexOf(this);s>-1&&this._parentContainer.cameras.splice(s,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==ve.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const 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=X.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ve.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const s=this.createRigCamera(this.name+"_R",1);s&&(s._isRightCamera=!0),i&&s&&(this._rigCameras.push(i),this._rigCameras.push(s))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return D.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=X.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===ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=_e.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),_e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=_e.Clone(ve.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=m.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){m.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,s=0,r=!0){const n=Ct.Construct(e,t,i,{interaxial_distance:s,isStereoscopicSideBySide:r});return n||(()=>ve._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ve.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=_e.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=m.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(m.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(m.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 o=e.animations[n],l=Si("BABYLON.Animation");l&&r.animations.push(l.Parse(o))}Ct.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}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}ve._CreateDefaultParsedCamera=(a,e)=>{throw Ge("UniversalCamera")};ve.PERSPECTIVE_CAMERA=0;ve.ORTHOGRAPHIC_CAMERA=1;ve.FOVMODE_VERTICAL_FIXED=0;ve.FOVMODE_HORIZONTAL_FIXED=1;ve.RIG_MODE_NONE=0;ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;ve.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;ve.RIG_MODE_STEREOSCOPIC_INTERLACED=14;ve.RIG_MODE_VR=20;ve.RIG_MODE_CUSTOM=22;ve.ForceAttachControlToAlwaysPreventDefault=!1;E([bs("position")],ve.prototype,"_position",void 0);E([bs("upVector")],ve.prototype,"_upVector",void 0);E([I()],ve.prototype,"orthoLeft",null);E([I()],ve.prototype,"orthoRight",null);E([I()],ve.prototype,"orthoBottom",null);E([I()],ve.prototype,"orthoTop",null);E([I()],ve.prototype,"fov",void 0);E([I()],ve.prototype,"projectionPlaneTilt",void 0);E([I()],ve.prototype,"minZ",void 0);E([I()],ve.prototype,"maxZ",void 0);E([I()],ve.prototype,"inertia",void 0);E([I()],ve.prototype,"mode",null);E([I()],ve.prototype,"layerMask",void 0);E([I()],ve.prototype,"fovMode",void 0);E([I()],ve.prototype,"cameraRigMode",void 0);E([I()],ve.prototype,"interaxialDistance",void 0);E([I()],ve.prototype,"isStereoscopicSideBySide",void 0);class rp{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class mn{constructor(e,t,i){this.vectors=Xi.BuildArray(8,m.Zero),this.center=m.Zero(),this.centerWorld=m.Zero(),this.extendSize=m.Zero(),this.extendSizeWorld=m.Zero(),this.directions=Xi.BuildArray(3,m.Zero),this.vectorsWorld=Xi.BuildArray(8,m.Zero),this.minimumWorld=m.Zero(),this.maximumWorld=m.Zero(),this.minimum=m.Zero(),this.maximum=m.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,o=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,l,h),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(o,l,h),c[2].copyFromFloats(o,r,n),c[3].copyFromFloats(s,l,n),c[4].copyFromFloats(s,r,h),c[5].copyFromFloats(o,l,n),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(o,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||D.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=mn._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),o=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)r[o].copyFrom(n[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){const l=r[o];m.TransformCoordinatesToRef(n[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}m.FromArrayToRef(e.m,0,s[0]),m.FromArrayToRef(e.m,4,s[1]),m.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return mn.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return mn.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,f=-rt;return!(o-c<f||f>c-s||l-u<f||f>u-r||h-d<f||f>d-n)}intersectsSphere(e){return mn.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,o=i.z,l=s.x,h=s.y,c=s.z,u=e.x,d=e.y,f=e.z,_=t.x,p=t.y,g=t.z;return!(l<u||r>_||h<d||n>p||c<f||o>g)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=mn._TmpVector3[0];return m.ClampToRef(i,e,t,r),m.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}}mn._TmpVector3=Xi.BuildArray(3,m.Zero);class ua{constructor(e,t,i){this.center=m.Zero(),this.centerWorld=m.Zero(),this.minimum=m.Zero(),this.maximum=m.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=m.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||D.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ua._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{m.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ua._TmpVector3[0];m.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=m.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=m.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 ua(this._TmpVector3[0],this._TmpVector3[2]);return i?s._worldMatrix=i:s._worldMatrix=D.Identity(),s}}ua._TmpVector3=Xi.BuildArray(3,m.Zero);const R_={min:0,max:0},I_={min:0,max:0},hx=(a,e,t)=>{const i=m.Dot(e.centerWorld,a),s=Math.abs(m.Dot(e.directions[0],a))*e.extendSize.x,r=Math.abs(m.Dot(e.directions[1],a))*e.extendSize.y,n=Math.abs(m.Dot(e.directions[2],a))*e.extendSize.z,o=s+r+n;t.min=i-o,t.max=i+o},tr=(a,e,t)=>(hx(a,e,R_),hx(a,t,I_),!(R_.min>I_.max||I_.min>R_.max));class or{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new mn(e,t,i),this.boundingSphere=new ua(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=or._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=or._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=m.Minimize(this.minimum,e),i=m.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=U.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=U.Vector3[0];return m.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),m.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,or._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(!ua.Intersects(this.boundingSphere,e.boundingSphere)||!mn.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!tr(i.directions[0],i,s)||!tr(i.directions[1],i,s)||!tr(i.directions[2],i,s)||!tr(s.directions[0],i,s)||!tr(s.directions[1],i,s)||!tr(s.directions[2],i,s)||!tr(m.Cross(i.directions[0],s.directions[0]),i,s)||!tr(m.Cross(i.directions[0],s.directions[1]),i,s)||!tr(m.Cross(i.directions[0],s.directions[2]),i,s)||!tr(m.Cross(i.directions[1],s.directions[0]),i,s)||!tr(m.Cross(i.directions[1],s.directions[1]),i,s)||!tr(m.Cross(i.directions[1],s.directions[2]),i,s)||!tr(m.Cross(i.directions[2],s.directions[0]),i,s)||!tr(m.Cross(i.directions[2],s.directions[1]),i,s)||!tr(m.Cross(i.directions[2],s.directions[2]),i,s))}}or._TmpVector3=Xi.BuildArray(2,m.Zero);class vf{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o<i+s;o++){const l=t[o]*3,h=e[l],c=e[l+1],u=e[l+2];r.minimizeInPlaceFromFloats(h,c,u),n.maximizeInPlaceFromFloats(h,c,u)}}static extractMinAndMax(e,t,i,s,r,n){for(let o=t,l=t*s;o<t+i;o++,l+=s){const h=e[l],c=e[l+1],u=e[l+2];r.minimizeInPlaceFromFloats(h,c,u),n.maximizeInPlaceFromFloats(h,c,u)}}}E([Qa.filter((...[a,e])=>!Array.isArray(a)&&!Array.isArray(e))],vf,"extractMinAndMaxIndexed",null);E([Qa.filter((...[a])=>!Array.isArray(a))],vf,"extractMinAndMax",null);function sb(a,e,t,i,s=null){const r=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return vf.extractMinAndMaxIndexed(a,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 Au(a,e,t,i=null,s){const r=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),vf.extractMinAndMax(a,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 Ss{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())==null?void 0:e.defines}set materialDefines(e){const t=this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Bi(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])==null||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:((e=this._getDrawWrapper())==null?void 0:e.effect)??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const 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,o,l=!0){return new Ss(e,t,i,s,r,n,o,l)}constructor(e,t,i,s,r,n,o,l=!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=o||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,l&&(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.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const i=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==i&&(this._currentMaterial=i,this.resetDrawCache()),i}}else return e?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(y.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=sb(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new or(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 o=3,l=!1;switch(n.fillMode){case 3:case 5:case 6:case 8:return null;case 7:o=1,l=!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,o,l,s,r)}_intersectLines(e,t,i,s,r){let n=null;for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=2){const l=t[i[o]],h=t[i[o+1]],c=e.intersectionSegment(l,h,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new rp(null,null,c),n.faceId=o/2,r))break}return n}_intersectUnIndexedLines(e,t,i,s,r){let n=null;for(let o=this.verticesStart;o<this.verticesStart+this.verticesCount;o+=2){const l=t[o],h=t[o+1],c=e.intersectionSegment(l,h,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new rp(null,null,c),n.faceId=o/2,r))break}return n}_intersectTriangles(e,t,i,s,r,n,o){let l=null,h=-1;for(let c=this.indexStart;c<this.indexStart+this.indexCount-(3-s);c+=s){h++;const u=i[c],d=i[c+1],f=i[c+2];if(r&&f===4294967295){c+=2;continue}const _=t[u],p=t[d],g=t[f];if(!_||!p||!g||o&&!o(_,p,g,e,u,d,f))continue;const x=e.intersectsTriangle(_,p,g);if(x){if(x.distance<0)continue;if((n||!l||x.distance<l.distance)&&(l=x,l.faceId=h,n))break}}return l}_intersectUnIndexedTriangles(e,t,i,s,r){let n=null;for(let o=this.verticesStart;o<this.verticesStart+this.verticesCount;o+=3){const l=t[o],h=t[o+1],c=t[o+2];if(r&&!r(l,h,c,e,-1,-1,-1))continue;const u=e.intersectsTriangle(l,h,c);if(u){if(u.distance<0)continue;if((s||!n||u.distance<n.distance)&&(n=u,n.faceId=o/3,s))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new Ss(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 or(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 o=Number.MAX_VALUE,l=-Number.MAX_VALUE;const c=(r||s).getIndices();for(let u=t;u<t+i;u++){const d=c[u];d<o&&(o=d),d>l&&(l=d)}return new Ss(e,o,l-o+1,t,i,s,r,n)}}class kd{}class le{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=ib(this._applyToCoroutine.bind(this)),this.uniqueId=le._UniqueIDGenerator,le._UniqueIDGenerator++}set(e,t){switch(e.length||O.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case y.PositionKind:this.positions=e;break;case y.NormalKind:this.normals=e;break;case y.TangentKind:this.tangents=e;break;case y.UVKind:this.uvs=e;break;case y.UV2Kind:this.uvs2=e;break;case y.UV3Kind:this.uvs3=e;break;case y.UV4Kind:this.uvs4=e;break;case y.UV5Kind:this.uvs5=e;break;case y.UV6Kind:this.uvs6=e;break;case y.ColorKind:this.colors=e;break;case y.MatricesIndicesKind:this.matricesIndices=e;break;case y.MatricesWeightsKind:this.matricesWeights=e;break;case y.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case y.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(y.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(y.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(y.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(y.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(y.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(y.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(y.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(y.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(y.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(y.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(y.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(y.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(y.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(y.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const s=e;s.subMeshes=[];for(const r of this.materialInfos)new Ss(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(y.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(y.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(y.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(y.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(y.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(y.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(y.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(y.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(y.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(y.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(y.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(y.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(y.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(y.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let o=i;o<i+s;o+=3)m.FromArrayToRef(e,o,r),m.TransformCoordinatesToRef(r,t,n),e[o]=n.x,e[o+1]=n.y,e[o+2]=n.z}static _TransformVector3Normals(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let o=i;o<i+s;o+=3)m.FromArrayToRef(e,o,r),m.TransformNormalToRef(r,t,n),e[o]=n.x,e[o+1]=n.y,e[o+2]=n.z}static _TransformVector4Normals(e,t,i=0,s=e.length){const r=U.Vector4[0],n=U.Vector4[1];for(let o=i;o<i+s;o+=4)we.FromArrayToRef(e,o,r),we.TransformNormalToRef(r,t,n),e[o]=n.x,e[o+1]=n.y,e[o+2]=n.z,e[o+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&&le._TransformVector3Coordinates(this.positions,e),this.normals&&le._TransformVector3Normals(this.normals,e),this.tangents&&le._TransformVector4Normals(this.tangents,e),t&&this.indices&&le._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const e=[];for(const t of this.materialInfos){const i=new le;if(this.positions&&(i.positions=this.positions.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(t.verticesStart*3,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(t.verticesStart*2,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(t.verticesStart*4,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let r=t.indexStart;r<t.indexStart+t.indexCount;r++)i.indices.push(this.indices[r]-t.verticesStart)}const s=new kd;s.indexStart=0,s.indexCount=i.indices?i.indices.length:0,s.materialIndex=t.materialIndex,s.verticesStart=0,s.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[s],e.push(i)}return e}merge(e,t=!1,i=!1,s=!1,r=!1){const n=Array.isArray(e)?e.map(o=>({vertexData:o})):[{vertexData:e}];return gm(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){var f,_;this._validate();let l=t.map(p=>p.vertexData),h=this;if(o)for(const p of l)p&&(p._validate(),!this.normals&&p.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&p.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&p.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&p.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&p.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&p.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&p.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&p.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&p.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&p.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&p.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&p.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&p.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const p of l)if(p){if(o)this.normals&&!p.normals&&(p.normals=new Float32Array(p.positions.length)),this.tangents&&!p.tangents&&(p.tangents=new Float32Array(p.positions.length/3*4)),this.uvs&&!p.uvs&&(p.uvs=new Float32Array(p.positions.length/3*2)),this.uvs2&&!p.uvs2&&(p.uvs2=new Float32Array(p.positions.length/3*2)),this.uvs3&&!p.uvs3&&(p.uvs3=new Float32Array(p.positions.length/3*2)),this.uvs4&&!p.uvs4&&(p.uvs4=new Float32Array(p.positions.length/3*2)),this.uvs5&&!p.uvs5&&(p.uvs5=new Float32Array(p.positions.length/3*2)),this.uvs6&&!p.uvs6&&(p.uvs6=new Float32Array(p.positions.length/3*2)),this.colors&&!p.colors&&(p.colors=new Float32Array(p.positions.length/3*4),p.colors.fill(1)),this.matricesIndices&&!p.matricesIndices&&(p.matricesIndices=new Float32Array(p.positions.length/3*4)),this.matricesWeights&&!p.matricesWeights&&(p.matricesWeights=new Float32Array(p.positions.length/3*4)),this.matricesIndicesExtra&&!p.matricesIndicesExtra&&(p.matricesIndicesExtra=new Float32Array(p.positions.length/3*4)),this.matricesWeightsExtra&&!p.matricesWeightsExtra&&(p.matricesWeightsExtra=new Float32Array(p.positions.length/3*4));else if(p._validate(),!this.normals!=!p.normals||!this.tangents!=!p.tangents||!this.uvs!=!p.uvs||!this.uvs2!=!p.uvs2||!this.uvs3!=!p.uvs3||!this.uvs4!=!p.uvs4||!this.uvs5!=!p.uvs5||!this.uvs6!=!p.uvs6||!this.colors!=!p.colors||!this.matricesIndices!=!p.matricesIndices||!this.matricesWeights!=!p.matricesWeights||!this.matricesIndicesExtra!=!p.matricesIndicesExtra||!this.matricesWeightsExtra!=!p.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let p=0,g=0,x=0;const T=[];let S=null;const C=[];for(const b of this.splitBasedOnMaterialID())C.push({vertexData:b,transform:e});for(const b of t)if(b.vertexData)for(const A of b.vertexData.splitBasedOnMaterialID())C.push({vertexData:A,transform:b.transform});C.sort((b,A)=>{const P=b.vertexData.materialInfos?b.vertexData.materialInfos[0].materialIndex:0,L=A.vertexData.materialInfos?A.vertexData.materialInfos[0].materialIndex:0;return P>L?1:P===L?0:-1});for(const b of C){const A=b.vertexData;if(A.materialInfos?p=A.materialInfos[0].materialIndex:p=0,S&&S.materialIndex===p)S.indexCount+=A.indices.length,S.verticesCount+=A.positions.length/3;else{const P=new kd;P.materialIndex=p,P.indexStart=g,P.indexCount=A.indices.length,P.verticesStart=x,P.verticesCount=A.positions.length/3,T.push(P),S=P}g+=A.indices.length,x+=A.positions.length/3}const v=C.splice(0,1)[0];h=v.vertexData,e=v.transform,l=C.map(b=>b.vertexData),t=C,this.materialInfos=T}const c=l.reduce((p,g)=>{var x;return p+(((x=g.indices)==null?void 0:x.length)??0)},((f=h.indices)==null?void 0:f.length)??0);let d=r||l.some(p=>p.indices===h.indices)?(_=h.indices)==null?void 0:_.slice():h.indices;if(c>0){let p=(d==null?void 0:d.length)??0;if(d||(d=new Array(c)),d.length!==c){if(Array.isArray(d))d.length=c;else{const x=i||d instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);x.set(d),d=x}e&&e.determinant()<0&&le._FlipFaces(d,0,p)}let g=h.positions?h.positions.length/3:0;for(const{vertexData:x,transform:T}of t)if(x.indices){for(let S=0;S<x.indices.length;S++)d[p+S]=x.indices[S]+g;T&&T.determinant()<0&&le._FlipFaces(d,p,x.indices.length),g+=x.positions.length/3,p+=x.indices.length,s&&(yield)}}return this.indices=d,this.positions=le._MergeElement(y.PositionKind,h.positions,e,t.map(p=>[p.vertexData.positions,p.transform])),s&&(yield),h.normals&&(this.normals=le._MergeElement(y.NormalKind,h.normals,e,t.map(p=>[p.vertexData.normals,p.transform])),s&&(yield)),h.tangents&&(this.tangents=le._MergeElement(y.TangentKind,h.tangents,e,t.map(p=>[p.vertexData.tangents,p.transform])),s&&(yield)),h.uvs&&(this.uvs=le._MergeElement(y.UVKind,h.uvs,e,t.map(p=>[p.vertexData.uvs,p.transform])),s&&(yield)),h.uvs2&&(this.uvs2=le._MergeElement(y.UV2Kind,h.uvs2,e,t.map(p=>[p.vertexData.uvs2,p.transform])),s&&(yield)),h.uvs3&&(this.uvs3=le._MergeElement(y.UV3Kind,h.uvs3,e,t.map(p=>[p.vertexData.uvs3,p.transform])),s&&(yield)),h.uvs4&&(this.uvs4=le._MergeElement(y.UV4Kind,h.uvs4,e,t.map(p=>[p.vertexData.uvs4,p.transform])),s&&(yield)),h.uvs5&&(this.uvs5=le._MergeElement(y.UV5Kind,h.uvs5,e,t.map(p=>[p.vertexData.uvs5,p.transform])),s&&(yield)),h.uvs6&&(this.uvs6=le._MergeElement(y.UV6Kind,h.uvs6,e,t.map(p=>[p.vertexData.uvs6,p.transform])),s&&(yield)),h.colors&&(this.colors=le._MergeElement(y.ColorKind,h.colors,e,t.map(p=>[p.vertexData.colors,p.transform])),(h.hasVertexAlpha!==void 0||t.some(p=>p.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some(p=>p.vertexData.hasVertexAlpha)),s&&(yield)),h.matricesIndices&&(this.matricesIndices=le._MergeElement(y.MatricesIndicesKind,h.matricesIndices,e,t.map(p=>[p.vertexData.matricesIndices,p.transform])),s&&(yield)),h.matricesWeights&&(this.matricesWeights=le._MergeElement(y.MatricesWeightsKind,h.matricesWeights,e,t.map(p=>[p.vertexData.matricesWeights,p.transform])),s&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=le._MergeElement(y.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map(p=>[p.vertexData.matricesIndicesExtra,p.transform])),s&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=le._MergeElement(y.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map(p=>[p.vertexData.matricesWeightsExtra,p.transform]))),this}static _MergeElement(e,t,i,s){const r=s.filter(l=>l[0]!==null&&l[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((l,h)=>l+h[0].length,t.length),o=e===y.PositionKind?le._TransformVector3Coordinates:e===y.NormalKind?le._TransformVector3Normals:e===y.TangentKind?le._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(n);l.set(t),i&&o(l,i,0,t.length);let h=t.length;for(const[c,u]of r)l.set(c,h),u&&o(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(n);for(let c=0;c<t.length;c++)l[c]=t[c];i&&o(l,i,0,t.length);let h=t.length;for(const[c,u]of r){for(let d=0;d<c.length;d++)l[h+d]=c[d];u&&o(l,u,h,c.length),h+=c.length}return l}}_validate(){if(!this.positions)throw new Sn("Positions are required",ca.MeshInvalidPositionsError);const e=(s,r)=>{const n=y.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(y.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(y.NormalKind,this.normals),this.tangents&&i(y.TangentKind,this.tangents),this.uvs&&i(y.UVKind,this.uvs),this.uvs2&&i(y.UV2Kind,this.uvs2),this.uvs3&&i(y.UV3Kind,this.uvs3),this.uvs4&&i(y.UV4Kind,this.uvs4),this.uvs5&&i(y.UV5Kind,this.uvs5),this.uvs6&&i(y.UV6Kind,this.uvs6),this.colors&&i(y.ColorKind,this.colors),this.matricesIndices&&i(y.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(y.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(y.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(y.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return le.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return le._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return le._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new le;return e.isVerticesDataPresent(y.PositionKind)&&(s.positions=e.getVerticesData(y.PositionKind,t,i)),e.isVerticesDataPresent(y.NormalKind)&&(s.normals=e.getVerticesData(y.NormalKind,t,i)),e.isVerticesDataPresent(y.TangentKind)&&(s.tangents=e.getVerticesData(y.TangentKind,t,i)),e.isVerticesDataPresent(y.UVKind)&&(s.uvs=e.getVerticesData(y.UVKind,t,i)),e.isVerticesDataPresent(y.UV2Kind)&&(s.uvs2=e.getVerticesData(y.UV2Kind,t,i)),e.isVerticesDataPresent(y.UV3Kind)&&(s.uvs3=e.getVerticesData(y.UV3Kind,t,i)),e.isVerticesDataPresent(y.UV4Kind)&&(s.uvs4=e.getVerticesData(y.UV4Kind,t,i)),e.isVerticesDataPresent(y.UV5Kind)&&(s.uvs5=e.getVerticesData(y.UV5Kind,t,i)),e.isVerticesDataPresent(y.UV6Kind)&&(s.uvs6=e.getVerticesData(y.UV6Kind,t,i)),e.isVerticesDataPresent(y.ColorKind)&&(s.colors=e.getVerticesData(y.ColorKind,t,i)),e.isVerticesDataPresent(y.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(y.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(y.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(y.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(y.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(y.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(y.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(y.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw Ge("ribbonBuilder")}static CreateBox(e){throw Ge("boxBuilder")}static CreateTiledBox(e){throw Ge("tiledBoxBuilder")}static CreateTiledPlane(e){throw Ge("tiledPlaneBuilder")}static CreateSphere(e){throw Ge("sphereBuilder")}static CreateCylinder(e){throw Ge("cylinderBuilder")}static CreateTorus(e){throw Ge("torusBuilder")}static CreateLineSystem(e){throw Ge("linesBuilder")}static CreateDashedLines(e){throw Ge("linesBuilder")}static CreateGround(e){throw Ge("groundBuilder")}static CreateTiledGround(e){throw Ge("groundBuilder")}static CreateGroundFromHeightMap(e){throw Ge("groundBuilder")}static CreatePlane(e){throw Ge("planeBuilder")}static CreateDisc(e){throw Ge("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw Ge("polygonBuilder")}static CreateIcoSphere(e){throw Ge("icoSphereBuilder")}static CreatePolyhedron(e){throw Ge("polyhedronBuilder")}static CreateCapsule(e={orientation:m.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Ge("capsuleBuilder")}static CreateTorusKnot(e){throw Ge("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0,f=0,_=0,p=0,g=0,x=0,T=0,S=0,C=0,v=0,b=0,A=0,P=0,L=!1,w=!1,$=!1,J=!1,ne=1,oe=0,re=null;s&&(L=!!s.facetNormals,w=!!s.facetPositions,$=!!s.facetPartitioning,ne=s.useRightHandedSystem===!0?-1:1,oe=s.ratio||0,J=!!s.depthSort,re=s.distanceTo,J&&re===void 0&&(re=m.Zero()));let ce=0,Se=0,Ce=0,ae=0;for($&&s&&s.bbSize&&(ce=s.subDiv.X*oe/s.bbSize.x,Se=s.subDiv.Y*oe/s.bbSize.y,Ce=s.subDiv.Z*oe/s.bbSize.z,ae=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r<e.length;r++)i[r]=0;const ie=t.length/3|0;for(r=0;r<ie;r++){if(g=t[r*3]*3,x=g+1,T=g+2,S=t[r*3+1]*3,C=S+1,v=S+2,b=t[r*3+2]*3,A=b+1,P=b+2,n=e[g]-e[S],o=e[x]-e[C],l=e[T]-e[v],h=e[b]-e[S],c=e[A]-e[C],u=e[P]-e[v],d=ne*(o*u-l*c),f=ne*(l*h-n*u),_=ne*(n*c-o*h),p=Math.sqrt(d*d+f*f+_*_),p=p===0?1:p,d/=p,f/=p,_/=p,L&&s&&(s.facetNormals[r].x=d,s.facetNormals[r].y=f,s.facetNormals[r].z=_),w&&s&&(s.facetPositions[r].x=(e[g]+e[S]+e[b])/3,s.facetPositions[r].y=(e[x]+e[C]+e[A])/3,s.facetPositions[r].z=(e[T]+e[v]+e[P])/3),$&&s){const F=Math.floor((s.facetPositions[r].x-s.bInfo.minimum.x*oe)*ce),j=Math.floor((s.facetPositions[r].y-s.bInfo.minimum.y*oe)*Se),se=Math.floor((s.facetPositions[r].z-s.bInfo.minimum.z*oe)*Ce),Ie=Math.floor((e[g]-s.bInfo.minimum.x*oe)*ce),Ye=Math.floor((e[x]-s.bInfo.minimum.y*oe)*Se),$e=Math.floor((e[T]-s.bInfo.minimum.z*oe)*Ce),fe=Math.floor((e[S]-s.bInfo.minimum.x*oe)*ce),me=Math.floor((e[C]-s.bInfo.minimum.y*oe)*Se),Xe=Math.floor((e[v]-s.bInfo.minimum.z*oe)*Ce),Fe=Math.floor((e[b]-s.bInfo.minimum.x*oe)*ce),ke=Math.floor((e[A]-s.bInfo.minimum.y*oe)*Se),Ue=Math.floor((e[P]-s.bInfo.minimum.z*oe)*Ce),Rt=Ie+s.subDiv.max*Ye+ae*$e,hi=fe+s.subDiv.max*me+ae*Xe,_i=Fe+s.subDiv.max*ke+ae*Ue,pi=F+s.subDiv.max*j+ae*se;s.facetPartitioning[pi]=s.facetPartitioning[pi]?s.facetPartitioning[pi]:new Array,s.facetPartitioning[Rt]=s.facetPartitioning[Rt]?s.facetPartitioning[Rt]:new Array,s.facetPartitioning[hi]=s.facetPartitioning[hi]?s.facetPartitioning[hi]:new Array,s.facetPartitioning[_i]=s.facetPartitioning[_i]?s.facetPartitioning[_i]:new Array,s.facetPartitioning[Rt].push(r),hi!=Rt&&s.facetPartitioning[hi].push(r),_i==hi||_i==Rt||s.facetPartitioning[_i].push(r),pi==Rt||pi==hi||pi==_i||s.facetPartitioning[pi].push(r)}if(J&&s&&s.facetPositions){const F=s.depthSortedFacets[r];F.ind=r*3,F.sqDistance=m.DistanceSquared(s.facetPositions[r],re)}i[g]+=d,i[x]+=f,i[T]+=_,i[S]+=d,i[C]+=f,i[v]+=_,i[b]+=d,i[A]+=f,i[P]+=_}for(r=0;r<i.length/3;r++)d=i[r*3],f=i[r*3+1],_=i[r*3+2],p=Math.sqrt(d*d+f*f+_*_),p=p===0?1:p,d/=p,f/=p,_/=p,i[r*3]=d,i[r*3+1]=f,i[r*3+2]=_}static _ComputeSides(e,t,i,s,r,n,o){const l=i.length,h=s.length;let c,u;switch(e=e||le.DEFAULTSIDE,e){case le.FRONTSIDE:break;case le.BACKSIDE:for(c=0;c<l;c+=3){const d=i[c];i[c]=i[c+2],i[c+2]=d}for(u=0;u<h;u++)s[u]=-s[u];break;case le.DOUBLESIDE:{const d=t.length,f=d/3;for(let g=0;g<d;g++)t[d+g]=t[g];for(c=0;c<l;c+=3)i[c+l]=i[c+2]+f,i[c+1+l]=i[c+1]+f,i[c+2+l]=i[c]+f;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 we(0,0,1,1),o=o||new we(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+_]=o.x+(o.z-o.x)*r[p+_],r[p+_+1]=o.y+(o.w-o.y)*r[p+_+1],p+=2;break}}}static Parse(e){const t=new le,i=e.positions;i&&t.set(i,y.PositionKind);const s=e.normals;s&&t.set(s,y.NormalKind);const r=e.tangents;r&&t.set(r,y.TangentKind);const n=e.uvs;n&&t.set(n,y.UVKind);const o=e.uvs2;o&&t.set(o,y.UV2Kind);const l=e.uvs3;l&&t.set(l,y.UV3Kind);const h=e.uvs4;h&&t.set(h,y.UV4Kind);const c=e.uvs5;c&&t.set(c,y.UV5Kind);const u=e.uvs6;u&&t.set(u,y.UV6Kind);const d=e.colors;d&&(t.set(xe.CheckColors4(d,i.length/3),y.ColorKind),e.hasVertexAlpha!==void 0&&(t.hasVertexAlpha=e.hasVertexAlpha));const f=e.matricesIndices;f&&t.set(f,y.MatricesIndicesKind);const _=e.matricesWeights;_&&t.set(_,y.MatricesWeightsKind);const p=e.indices;p&&(t.indices=p);const g=e.materialInfos;if(g){t.materialInfos=[];for(const x of g){const T=new kd;T.indexCount=x.indexCount,T.indexStart=x.indexStart,T.verticesCount=x.verticesCount,T.verticesStart=x.verticesStart,T.materialIndex=x.materialIndex,t.materialInfos.push(T)}}return t}static ImportVertexData(e,t){const i=le.Parse(e);t.setAllVerticesData(i,e.updatable)}}le.FRONTSIDE=0;le.BACKSIDE=1;le.DOUBLESIDE=2;le.DEFAULTSIDE=0;le._UniqueIDGenerator=0;E([Qa.filter((...[a])=>!Array.isArray(a))],le,"_TransformVector3Coordinates",null);E([Qa.filter((...[a])=>!Array.isArray(a))],le,"_TransformVector3Normals",null);E([Qa.filter((...[a])=>!Array.isArray(a))],le,"_TransformVector4Normals",null);E([Qa.filter((...[a])=>!Array.isArray(a))],le,"_FlipFaces",null);class Qi{static get ForceFullSceneLoadingForIncremental(){return Qi._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Qi._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Qi._ShowLoadingScreen}static set ShowLoadingScreen(e){Qi._ShowLoadingScreen=e}static get loggingLevel(){return Qi._LoggingLevel}static set loggingLevel(e){Qi._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Qi._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Qi._CleanBoneMatrixWeights=e}}Qi._ForceFullSceneLoadingForIncremental=!1;Qi._ShowLoadingScreen=!0;Qi._CleanBoneMatrixWeights=!1;Qi._LoggingLevel=0;class mt{}mt.UseOpenGLOrientationForUV=!1;class zi{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 zi(zi.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||Ae.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,"Geometry_"+this.id+"_IndexBuffer"));const e=new Set;for(const t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach(t=>{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new y(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:s,label:"Geometry_"+this.id+"_"+e});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===y.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let h=0;h<n;h++){const c=r[h];c.buildBoundingInfo(o,l),c._createGlobalSubMesh(c.isUnIndexed),c.computeWorldMatrix(!0),c.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===y.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)}}setIndexBuffer(e,t,i){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,e.is32Bits||(e.is32Bits=this._totalIndices>65535);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);s!==-1&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(y.PositionKind),!e))return;this._extend=Au(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===y.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,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(y.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(y.PositionKind,t,!1)}const i=this.getVerticesData(y.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(y.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(y.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]=m.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 le;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l<i.length;l++)t.indices.push(i[l]);let s=!1,r=!1,n;for(n in this._vertexBuffers){const l=this.getVerticesData(n);if(l&&(l instanceof Float32Array?t.set(new Float32Array(l),n):t.set(l.slice(0),n),!r)){const h=this.getVertexBuffer(n);h&&(s=h.isUpdatable(),r=!s)}}const o=new zi(e,this._scene,t,s);o.delayLoadState=this.delayLoadState,o.delayLoadingFile=this.delayLoadingFile,o._delayLoadingFunction=this._delayLoadingFunction;for(n in this._delayInfo)o._delayInfo=o._delayInfo||[],o._delayInfo.push(n);return o._boundingInfo=new or(this._extend.minimum,this._extend.maximum),o}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,ft&&ft.HasTags(this)&&(e.tags=ft.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(y.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(y.PositionKind)),this.isVertexBufferUpdatable(y.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(y.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(y.NormalKind)),this.isVertexBufferUpdatable(y.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(y.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(y.TangentKind)),this.isVertexBufferUpdatable(y.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(y.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(y.UVKind)),this.isVertexBufferUpdatable(y.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(y.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(y.UV2Kind)),this.isVertexBufferUpdatable(y.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(y.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(y.UV3Kind)),this.isVertexBufferUpdatable(y.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(y.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(y.UV4Kind)),this.isVertexBufferUpdatable(y.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(y.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(y.UV5Kind)),this.isVertexBufferUpdatable(y.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(y.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(y.UV6Kind)),this.isVertexBufferUpdatable(y.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(y.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(y.ColorKind)),this.isVertexBufferUpdatable(y.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(y.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(y.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(y.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(y.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(y.MatricesWeightsKind)),this.isVertexBufferUpdatable(y.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 X.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 o=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(y.PositionKind,o,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const o=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(y.NormalKind,o,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const o=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(y.TangentKind,o,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const o=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UVKind,o,!1)}if(n.uvs2AttrDesc&&n.uvs2AttrDesc.count>0){const o=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UV2Kind,o,!1)}if(n.uvs3AttrDesc&&n.uvs3AttrDesc.count>0){const o=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UV3Kind,o,!1)}if(n.uvs4AttrDesc&&n.uvs4AttrDesc.count>0){const o=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UV4Kind,o,!1)}if(n.uvs5AttrDesc&&n.uvs5AttrDesc.count>0){const o=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UV5Kind,o,!1)}if(n.uvs6AttrDesc&&n.uvs6AttrDesc.count>0){const o=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(mt.UseOpenGLOrientationForUV)for(let l=1;l<o.length;l+=2)o[l]=1-o[l];t.setVerticesData(y.UV6Kind,o,!1)}if(n.colorsAttrDesc&&n.colorsAttrDesc.count>0){const o=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(y.ColorKind,o,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),l=[];for(let h=0;h<o.length;h++){const c=o[h];l.push(c&255),l.push((c&65280)>>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(y.MatricesIndicesKind,l,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h<o.length;h++){const c=o[h];l.push(c&255),l.push((c&65280)>>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(y.MatricesIndicesExtraKind,l,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(y.MatricesWeightsKind,o,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const o=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(o,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const o=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l<n.subMeshesAttrDesc.count;l++){const h=o[l*5+0],c=o[l*5+1],u=o[l*5+2],d=o[l*5+3],f=o[l*5+4];Ss.AddToMesh(h,c,u,d,f,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(y.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(y.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(y.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(y.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(y.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(y.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(y.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(y.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(y.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(y.ColorKind,xe.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(y.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const n=[];for(let o=0;o<e.matricesIndices.length;o++){const l=e.matricesIndices[o];n.push(l&255),n.push((l&65280)>>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(y.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(y.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let o=0;o<e.matricesIndicesExtra.length;o++){const l=e.matricesIndicesExtra[o];n.push(l&255),n.push((l&65280)>>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(y.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(zi._CleanMatricesWeights(e,t),t.setVerticesData(y.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(y.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 o=e.subMeshes[n];Ss.AddToMesh(o.materialIndex,o.verticesStart,o.verticesCount,o.indexStart,o.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!Qi.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(y.MatricesIndicesKind),n=t.getVerticesData(y.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=o.length;for(let u=0;u<c;u+=4){let d=0,f=-1;for(let _=0;_<4;_++){const p=o[u+_];d+=p,p<.001&&f<0&&(f=_)}if(l)for(let _=0;_<4;_++){const p=l[u+_];d+=p,p<.001&&f<0&&(f=_+4)}if((f<0||f>h-1)&&(f=h-1),d>.001){const _=1/d;for(let p=0;p<4;p++)o[u+p]*=_;if(l)for(let p=0;p<4;p++)l[u+p]*=_}else f>=4?(l[u+f-4]=1-d,n[u+f-4]=s):(o[u+f]=1-d,r[u+f]=s)}t.setVerticesData(y.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(y.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new zi(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ft&&ft.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new or(m.FromArray(e.boundingBoxMinimum),m.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(y.UVKind),e.hasUVs2&&s._delayInfo.push(y.UV2Kind),e.hasUVs3&&s._delayInfo.push(y.UV3Kind),e.hasUVs4&&s._delayInfo.push(y.UV4Kind),e.hasUVs5&&s._delayInfo.push(y.UV5Kind),e.hasUVs6&&s._delayInfo.push(y.UV6Kind),e.hasColors&&s._delayInfo.push(y.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(y.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(y.MatricesWeightsKind),s._delayLoadingFunction=le.ImportVertexData):le.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class rb{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new nb(e)}sampleFrame(e=Zi.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 nb{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}}pe.prototype.setAlphaConstants=function(a,e,t,i){this._alphaState.setAlphaBlendConstants(a,e,t,i)};pe.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break}e||(this.depthCullingState.depthMask=a===0),this._alphaMode=a};pe.prototype.getAlphaMode=function(){return this._alphaMode};pe.prototype.setAlphaEquation=function(a){if(this._alphaEquation!==a){switch(a){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774);break}this._alphaEquation=a}};pe.prototype.getAlphaEquation=function(){return this._alphaEquation};function np(a,e,t=!1,i){switch(a){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}pe.prototype._readTexturePixelsSync=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,h=0){var d,f;const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const _=c.createFramebuffer();if(!_)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=_}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),i>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,(d=a._hardwareTexture)==null?void 0:d.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(f=a._hardwareTexture)==null?void 0:f.underlyingResource,s);let u=a.type!==void 0?this._getWebGLTextureType(a.type):c.UNSIGNED_BYTE;if(o)r||(r=np(a.type,4*e*t));else switch(u){case c.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),u=c.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),u=c.FLOAT;break}return n&&this.flushFramebuffer(),c.readPixels(l,h,e,t,c.RGBA,u,r),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),r};pe.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,r,n,o,l,h))};pe.prototype.updateDynamicIndexBuffer=function(a,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(a);let i;a.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};pe.prototype.updateDynamicVertexBuffer=function(a,e,t,i){this.bindArrayBuffer(a),t===void 0&&(t=0);const s=e.byteLength||e.length;i===void 0||i>=s&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(e).subarray(t,t+i)):(e instanceof ArrayBuffer?e=new Uint8Array(e,t,i):e=new Uint8Array(e.buffer,e.byteOffset+t,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)),this._resetVertexBufferBinding()};class H extends pe{static get NpmPackage(){return pe.NpmPackage}static get Version(){return pe.Version}static get Instances(){return Ae.Instances}static get LastCreatedEngine(){return Ae.LastCreatedEngine}static get LastCreatedScene(){return Ae.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{this.createImageBitmap(n,t).then(o=>{s(o)})})},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<H.Instances.length;i++){const s=H.Instances[i];for(let r=0;r<s.scenes.length;r++)s.scenes[r].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw Ge("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!H._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=[],this._virtualScenes=new Array,this.onNewSceneAddedObservable=new G,this.postProcesses=[],this.isPointerLock=!1,this.onResizeObservable=new G,this.onCanvasBlurObservable=new G,this.onCanvasFocusObservable=new G,this.onCanvasPointerOutObservable=new G,this.onBeginFrameObservable=new G,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new G,this.onBeforeShaderCompilationObservable=new G,this.onAfterShaderCompilationObservable=new G,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new wr,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new rb,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],H.Instances.push(this),!!e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const r=e;this._sharedInit(r)}}_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(),!H.audioEngine&&this._creationOptions.audioEngine&&H.AudioEngineFactory&&(H.audioEngine=H.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),jc()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&H._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=H.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.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)}_loadFileAsync(e,t,i){return new Promise((s,r)=>{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,o)=>{r(o)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}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){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s==null?void 0:s.texture)??null,i)}setTextureFromPostProcessOutput(e,t,i){var s;this._bindTexture(e,((s=t==null?void 0:t._outputTexture)==null?void 0:s.texture)??null,i)}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){const t=this._activeRenderLoops[e];t()}}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&H._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&H._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&H._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){H._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}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 o=r.cameras[n];o._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 o=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_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 o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=o}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=++H._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&&H._RescalePostProcessFactory&&(this._rescalePostProcess=H._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],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,s=0,r=0){const n=new Ec(e,this._gl),o=new Tt(this,et.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),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,l,o,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){O.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 Eu(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 o=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){n();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(o,i);return}r()};o()})}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,r,n,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const c=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(l.flush(),this._clientWaitAsync(c,0,10).then(()=>(l.deleteSync(c),l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),o))):null}dispose(){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();Ae.Instances.length===1&&H.audioEngine&&(H.audioEngine.dispose(),H.audioEngine=null);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)),jc()&&(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=Ae.Instances.indexOf(this);t>=0&&Ae.Instances.splice(t,1),H.Instances.length||Ae.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(!ls())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!ls())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=H.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}}}H.ALPHA_DISABLE=0;H.ALPHA_ADD=1;H.ALPHA_COMBINE=2;H.ALPHA_SUBTRACT=3;H.ALPHA_MULTIPLY=4;H.ALPHA_MAXIMIZED=5;H.ALPHA_ONEONE=6;H.ALPHA_PREMULTIPLIED=7;H.ALPHA_PREMULTIPLIED_PORTERDUFF=8;H.ALPHA_INTERPOLATE=9;H.ALPHA_SCREENMODE=10;H.DELAYLOADSTATE_NONE=0;H.DELAYLOADSTATE_LOADED=1;H.DELAYLOADSTATE_LOADING=2;H.DELAYLOADSTATE_NOTLOADED=4;H.NEVER=512;H.ALWAYS=519;H.LESS=513;H.EQUAL=514;H.LEQUAL=515;H.GREATER=516;H.GEQUAL=518;H.NOTEQUAL=517;H.KEEP=7680;H.REPLACE=7681;H.INCR=7682;H.DECR=7683;H.INVERT=5386;H.INCR_WRAP=34055;H.DECR_WRAP=34056;H.TEXTURE_CLAMP_ADDRESSMODE=0;H.TEXTURE_WRAP_ADDRESSMODE=1;H.TEXTURE_MIRROR_ADDRESSMODE=2;H.TEXTUREFORMAT_ALPHA=0;H.TEXTUREFORMAT_LUMINANCE=1;H.TEXTUREFORMAT_LUMINANCE_ALPHA=2;H.TEXTUREFORMAT_RGB=4;H.TEXTUREFORMAT_RGBA=5;H.TEXTUREFORMAT_RED=6;H.TEXTUREFORMAT_R=6;H.TEXTUREFORMAT_RG=7;H.TEXTUREFORMAT_RED_INTEGER=8;H.TEXTUREFORMAT_R_INTEGER=8;H.TEXTUREFORMAT_RG_INTEGER=9;H.TEXTUREFORMAT_RGB_INTEGER=10;H.TEXTUREFORMAT_RGBA_INTEGER=11;H.TEXTURETYPE_UNSIGNED_BYTE=0;H.TEXTURETYPE_UNSIGNED_INT=0;H.TEXTURETYPE_FLOAT=1;H.TEXTURETYPE_HALF_FLOAT=2;H.TEXTURETYPE_BYTE=3;H.TEXTURETYPE_SHORT=4;H.TEXTURETYPE_UNSIGNED_SHORT=5;H.TEXTURETYPE_INT=6;H.TEXTURETYPE_UNSIGNED_INTEGER=7;H.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;H.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;H.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;H.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;H.TEXTURETYPE_UNSIGNED_INT_24_8=12;H.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;H.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;H.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;H.TEXTURE_NEAREST_SAMPLINGMODE=1;H.TEXTURE_BILINEAR_SAMPLINGMODE=2;H.TEXTURE_TRILINEAR_SAMPLINGMODE=3;H.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;H.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;H.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;H.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;H.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;H.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;H.TEXTURE_NEAREST_LINEAR=7;H.TEXTURE_NEAREST_NEAREST=1;H.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;H.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;H.TEXTURE_LINEAR_LINEAR=2;H.TEXTURE_LINEAR_NEAREST=12;H.TEXTURE_EXPLICIT_MODE=0;H.TEXTURE_SPHERICAL_MODE=1;H.TEXTURE_PLANAR_MODE=2;H.TEXTURE_CUBIC_MODE=3;H.TEXTURE_PROJECTION_MODE=4;H.TEXTURE_SKYBOX_MODE=5;H.TEXTURE_INVCUBIC_MODE=6;H.TEXTURE_EQUIRECTANGULAR_MODE=7;H.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;H.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;H.SCALEMODE_FLOOR=1;H.SCALEMODE_NEAREST=2;H.SCALEMODE_CEILING=3;H._RescalePostProcessFactory=null;H._RenderPassIdCounter=0;const ab=D.Compose(m.One(),Q.FromEulerAngles(0,Math.PI,0),m.Zero());class Ke extends Ct{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Ke.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!==Ke.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 m(0,0,1),this._up=new m(0,1,0),this._right=new m(1,0,0),this._position=m.Zero(),this._rotation=m.Zero(),this._rotationQuaternion=null,this._scaling=m.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Ke.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=D.Zero(),this._usePivotMatrix=!1,this._absolutePosition=m.Zero(),this._absoluteScaling=m.Zero(),this._absoluteRotationQuaternion=Q.Identity(),this._pivotMatrix=D.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new G,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return m.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return m.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return m.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=D.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Ke.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=D.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||Q.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=U.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),m.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=m.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=U.Matrix[0];return this._localMatrix.invertToRef(e),m.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=m.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=pt.LOCAL){const n=Ke._LookAtVectorCache,o=r===pt.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===pt.WORLD&&this.parent)if(this.rotationQuaternion){const l=U.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=U.Quaternion[0];Q.FromEulerVectorToRef(this.rotation,l);const h=U.Matrix[0];l.toRotationMatrix(h);const c=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),h.multiplyToRef(c,h),l.fromRotationMatrix(h),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=m.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return m.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),o=-Math.atan2(e.y,n);return this.rotationQuaternion?Q.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=pt.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==pt.WORLD){const s=U.Matrix[0];i.invertToRef(s),e=m.TransformCoordinates(e,s)}return this.setPivotMatrix(D.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=m.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=m.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),m.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=U.Quaternion[0],r=U.Vector3[0],n=U.Vector3[1],o=U.Matrix[1];D.IdentityToRef(o);const l=U.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=Ke._TmpRotation,Q.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),D.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(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(D.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(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let s;if(!i||i===pt.LOCAL)s=Q.RotationAxisToRef(e,t,Ke._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=this.parent.getWorldMatrix(),n=U.Matrix[0];r.invertToRef(n),e=m.TransformNormal(e,n),r.determinant()<0&&(t*=-1)}s=Q.RotationAxisToRef(e,t,Ke._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Q.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=U.Vector3[0],r=U.Vector3[1],n=U.Vector3[2],o=U.Quaternion[0],l=U.Matrix[0],h=U.Matrix[1],c=U.Matrix[2],u=U.Matrix[3];return e.subtractToRef(this.position,s),D.TranslationToRef(s.x,s.y,s.z,l),D.TranslationToRef(-s.x,-s.y,-s.z,h),D.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===pt.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=U.Quaternion[1],Q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=U.Quaternion[0];return Q.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!==Ke.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=Ke._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new m(h.m[12],h.m[13],h.m[14]);o=Ke._TmpTranslation,o.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 l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Q.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=Ke._TmpRotation,Q.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=U.Matrix[1];D.ScalingToRef(n.x,n.y,n.z,h);const c=U.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,U.Matrix[4]),U.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else D.ComposeToRef(n,l,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),U.Matrix[7])}else U.Matrix[7].copyFrom(r.getWorldMatrix());const h=U.Vector3[5],c=U.Vector3[6],u=U.Quaternion[0];U.Matrix[7].decompose(c,u,h),D.ScalingToRef(c.x,c.y,c.z,U.Matrix[7]),U.Matrix[7].setTranslation(h),Ke.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(U.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const h=this.parent;h.getSkeleton().prepare(),this._localMatrix.multiplyToRef(h.getFinalMatrix(),U.Matrix[6]),U.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else 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=U.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),U.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&U.Matrix[1].multiplyToRef(ab,U.Matrix[1]),U.Matrix[1].setTranslationFromFloats(0,0,0),U.Matrix[1].invertToRef(U.Matrix[0]),(this.billboardMode&Ke.BILLBOARDMODE_ALL)!==Ke.BILLBOARDMODE_ALL){U.Matrix[0].decompose(void 0,U.Quaternion[0],void 0);const c=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&Ke.BILLBOARDMODE_X)!==Ke.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&Ke.BILLBOARDMODE_Y)!==Ke.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&Ke.BILLBOARDMODE_Z)!==Ke.BILLBOARDMODE_Z&&(c.z=0),D.RotationYawPitchRollToRef(c.y,c.x,c.z,U.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=U.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(U.Matrix[1]);const u=U.Vector3[1];m.TransformCoordinatesToRef(c,U.Matrix[1],u),u.normalize();const d=-Math.atan2(u.z,u.x)+Math.PI/2,f=Math.sqrt(u.x*u.x+u.z*u.z),_=-Math.atan2(u.y,f);if(Q.RotationYawPitchRollToRef(d,_,0,U.Quaternion[0]),(this.billboardMode&Ke.BILLBOARDMODE_ALL)!==Ke.BILLBOARDMODE_ALL){const p=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(p),(this.billboardMode&Ke.BILLBOARDMODE_X)!==Ke.BILLBOARDMODE_X&&(p.x=0),(this.billboardMode&Ke.BILLBOARDMODE_Y)!==Ke.BILLBOARDMODE_Y&&(p.y=0),(this.billboardMode&Ke.BILLBOARDMODE_Z)!==Ke.BILLBOARDMODE_Z&&(p.z=0),D.RotationYawPitchRollToRef(p.y,p.x,p.z,U.Matrix[0])}else D.FromQuaternionToRef(U.Quaternion[0],U.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.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=D.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=U.Matrix[0];s._localMatrix.multiplyToRef(this._localMatrix,r);const n=U.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=Q.Identity()),this._worldMatrix=D.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),m.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=_e.Clone(()=>new Ke(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 o=r[n];o.clone&&o.clone(e+"."+o.name,s)}}return s}serialize(e){const t=_e.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(),_e.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,i){const s=_e.Parse(()=>new Ke(e.name,t),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(D.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(D.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],o=Si("BABYLON.Animation");o&&s.animations.push(o.Parse(n))}Ct.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof Ke),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),o=n.max.subtract(n.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const h=1/l;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&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)}}Ke.BILLBOARDMODE_NONE=0;Ke.BILLBOARDMODE_X=1;Ke.BILLBOARDMODE_Y=2;Ke.BILLBOARDMODE_Z=4;Ke.BILLBOARDMODE_ALL=7;Ke.BILLBOARDMODE_USE_POSITION=128;Ke.BillboardUseParentOrientation=!1;Ke._TmpRotation=Q.Zero();Ke._TmpScaling=m.Zero();Ke._TmpTranslation=m.Zero();Ke._LookAtVectorCache=new m(0,0,0);Ke._RotationAxisCache=new Q;E([bs("position")],Ke.prototype,"_position",void 0);E([bs("rotation")],Ke.prototype,"_rotation",void 0);E([pv("rotationQuaternion")],Ke.prototype,"_rotationQuaternion",void 0);E([bs("scaling")],Ke.prototype,"_scaling",void 0);E([I("billboardMode")],Ke.prototype,"_billboardMode",void 0);E([I()],Ke.prototype,"scalingDeterminant",void 0);E([I("infiniteDistance")],Ke.prototype,"_infiniteDistance",void 0);E([I()],Ke.prototype,"ignoreNonUniformScaling",void 0);E([I()],Ke.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class ob{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new m(0,0,0),this._diffPositionForCollisions=new m(0,0,0),this._collisionResponse=!0}}class lb{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=m.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class hb{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new lb,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 ob,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class ut extends Ke{static get BILLBOARDMODE_NONE(){return Ke.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Ke.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Ke.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Ke.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Ke.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Ke.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?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 hb,this._waitingMaterialId=null,this.cullingStrategy=ut.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new G,this.onCollisionPositionChangeObservable=new G,this.onMaterialChangedObservable=new G,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=q.Red(),this.outlineWidth=.02,this.overlayColor=q.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 m(.5,1,.5),this.ellipsoidOffset=new m(0,0,0),this.edgesWidth=1,this.edgesColor=new xe(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new G,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>H.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 be(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Gn.Aggressive:this.doNotSyncBoundingInfo=!0;case Gn.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!==Ke.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){const s=t._drawWrappers[i];!s||!s.defines||!s.defines.markAllAsDirty||e(s.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new or(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(y.MatricesIndicesKind)&&this.isVerticesDataPresent(y.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Ke.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 D;(this.rotationQuaternion?this.rotationQuaternion:Q.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=m.Zero(),o=this.definedFacingForward?-1:1;return m.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,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 m(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=Au(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new or(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=y.PositionKind){if(i=i??this.getVerticesData(s).slice(),i&&t&&this.morphTargetManager){let r=0,n=0;for(let o=0;o<i.length;o++){let l=i[o];for(let h=0;h<this.morphTargetManager.numTargets;h++){const c=this.morphTargetManager.getTarget(h),u=c.influence;if(u!==0){let d=null;switch(s){case y.PositionKind:d=c.getPositions();break;case y.NormalKind:d=c.getNormals();break;case y.TangentKind:d=c.getTangents();break;case y.UVKind:d=c.getUVs();break}d&&(l+=(d[o]-i[o])*u)}}if(i[o]=l,r++,s===y.PositionKind&&this._positions&&r===3){r=0;const h=n*3;this._positions[n++].copyFromFloats(i[h],i[h+1],i[h+2])}}}if(i&&e&&this.skeleton){const r=this.getVerticesData(y.MatricesIndicesKind),n=this.getVerticesData(y.MatricesWeightsKind);if(n&&r){const o=this.numBoneInfluencers>4,l=o?this.getVerticesData(y.MatricesIndicesExtraKind):null,h=o?this.getVerticesData(y.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=U.Vector3[0],d=U.Matrix[0],f=U.Matrix[1];let _=0;for(let p=0;p<i.length;p+=3,_+=4){d.reset();let g,x;for(g=0;g<4;g++)x=n[_+g],x>0&&(D.FromFloat32ArrayToRefScaled(c,Math.floor(r[_+g]*16),x,f),d.addToSelf(f));if(o)for(g=0;g<4;g++)x=h[_+g],x>0&&(D.FromFloat32ArrayToRefScaled(c,Math.floor(l[_+g]*16),x,f),d.addToSelf(f));s===y.NormalKind?m.TransformNormalFromFloatsToRef(i[p],i[p+1],i[p+2],d,u):m.TransformCoordinatesFromFloatsToRef(i[p],i[p+1],i[p+2],d,u),u.toArray(i,p),s===y.PositionKind&&this._positions&&this._positions[p/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,y.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,y.PositionKind)}_getPositionData(e,t){var s;let i=this.getVerticesData(y.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.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]=((s=r[n])==null?void 0:s.clone())||new m}return this.getPositionData(e,t,i)}return i}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new or(m.Zero(),m.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 o=r;o<n;o++)e._lastColliderWorldVertices.push(m.TransformCoordinates(this._positions[o],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?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=U.Matrix[0],i=U.Matrix[1];return D.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 o=new es,l=this.getClassName(),h=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:m.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let _=!1;for(let p=0;p<f;p++){const x=d.data[p].getMaterial();if(x&&(x.fillMode==7||x.fillMode==0||x.fillMode==1||x.fillMode==2||x.fillMode==4)){_=!0;break}}if(!_)return o.hit=!0,o.pickedMesh=this,o.distance=m.Distance(e.origin,c.boundingSphere.center),o.subMeshId=-1,o;for(let p=0;p<f;p++){const g=d.data[p];if(f>1&&!n&&!g.canIntersects(e))continue;const x=g.intersects(e,this._positions,this.getIndices(),t,i);if(x&&(t||!u||x.distance<u.distance)&&(u=x,u.subMeshId=p,t))break}if(u){const p=r??this.getWorldMatrix(),g=U.Vector3[0],x=U.Vector3[1];m.TransformCoordinatesToRef(e.origin,p,g),e.direction.scaleToRef(u.distance,x);const S=m.TransformNormal(x,p).addInPlace(g);return o.hit=!0,o.distance=m.Distance(g,S),o.pickedPoint=S,o.pickedMesh=this,o.bu=u.bu||0,o.bv=u.bv||0,o.subMeshFaceId=u.faceId,o.faceId=u.faceId+d.data[u.subMeshId].indexStart/(this.getClassName().indexOf("LinesMesh")!==-1?2:3),o.subMeshId=u.subMeshId,o}return o}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;const s=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),s.freeActiveMeshes(),s.freeRenderingGroups(),s.renderingManager.maintainStateBetweenFrames&&s.renderingManager.restoreDispachedFlags(),this.actionManager!==void 0&&this.actionManager!==null&&(this._scene.meshes.some(o=>o!==this&&o.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){const o=this._intersectionsInProgress[i],l=o._intersectionsInProgress.indexOf(this);o._intersectionsInProgress.splice(l,1)}this._intersectionsInProgress.length=0,s.lights.forEach(o=>{let l=o.includedOnlyMeshes.indexOf(this);l!==-1&&o.includedOnlyMeshes.splice(l,1),l=o.excludedMeshes.indexOf(this),l!==-1&&o.excludedMeshes.splice(l,1);const h=o.getShadowGenerators();if(h){const c=h.values();for(let u=c.next();u.done!==!0;u=c.next()){const f=u.value.getShadowMap();f&&f.renderList&&(l=f.renderList.indexOf(this),l!==-1&&f.renderList.splice(l,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const n=s.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),s.removeMesh(this),this._parentContainer){const o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<s.particleSystems.length;i++)s.particleSystems[i].emitter===this&&(s.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}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=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=m.Zero(),e.facetPositions[t]=m.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(y.PositionKind),i=this.getIndices(),s=this.getVerticesData(y.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 o=!1;for(let l=0;l<i.length;l++)if(i[l]>65535){o=!0;break}o?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(o,l){return l.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:m.Zero()}e.depthSortedFacets=[];for(let o=0;o<e.facetNb;o++){const l={ind:o*3,sqDistance:0};e.depthSortedFacets.push(l)}e.invertedMatrix=D.Identity(),e.facetDepthSortOrigin=m.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>rt?r.maximum.x-r.minimum.x:rt,e.bbSize.y=r.maximum.y-r.minimum.y>rt?r.maximum.y-r.minimum.y:rt,e.bbSize.z=r.maximum.z-r.minimum.z>rt?r.maximum.z-r.minimum.z:rt;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),m.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&le.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;l<o;l++){const h=e.depthSortedFacets[l].ind;e.depthSortedIndices[l*3]=i[h],e.depthSortedIndices[l*3+1]=i[h+1],e.depthSortedIndices[l*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=m.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],s=this.getWorldMatrix();return m.TransformCoordinatesToRef(i,s,t),this}getFacetNormal(e){const t=m.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return m.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),o=Math.floor((t-s.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),l=Math.floor((i-s.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return n<0||n>r.subDiv.max||o<0||o>r.subDiv.max||l<0||l>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),l=U.Matrix[5];o.invertToRef(l);const h=U.Vector3[8];m.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&m.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,l=0,h=0,c=0,u=0,d=0,f=0,_=0,p=0;const g=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),T=this.getFacetsAtLocalCoordinates(e,t,i);if(!T)return null;let S=Number.MAX_VALUE,C=S,v,b,A;for(let P=0;P<T.length;P++)v=T[P],b=x[v],A=g[v],u=(e-A.x)*b.x+(t-A.y)*b.y+(i-A.z)*b.z,(!r||r&&n&&u>=0||r&&!n&&u<=0)&&(u=b.x*A.x+b.y*A.y+b.z*A.z,d=-(b.x*e+b.y*t+b.z*i-u)/(b.x*b.x+b.y*b.y+b.z*b.z),f=e+b.x*d,_=t+b.y*d,p=i+b.z*d,l=f-e,h=_-t,c=p-i,C=l*l+h*h+c*c,C<S&&(S=C,o=v,s&&(s.x=f,s.y=_,s.z=p)));return o}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(y.PositionKind),i=this.getIndices();let s;return this.isVerticesDataPresent(y.NormalKind)?s=this.getVerticesData(y.NormalKind):s=[],le.ComputeNormals(t,i,s,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(y.NormalKind,s,e),this}alignWithNormal(e,t){t||(t=Bs.Y);const i=U.Vector3[0],s=U.Vector3[1];return m.CrossToRef(t,e,s),m.CrossToRef(e,s,i),this.rotationQuaternion?Q.RotationQuaternionFromAxisToRef(i,e,s,this.rotationQuaternion):m.RotationFromAxisToRef(i,e,s,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw Ge("EdgesRenderer")}enableEdgesRendering(e,t,i){throw Ge("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}}ut.OCCLUSION_TYPE_NONE=0;ut.OCCLUSION_TYPE_OPTIMISTIC=1;ut.OCCLUSION_TYPE_STRICT=2;ut.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;ut.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;ut.CULLINGSTRATEGY_STANDARD=0;ut.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;ut.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;ut.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;V("BABYLON.AbstractMesh",ut);class Ea{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){_e.Clone(()=>e,this)}serialize(){return _e.Serialize(this)}parse(e,t,i){_e.Parse(()=>this,e,t,i)}}E([I()],Ea.prototype,"func",null);E([I()],Ea.prototype,"funcRef",null);E([I()],Ea.prototype,"funcMask",null);E([I()],Ea.prototype,"opStencilFail",null);E([I()],Ea.prototype,"opDepthFail",null);E([I()],Ea.prototype,"opStencilDepthPass",null);E([I()],Ea.prototype,"mask",null);E([I()],Ea.prototype,"enabled",null);var Es;(function(a){a[a.Created=1]="Created",a[a.Disposed=2]="Disposed",a[a.GetDefineNames=4]="GetDefineNames",a[a.PrepareUniformBuffer=8]="PrepareUniformBuffer",a[a.IsReadyForSubMesh=16]="IsReadyForSubMesh",a[a.PrepareDefines=32]="PrepareDefines",a[a.BindForSubMesh=64]="BindForSubMesh",a[a.PrepareEffect=128]="PrepareEffect",a[a.GetAnimatables=256]="GetAnimatables",a[a.GetActiveTextures=512]="GetActiveTextures",a[a.HasTexture=1024]="HasTexture",a[a.FillRenderTargetTextures=2048]="FillRenderTargetTextures",a[a.HasRenderTargetTextures=4096]="HasRenderTargetTextures",a[a.HardBindForSubMesh=8192]="HardBindForSubMesh"})(Es||(Es={}));function sn(a){a.indexOf("vClipPlane")===-1&&a.push("vClipPlane"),a.indexOf("vClipPlane2")===-1&&a.push("vClipPlane2"),a.indexOf("vClipPlane3")===-1&&a.push("vClipPlane3"),a.indexOf("vClipPlane4")===-1&&a.push("vClipPlane4"),a.indexOf("vClipPlane5")===-1&&a.push("vClipPlane5"),a.indexOf("vClipPlane6")===-1&&a.push("vClipPlane6")}function no(a,e,t){const i=!!(a.clipPlane??e.clipPlane),s=!!(a.clipPlane2??e.clipPlane2),r=!!(a.clipPlane3??e.clipPlane3),n=!!(a.clipPlane4??e.clipPlane4),o=!!(a.clipPlane5??e.clipPlane5),l=!!(a.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),s&&t.push("#define CLIPPLANE2"),r&&t.push("#define CLIPPLANE3"),n&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function cb(a,e,t){let i=!1;const s=!!(a.clipPlane??e.clipPlane),r=!!(a.clipPlane2??e.clipPlane2),n=!!(a.clipPlane3??e.clipPlane3),o=!!(a.clipPlane4??e.clipPlane4),l=!!(a.clipPlane5??e.clipPlane5),h=!!(a.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==s&&(t.CLIPPLANE=s,i=!0),t.CLIPPLANE2!==r&&(t.CLIPPLANE2=r,i=!0),t.CLIPPLANE3!==n&&(t.CLIPPLANE3=n,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==h&&(t.CLIPPLANE6=h,i=!0),i}function Gr(a,e,t){let i=e.clipPlane??t.clipPlane;nl(a,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,nl(a,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,nl(a,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,nl(a,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,nl(a,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,nl(a,"vClipPlane6",i)}function nl(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const cx=q.Black(),ux={NUM_MORPH_INFLUENCERS:0};function ao(a,e,t){if(!a||a.LOGARITHMICDEPTH||a.indexOf&&a.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&O.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function Go(a,e,t,i=!1){t&&a.fogEnabled&&(!e||e.applyFog)&&a.fogMode!==0&&(t.setFloat4("vFogInfos",a.fogMode,a.fogStart,a.fogEnd,a.fogDensity),i?(a.fogColor.toLinearSpaceToRef(cx,a.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",cx)):t.setColor3("vFogColor",a.fogColor))}function $u(a,e,t){ux.NUM_MORPH_INFLUENCERS=t,xm(a,e,ux)}function xm(a,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&Ae.LastCreatedEngine){const s=Ae.LastCreatedEngine.getCaps().maxVertexAttribs,r=e.morphTargetManager;if(r!=null&&r.isUsingTextureForTargets)return;const n=r&&r.supportsNormals&&t.NORMAL,o=r&&r.supportsTangents&&t.TANGENT,l=r&&r.supportsUVs&&t.UV1;for(let h=0;h<i;h++)a.push("position"+h),n&&a.push("normal"+h),o&&a.push("tangent"+h),l&&a.push("uv_"+h),a.length>s&&O.Error("Cannot add more vertex attributes for mesh "+e.name)}}function oo(a,e=!1){a.push("world0"),a.push("world1"),a.push("world2"),a.push("world3"),e&&(a.push("previousWorld0"),a.push("previousWorld1"),a.push("previousWorld2"),a.push("previousWorld3"))}function Sa(a,e){const t=a.morphTargetManager;!a||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function bf(a,e){e.bindToEffect(a,"Scene")}function qt(a,e,t){e._needUVs=!0,e[t]=!0,a.optimizeUVAllocation&&a.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=a.coordinatesIndex+1,e["MAINUV"+(a.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function Gt(a,e,t){const i=a.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Tm(a,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&a.push("bakedVertexAnimationSettingsInstanced")}function ub(a,e){return e.set(a),e}function Ku(a,e,t){if(!(!e||!a)&&(a.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(a.computeBonesUsingShaders=!1),a.useBones&&a.computeBonesUsingShaders&&a.skeleton)){const i=a.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const s=i.getTransformMatrixTexture(a);e.setTexture("boneSampler",s),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const s=i.getTransformMatrices(a);s&&(e.setMatrices("mBones",s),t&&a.getScene().prePassRenderer&&a.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[a.uniqueId]||(t.previousBones[a.uniqueId]=s.slice()),e.setMatrices("mPreviousBones",t.previousBones[a.uniqueId]),ub(s,t.previousBones[a.uniqueId])))}}}function Em(a,e,t,i,s,r=!0){a._bindLight(e,t,i,s,r)}function ju(a,e,t,i,s=4){const r=Math.min(e.lightSources.length,s);for(let n=0;n<r;n++){const o=e.lightSources[n];Em(o,n,a,t,typeof i=="boolean"?i:i.SPECULARTERM,e.receiveShadows)}}function Sm(a,e,t,i){t.NUM_BONE_INFLUENCERS>0&&(i.addCPUSkinningFallback(0,e),a.push("matricesIndices"),a.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(a.push("matricesIndicesExtra"),a.push("matricesWeightsExtra")))}function Af(a,e){(e.INSTANCES||e.THIN_INSTANCES)&&oo(a,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&a.push("instanceColor")}function Cm(a,e,t=4,i=0){let s=0;for(let r=0;r<t&&a["LIGHT"+r];r++)r>0&&(s=i+r,e.addFallback(s,"LIGHT"+r)),a.SHADOWS||(a["SHADOW"+r]&&e.addFallback(i,"SHADOW"+r),a["SHADOWPCF"+r]&&e.addFallback(i,"SHADOWPCF"+r),a["SHADOWPCSS"+r]&&e.addFallback(i,"SHADOWPCSS"+r),a["SHADOWPOISSON"+r]&&e.addFallback(i,"SHADOWPOISSON"+r),a["SHADOWESM"+r]&&e.addFallback(i,"SHADOWESM"+r),a["SHADOWCLOSEESM"+r]&&e.addFallback(i,"SHADOWCLOSEESM"+r));return s++}function BE(a,e){return e.fogEnabled&&a.applyFog&&e.fogMode!==0}function yf(a,e,t,i,s,r,n,o=!1){n._areMiscDirty&&(n.LOGARITHMICDEPTH=t,n.POINTSIZE=i,n.FOG=s&&BE(a,e),n.NONUNIFORMSCALING=a.nonUniformScaling,n.ALPHATEST=r,n.DECAL_AFTER_DETAIL=o)}function qu(a,e,t,i,s=4,r=!1){if(!t._areLightsDirty)return t._needNormals;let n=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(a.lightsEnabled&&!r){for(const h of e.lightSources)if(vm(a,e,h,n,t,i,o),n++,n===s)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let h=n;h<s;h++)t["LIGHT"+h]!==void 0&&(t["LIGHT"+h]=!1,t["HEMILIGHT"+h]=!1,t["POINTLIGHT"+h]=!1,t["DIRLIGHT"+h]=!1,t["SPOTLIGHT"+h]=!1,t["SHADOW"+h]=!1,t["SHADOWCSM"+h]=!1,t["SHADOWCSMDEBUG"+h]=!1,t["SHADOWCSMNUM_CASCADES"+h]=!1,t["SHADOWCSMUSESHADOWMAXZ"+h]=!1,t["SHADOWCSMNOBLEND"+h]=!1,t["SHADOWCSM_RIGHTHANDED"+h]=!1,t["SHADOWPCF"+h]=!1,t["SHADOWPCSS"+h]=!1,t["SHADOWPOISSON"+h]=!1,t["SHADOWESM"+h]=!1,t["SHADOWCLOSEESM"+h]=!1,t["SHADOWCUBE"+h]=!1,t["SHADOWLOWQUALITY"+h]=!1,t["SHADOWMEDIUMQUALITY"+h]=!1);const l=a.getEngine().getCaps();return t.SHADOWFLOAT===void 0&&(o.needRebuild=!0),t.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),t.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&t.rebuild(),o.needNormals}function vm(a,e,t,i,s,r,n){switch(n.needNormals=!0,s["LIGHT"+i]===void 0&&(n.needRebuild=!0),s["LIGHT"+i]=!0,s["SPOTLIGHT"+i]=!1,s["HEMILIGHT"+i]=!1,s["POINTLIGHT"+i]=!1,s["DIRLIGHT"+i]=!1,t.prepareLightSpecificDefines(s,i),s["LIGHT_FALLOFF_PHYSICAL"+i]=!1,s["LIGHT_FALLOFF_GLTF"+i]=!1,s["LIGHT_FALLOFF_STANDARD"+i]=!1,t.falloffType){case Nt.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Nt.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Nt.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+i]=!0;break}if(r&&!t.specular.equalsFloats(0,0,0)&&(n.specularEnabled=!0),s["SHADOW"+i]=!1,s["SHADOWCSM"+i]=!1,s["SHADOWCSMDEBUG"+i]=!1,s["SHADOWCSMNUM_CASCADES"+i]=!1,s["SHADOWCSMUSESHADOWMAXZ"+i]=!1,s["SHADOWCSMNOBLEND"+i]=!1,s["SHADOWCSM_RIGHTHANDED"+i]=!1,s["SHADOWPCF"+i]=!1,s["SHADOWPCSS"+i]=!1,s["SHADOWPOISSON"+i]=!1,s["SHADOWESM"+i]=!1,s["SHADOWCLOSEESM"+i]=!1,s["SHADOWCUBE"+i]=!1,s["SHADOWLOWQUALITY"+i]=!1,s["SHADOWMEDIUMQUALITY"+i]=!1,e&&e.receiveShadows&&a.shadowsEnabled&&t.shadowEnabled){const o=t.getShadowGenerator(a.activeCamera)??t.getShadowGenerator();if(o){const l=o.getShadowMap();l&&l.renderList&&l.renderList.length>0&&(n.shadowEnabled=!0,o.prepareDefines(s,i))}}t.lightmapMode!=Nt.LIGHTMAP_DEFAULT?(n.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+i]=!0,s["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Nt.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+i]=!1,s["LIGHTMAPNOSPECULAR"+i]=!1)}function Rf(a,e,t,i,s,r=null,n=!1){let o=GE(a,i);r!==!1&&(o=cb(t,a,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==s&&(i.INSTANCES=s,o=!0),i.THIN_INSTANCES!==n&&(i.THIN_INSTANCES=n,o=!0),o&&i.markAsUnprocessed()}function UE(a,e){if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){e.NUM_BONE_INFLUENCERS=a.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(a.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=a.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=a.getScene().prePassRenderer;if(i&&i.enabled){const s=i.excludedSkinnedMesh.indexOf(a)===-1;e.BONES_VELOCITY_ENABLED=s}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function VE(a,e){const t=a.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function db(a,e){const t=a.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function If(a,e,t,i,s=!1,r=!0,n=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&a.isVerticesDataPresent("normal"),e._needNormals&&a.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?a.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){const o=a.useVertexColors&&a.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=a.hasVertexAlpha&&o&&r}return a.isVerticesDataPresent("instanceColor")&&(a.hasInstances||a.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&UE(a,e),s&&VE(a,e),n&&db(a,e),!0}function Pf(a,e){if(a.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=a.activeCamera.outputRenderTarget!==null&&a.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function kE(a,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,s=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=a.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!a.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||s!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function bm(a,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(a.prePassRenderer&&a.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=a.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=a.prePassRenderer.generateNormalsInWorldSpace;for(let r=0;r<s.length;r++){const n=a.prePassRenderer.getIndex(s[r].type);n!==-1?(e[s[r].define]=!0,e[s[r].index]=n):e[s[r].define]=!1}}else{e.PREPASS=!1;for(let r=0;r<s.length;r++)e[s[r].define]=!1}e.PREPASS!=i&&(e.markAsUnprocessed(),e.markAsImageProcessingDirty())}function GE(a,e){let t=!1;if(a.activeCamera){const i=e.CAMERA_ORTHOGRAPHIC?1:0,s=e.CAMERA_PERSPECTIVE?1:0,r=a.activeCamera.mode===1?1:0,n=a.activeCamera.mode===0?1:0;(i^r||s^n)&&(e.CAMERA_ORTHOGRAPHIC=r===1,e.CAMERA_PERSPECTIVE=n===1,t=!0)}return t}function Am(a,e,t,i,s=null,r=!1){s&&s.push("Light"+a),!r&&(e.push("vLightData"+a,"vLightDiffuse"+a,"vLightSpecular"+a,"vLightDirection"+a,"vLightFalloff"+a,"vLightGround"+a,"lightMatrix"+a,"shadowsInfo"+a,"depthValues"+a),t.push("shadowSampler"+a),t.push("depthSampler"+a),e.push("viewFrustumZ"+a,"cascadeBlendFactor"+a,"lightSizeUVCorrection"+a,"depthCorrection"+a,"penumbraDarkness"+a,"frustumLengths"+a),i&&(t.push("projectionLightSampler"+a),e.push("textureProjectionMatrix"+a)))}function Mf(a,e,t,i=4){let s,r=null;if(a.uniformsNames){const n=a;s=n.uniformsNames,r=n.uniformBuffersNames,e=n.samplers,t=n.defines,i=n.maxSimultaneousLights||0}else s=a,e||(e=[]);for(let n=0;n<i&&t["LIGHT"+n];n++)Am(n,s,e,t["PROJECTEDLIGHTTEXTURE"+n],r);t.NUM_MORPH_INFLUENCERS&&(s.push("morphTargetInfluences"),s.push("morphTargetCount")),t.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),e.push("bakedVertexAnimationTexture"))}class ee{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(ee.MiscDirtyFlag+ee.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(ee.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(ee.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new G),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new G),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new G),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(ee.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(ee.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case ee.WireFrameFillMode:case ee.LineListDrawMode:case ee.LineLoopDrawMode:case ee.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?ee.WireFrameFillMode:ee.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case ee.PointFillMode:case ee.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?ee.PointFillMode:ee.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(ee.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&O.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new G,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=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 Ea,this._useUBO=!1,this._fillMode=ee.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||Ae.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||X.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Bi(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=ee.ClockWiseSideOrientation:this.sideOrientation=ee.CounterClockWiseSideOrientation,this._uniformBuffer=new be(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),ee.OnEventObservable.notifyObservers(this,Es.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===ee.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===ee.MATERIAL_OPAQUE||this._transparencyMode===ee.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes){for(const s of i.subMeshes)if(s.getMaterial()===this)for(const r of s._drawWrappers)r&&this._materialContext===r.materialContext&&(r._wasPreviouslyReady=!1,r._wasPreviouslyUsingInstances=null,r._forceRebindOnNextCall=e)}e&&this.markAsDirty(ee.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===ee.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(Es.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,bf(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const s=this._scene.getEngine();this._cachedDepthWriteState=s.getDepthWrite(),s.setDepthWrite(!1)}if(this.disableColorWrite){const s=this._scene.getEngine();this._cachedColorWriteState=s.getColorWrite(),s.setColorWrite(!1)}if(this.depthFunction!==0){const s=this._scene.getEngine();this._cachedDepthFunctionState=s.getDepthFunction()||0,s.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Es.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Es.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Es.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),ee._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);r&&s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Ks(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const d=new Ss(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,r.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?u=d.effect.getCompilationError():(c=!1,setTimeout(l,16)))}c&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);r.clipPlane&&(n.clipPlane=h)};l()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,r=>{s(r)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(ee._DirtyCallbackArray.length=0,e&ee.TextureDirtyFlag&&ee._DirtyCallbackArray.push(ee._TextureDirtyCallBack),e&ee.LightDirtyFlag&&ee._DirtyCallbackArray.push(ee._LightsDirtyCallBack),e&ee.FresnelDirtyFlag&&ee._DirtyCallbackArray.push(ee._FresnelDirtyCallBack),e&ee.AttributesDirtyFlag&&ee._DirtyCallbackArray.push(ee._AttributeDirtyCallBack),e&ee.MiscDirtyFlag&&ee._DirtyCallbackArray.push(ee._MiscDirtyCallBack),e&ee.PrePassDirtyFlag&&ee._DirtyCallbackArray.push(ee._PrePassDirtyCallBack),ee._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(ee._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(ee._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(ee._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(ee._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(ee._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(ee._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(ee._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(ee._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(ee._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(ee._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(ee._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Gn.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(Es.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){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=_e.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 O.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=X.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 o=e.plugins[n];let l=(r=t.pluginManager)==null?void 0:r.getPlugin(o.name);if(!l){const h=X.Instantiate("BABYLON."+n);h&&(l=new h(t))}l==null||l.parse(o,i,s)}}}ee.TriangleFillMode=0;ee.WireFrameFillMode=1;ee.PointFillMode=2;ee.PointListDrawMode=3;ee.LineListDrawMode=4;ee.LineLoopDrawMode=5;ee.LineStripDrawMode=6;ee.TriangleStripDrawMode=7;ee.TriangleFanDrawMode=8;ee.ClockWiseSideOrientation=0;ee.CounterClockWiseSideOrientation=1;ee.TextureDirtyFlag=1;ee.LightDirtyFlag=2;ee.FresnelDirtyFlag=4;ee.AttributesDirtyFlag=8;ee.MiscDirtyFlag=16;ee.PrePassDirtyFlag=32;ee.AllDirtyFlag=63;ee.MATERIAL_OPAQUE=0;ee.MATERIAL_ALPHATEST=1;ee.MATERIAL_ALPHABLEND=2;ee.MATERIAL_ALPHATESTANDBLEND=3;ee.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;ee.MATERIAL_NORMALBLENDMETHOD_RNM=1;ee.OnEventObservable=new G;ee._AllDirtyCallBack=a=>a.markAllAsDirty();ee._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();ee._TextureDirtyCallBack=a=>a.markAsTexturesDirty();ee._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();ee._MiscDirtyCallBack=a=>a.markAsMiscDirty();ee._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();ee._LightsDirtyCallBack=a=>a.markAsLightDirty();ee._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();ee._FresnelAndMiscDirtyCallBack=a=>{ee._FresnelDirtyCallBack(a),ee._MiscDirtyCallBack(a)};ee._TextureAndMiscDirtyCallBack=a=>{ee._TextureDirtyCallBack(a),ee._MiscDirtyCallBack(a)};ee._DirtyCallbackArray=[];ee._RunDirtyCallBacks=a=>{for(const e of ee._DirtyCallbackArray)e(a)};E([I()],ee.prototype,"id",void 0);E([I()],ee.prototype,"uniqueId",void 0);E([I()],ee.prototype,"name",void 0);E([I()],ee.prototype,"metadata",void 0);E([I()],ee.prototype,"checkReadyOnEveryCall",void 0);E([I()],ee.prototype,"checkReadyOnlyOnce",void 0);E([I()],ee.prototype,"state",void 0);E([I("alpha")],ee.prototype,"_alpha",void 0);E([I("backFaceCulling")],ee.prototype,"_backFaceCulling",void 0);E([I("cullBackFaces")],ee.prototype,"_cullBackFaces",void 0);E([I()],ee.prototype,"sideOrientation",void 0);E([I("alphaMode")],ee.prototype,"_alphaMode",void 0);E([I()],ee.prototype,"_needDepthPrePass",void 0);E([I()],ee.prototype,"disableDepthWrite",void 0);E([I()],ee.prototype,"disableColorWrite",void 0);E([I()],ee.prototype,"forceDepthWrite",void 0);E([I()],ee.prototype,"depthFunction",void 0);E([I()],ee.prototype,"separateCullingPass",void 0);E([I("fogEnabled")],ee.prototype,"_fogEnabled",void 0);E([I()],ee.prototype,"pointSize",void 0);E([I()],ee.prototype,"zOffset",void 0);E([I()],ee.prototype,"zOffsetUnits",void 0);E([I()],ee.prototype,"pointsCloud",null);E([I()],ee.prototype,"fillMode",null);E([I()],ee.prototype,"useLogarithmicDepth",null);E([I()],ee.prototype,"transparencyMode",null);class _a extends ee{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const 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.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 _a(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,ft&&(e.tags=ft.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 o=this.subMaterials[n];o&&o.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 _a(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ft&&ft.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}V("BABYLON.MultiMaterial",_a);class fb{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class zE{}class _b{constructor(){this.visibleInstances={},this.batchCache=new dx,this.batchCacheReplacementModeInFrozenMode=new dx,this.instancesBufferSize=32*16*4}}class dx{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class pb{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class mb{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 z extends ut{static _GetDefaultSideOrientation(e){return e||z.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(y.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(y.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new G),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new G),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new G),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new G),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new G),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get 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 mb,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _b,this._thinInstanceDataStorage=new pb,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=z.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(o,l,h)=>{o&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),Cs.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const o=s._ranges;for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&this.createAnimationRange(l,o[l].from,o[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ft&&ft.HasTags(s)&&ft.AddTagsTo(this,ft.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const o=s.getDescendants(!0);for(let l=0;l<o.length;l++){const h=o[l];h.clone&&h.clone(e+"."+h.name,this)}}if(s.morphTargetManager&&(this.morphTargetManager=s.morphTargetManager),t.getPhysicsEngine){const o=t.getPhysicsEngine();if(n&&o)if(o.getPluginVersion()===1){const l=o.getImpostorForPhysicsObject(s);l&&(this.physicsImpostor=l.clone(this))}else o.getPluginVersion()===2&&s.physicsBody&&s.physicsBody.clone(this)}for(let o=0;o<t.particleSystems.length;o++){const l=t.particleSystems[o];l.emitter===s&&l.clone(l.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=o=>{o.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new G(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(y.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 O.Warn("You cannot use a mesh as LOD level twice"),this;const i=new fb(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===ve.ORTHOGRAPHIC_CAMERA?e.minZ:s.centerWorld.subtract(e.globalPosition).length();let n=r,o=1;if(i._useLODScreenCoverage){const l=e.screenArea;let h=s.radiusWorld*e.minZ/r;h=h*h*Math.PI,n=h/l,o=-1}if(o*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>o*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let l=0;l<i._LODLevels.length;l++){const h=i._LODLevels[l];if(o*h.distanceOrScreenCoverage<o*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 n,o;if(!this._geometry)return null;let r=s||(o=(n=this._userInstancedBuffersStorage)==null?void 0:n.vertexBuffers[e])==null?void 0:o.getFloatData(this.instances.length+1,i||t&&this._geometry.meshes.length!==1);return r||(r=this._geometry.getVerticesData(e,t,i)),r}getVertexBuffer(e,t){var i;return this._geometry?(t||(i=this._userInstancedBuffersStorage)==null?void 0:i.vertexBuffers[e])??this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var i;return this._geometry?!t&&((i=this._userInstancedBuffersStorage)==null?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?void 0:i.vertexBuffers[e];if(s)return s.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const i=[];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 l,h,c,u,d;if(this.delayLoadState===2||!super.isReady(e))return!1;if(!this.subMeshes||this.subMeshes.length===0||!e)return!0;const i=this.getEngine(),s=this.getScene(),r=t||i.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n){if(n._storeEffectOnSubMeshes)for(const f of this.subMeshes){const _=f.getMaterial();if(_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,f,r))return!1}else if(!_.isReady(this,r))return!1}}else if(!n.isReady(this,r))return!1}const o=i.currentRenderPassId;for(const f of this.lightSources){const _=f.getShadowGenerators();if(!_)continue;const p=_.values();for(let g=p.next();g.done!==!0;g=p.next()){const x=g.value;if(x&&(!((l=x.getShadowMap())!=null&&l.renderList)||(h=x.getShadowMap())!=null&&h.renderList&&((u=(c=x.getShadowMap())==null?void 0:c.renderList)==null?void 0:u.indexOf(this))!==-1)){const S=x.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let C=0;C<S.length;++C){i.currentRenderPassId=S[C];for(const v of this.subMeshes)if(!x.isReady(v,r,((d=v.getMaterial())==null?void 0:d.needAlphaBlendingForMesh(this))??!1))return i.currentRenderPassId=o,!1}i.currentRenderPassId=o}}}for(const f of this._internalMeshDataInfo._LODLevels)if(f.mesh&&!f.mesh.isReady(r))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 Ss(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++)Ss.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 le;r.set(t,e);const n=this.getScene();new zi(zi.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=zi.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(y.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(y.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(y.NormalKind);if(!r)return this;le.ComputeNormals(i,s,r),this.updateVerticesData(y.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(zi.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new zi(zi.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const s=new le;s.indices=e;const r=this.getScene();new zi(zi.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 ee.PointFillMode:n=null;break;case ee.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case ee.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==ee.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==ee.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 o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?o.intermediateDefaultRenderId:o.defaultRenderId;n.visibleInstances[e]=o[l],!n.visibleInstances[e]&&h&&(n.visibleInstances[e]=o[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 T;const n=i.visibleInstances[e._id],o=n?n.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let c=l.instancesBuffer,u=l.instancesPreviousBuffer;const f=(o+1)*16*4;for(;l.instancesBufferSize<f;)l.instancesBufferSize*=2;(!l.instancesData||h!=l.instancesBufferSize)&&(l.instancesData=new Float32Array(l.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousData||h!=l.instancesBufferSize)&&(l.instancesPreviousData=new Float32Array(l.instancesBufferSize/4));let _=0,p=0;const g=i.renderSelf[e._id],x=!c||h!==l.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!l.isFrozen||x)){const S=this.getWorldMatrix();if(g&&(this._scene.needsPreviousWorldMatrices&&(l.masterMeshPreviousWorldMatrix?(l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_),l.masterMeshPreviousWorldMatrix.copyFrom(S)):(l.masterMeshPreviousWorldMatrix=S.clone(),l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_))),S.copyToArray(l.instancesData,_),_+=16,p++),n){if(z.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((T=e.getMaterial())!=null&&T.needAlphaBlendingForMesh(e.getRenderingMesh()))){const C=this._scene.activeCamera.globalPosition;for(let v=0;v<n.length;v++){const b=n[v];b._distanceToCamera=m.Distance(b.getBoundingInfo().boundingSphere.centerWorld,C)}n.sort((v,b)=>v._distanceToCamera>b._distanceToCamera?-1:v._distanceToCamera<b._distanceToCamera?1:0)}for(let C=0;C<n.length;C++){const v=n[C],b=v.getWorldMatrix();b.copyToArray(l.instancesData,_),this._scene.needsPreviousWorldMatrices&&(v._previousWorldMatrix?(v._previousWorldMatrix.copyToArray(l.instancesPreviousData,_),v._previousWorldMatrix.copyFrom(b)):(v._previousWorldMatrix=b.clone(),v._previousWorldMatrix.copyToArray(l.instancesPreviousData,_))),_+=16,p++}}}else p=(g?1:0)+o;return x?(c&&c.dispose(),u&&u.dispose(),c=new Ji(r,l.instancesData,!0,16,!1,!0),l.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=c.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=c.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=c.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new Ji(r,l.instancesPreviousData,!0,16,!1,!0),l.instancesPreviousBuffer=u,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(c.updateDirectly(l.instancesData,0,p),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&u.updateDirectly(l.instancesPreviousData,0,p)),this._processInstancedBuffers(n,g),this.getScene()._activeIndices.addCount(e.indexCount*p,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,p),this._scene.needsPreviousWorldMatrices&&!x&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&u.updateDirectly(l.instancesData,0,p),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,s){var n;const r=((n=this._thinInstanceDataStorage)==null?void 0:n.instancesCount)??0;this.getScene()._activeIndices.addCount(e.indexCount*r,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,r),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,r):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),s.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,s,r,n,o,l){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]&&(o&&o(!1,e.getWorldMatrix(),l),u++,this._draw(t,s,this._instanceDataStorage.overridenInstanceCount));const d=r.visibleInstances[t._id];if(d){const f=d.length;u+=f;for(let _=0;_<f;_++){const g=d[_].getWorldMatrix();o&&o(!0,g,l),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}renderWithRenderPassId(e,t,i,s,r=!0){const n=this._scene.getEngine(),o=n.currentRenderPassId;if(e!==void 0&&(n.currentRenderPassId=e),s)(!r||r&&s.isInFrustum(this._scene._frustumPlanes))&&this.render(s,!!t,i);else for(let l=0;l<this.subMeshes.length;l++){const h=this.subMeshes[l];(!r||r&&h.isInFrustum(this._scene._frustumPlanes))&&this.render(h,!!t,i)}return e!==void 0&&(n.currentRenderPassId=o),this}render(e,t,i){var A,P;const s=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const r=((A=s.activeCameras)==null?void 0:A.length)??0;if((r>1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const o=this._getInstancesRenderList(e._id,!!i);if(o.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const l=s.getEngine();let h=0,c=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(h=s.activeCamera.maxZ,c=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),d=o.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,f=this._instanceDataStorage,_=e.getMaterial();if(!_)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;if(!f.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,e,d))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this}else if(!_.isReady(this,d))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=_}else if(_._storeEffectOnSubMeshes&&!((P=e._drawWrapper)!=null&&P._wasPreviouslyReady)||!_._storeEffectOnSubMeshes&&!_._getDrawWrapper()._wasPreviouslyReady)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let p;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?p=e._drawWrapper:p=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const g=(p==null?void 0:p.effect)??null;for(const L of s._beforeRenderingMeshStage)L.action(this,e,o,g);if(!p||!g)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;const x=i||this;let T;if(!f.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const L=x._getWorldMatrixDeterminant();T=this.overrideMaterialSideOrientation,T==null&&(T=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),L<0&&(T=T===ee.ClockWiseSideOrientation?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation),f.sideOrientation=T}else T=f.sideOrientation;const S=this._internalMeshDataInfo._effectiveMaterial._preBind(p,T);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const C=this._internalMeshDataInfo._effectiveMaterial,v=C.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,g,v,!1);const b=x.getWorldMatrix();C._storeEffectOnSubMeshes?C.bindForSubMesh(b,this,e):C.bind(b,this),!C.backFaceCulling&&C.separateCullingPass&&(l.setState(!0,C.zOffset,!1,!S,C.cullBackFaces,C.stencil,C.zOffsetUnits),this._processRendering(this,e,g,v,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),l.setState(!0,C.zOffset,!1,S,C.cullBackFaces,C.stencil,C.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,g,v,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const L of s._afterRenderingMeshStage)L.action(this,e,o,g);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),c&&(c.maxZ=h,s.updateTransformMatrix(!0)),s.performancePriority===Gn.Aggressive&&!f.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(y.MatricesWeightsKind)&&(this.isVerticesDataPresent(y.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(y.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(y.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(y.MatricesWeightsExtraKind),t=this.getVerticesData(y.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(y.MatricesWeightsKind,t),this.setVerticesData(y.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(y.MatricesWeightsExtraKind),t=this.getVerticesData(y.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,o=0;const l=e===null?4:8,h=[];for(let g=0;g<=l;g++)h[g]=0;const c=.001;for(let g=0;g<i;g+=4){let x=t[g],T=x,S=T===0?0:1;for(let C=1;C<l;C++){const v=C<4?t[g+C]:e[g+C-4];v>x&&s++,v!==0&&S++,T+=v,x=v}if(h[S]++,S>n&&(n=S),T===0)r++;else{const C=1/T;let v=0;for(let b=0;b<l;b++)b<4?v+=Math.abs(t[g+b]-t[g+b]*C):v+=Math.abs(e[g+b-4]-e[g+b-4]*C);v>c&&o++}}const u=this.skeleton.bones.length,d=this.getVerticesData(y.MatricesIndicesKind),f=this.getVerticesData(y.MatricesIndicesExtraKind);let _=0;for(let g=0;g<i;g+=4)for(let x=0;x<l;x++){const T=x<4?d[g+x]:f[g+x-4];(T>=u||T<0)&&_++}const p="Number of Weights = "+i/4+`
Maximum influences = `+n+`
Missing Weights = `+r+`
Not Sorted = `+s+`
Not Normalized = `+o+`
WeightCounts = [`+h+`]
Number of bones = `+u+`
Bad Bone Indices = `+_;return{skinned:!0,valid:r===0&&o===0&&_===0,report:p}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return X.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(s=>{s.refreshBoundingInfo(),s._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(y.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(y.PositionKind);const s=m.Zero();let r;for(r=0;r<i.length;r+=3)m.TransformCoordinatesFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).toArray(i,r);if(this.setVerticesData(y.PositionKind,i,this.getVertexBuffer(y.PositionKind).isUpdatable()),this.isVerticesDataPresent(y.NormalKind)){for(i=this.getVerticesData(y.NormalKind),r=0;r<i.length;r+=3)m.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).normalize().toArray(i,r);this.setVerticesData(y.NormalKind,i,this.getVertexBuffer(y.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(y.TangentKind)){for(i=this.getVerticesData(y.TangentKind),r=0;r<i.length;r+=4)m.TransformNormalFromFloatsToRef(i[r],i[r+1],i[r+2],e,s).normalize().toArray(i,r);this.setVerticesData(y.TangentKind,i,this.getVertexBuffer(y.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return this._geometry?this._geometry._generatePointsArray():!1}clone(e="",t=null,i,s=!0){return new z(e,this.getScene(),t,this,i,s)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(const s in i.meshMap){const r=i.meshMap[s];r&&(r._internalMeshDataInfo._source=null,i.meshMap[s]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const s=this.getScene().meshes;for(const r of s){const n=r;n._internalMeshDataInfo&&n._internalMeshDataInfo._source&&n._internalMeshDataInfo._source===this&&(n._internalMeshDataInfo._source=null)}}i._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,s,r,n,o=!1,l){const h=this.getScene(),c=u=>{const d=u.width,f=u.height,p=this.getEngine().createCanvas(d,f).getContext("2d");p.drawImage(u,0,0);const g=p.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(g,d,f,t,i,r,n,o),s&&s(this)};return X.LoadImage(e,c,l||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,l=!1){if(!this.isVerticesDataPresent(y.PositionKind)||!this.isVerticesDataPresent(y.NormalKind)||!this.isVerticesDataPresent(y.UVKind))return O.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(y.PositionKind,!0,!0),c=this.getVerticesData(y.NormalKind),u=this.getVerticesData(y.UVKind);let d=m.Zero();const f=m.Zero(),_=Z.Zero();n=n||Z.Zero(),o=o||new Z(1,1);for(let p=0;p<h.length;p+=3){m.FromArrayToRef(h,p,d),m.FromArrayToRef(c,p,f),Z.FromArrayToRef(u,p/3*2,_);const g=Math.abs(_.x*o.x+n.x%1)*(t-1)%t|0,x=Math.abs(_.y*o.y+n.y%1)*(i-1)%i|0,T=(g+x*t)*4,S=e[T]/255,C=e[T+1]/255,v=e[T+2]/255,b=S*.3+C*.59+v*.11;f.normalize(),f.scaleInPlace(s+(r-s)*b),d=d.add(f),d.toArray(h,p)}return le.ComputeNormals(h,this.getIndices(),c),l?(this.setVerticesData(y.PositionKind,h),this.setVerticesData(y.NormalKind,c),this.setVerticesData(y.UVKind,u)):(this.updateVerticesData(y.PositionKind,h),this.updateVerticesData(y.NormalKind,c)),this}_getFlattenedNormals(e,t){const i=new Float32Array(e.length*3);let s=0;const r=this.overrideMaterialSideOrientation===(this._scene.useRightHandedSystem?1:0);for(let n=0;n<e.length;n+=3){const o=m.FromArray(t,e[n]*3),l=m.FromArray(t,e[n+1]*3),h=m.FromArray(t,e[n+2]*3),c=o.subtract(l),u=h.subtract(l),d=m.Normalize(m.Cross(c,u));r&&d.scaleInPlace(-1);for(let f=0;f<3;f++)i[s++]=d.x,i[s++]=d.y,i[s++]=d.z}return i}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds(),i=this.getIndices(),s={},r=(o,l)=>{const h=new Float32Array(i.length*l);let c=0;for(let u=0;u<i.length;u++)for(let d=0;d<l;d++)h[c++]=o[i[u]*l+d];return h},n=this.geometry?this.subMeshes.slice(0):[];for(const o of t)s[o]=this.getVerticesData(o);for(const o of t){const l=this.getVertexBuffer(o),h=l.getStrideSize();if(e&&o===y.NormalKind){const c=this._getFlattenedNormals(i,s[y.PositionKind]);this.setVerticesData(y.NormalKind,c,l.isUpdatable(),h)}else this.setVerticesData(o,r(s[o],h),l.isUpdatable(),h)}if(this.morphTargetManager){for(let o=0;o<this.morphTargetManager.numTargets;o++){const l=this.morphTargetManager.getTarget(o),h=l.getPositions();l.setPositions(r(h,3));const c=l.getNormals();c&&l.setNormals(e?this._getFlattenedNormals(i,h):r(c,3));const u=l.getTangents();u&&l.setTangents(r(u,3));const d=l.getUVs();d&&l.setUVs(r(d,2))}this.morphTargetManager.synchronize()}for(let o=0;o<i.length;o++)i[o]=o;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(const o of n)Ss.AddToMesh(o.materialIndex,o.indexStart,o.indexCount,o.indexStart,o.indexCount,this);return this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=le.ExtractFromMesh(this);let i;if(e&&this.isVerticesDataPresent(y.NormalKind)&&t.normals)for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;if(t.indices){let s;for(i=0;i<t.indices.length;i+=3)s=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=s}return t.applyToMesh(this,this.isVertexBufferUpdatable(y.PositionKind)),this}increaseVertices(e=1){const t=le.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,s=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,n=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(!i||!s)O.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");else{t.indices=i,t.positions=s,r&&(t.uvs=r),n&&(t.normals=n);const o=e+1,l=new Array;for(let v=0;v<o+1;v++)l[v]=new Array;let h,c;const u=new m(0,0,0),d=new m(0,0,0),f=new Z(0,0),_=new Array,p=new Array,g=new Array;let x,T=s.length,S;r&&(S=r.length);let C;n&&(C=n.length);for(let v=0;v<i.length;v+=3){p[0]=i[v],p[1]=i[v+1],p[2]=i[v+2];for(let b=0;b<3;b++)if(h=p[b],c=p[(b+1)%3],g[h]===void 0&&g[c]===void 0?(g[h]=new Array,g[c]=new Array):(g[h]===void 0&&(g[h]=new Array),g[c]===void 0&&(g[c]=new Array)),g[h][c]===void 0&&g[c][h]===void 0){g[h][c]=[],u.x=(s[3*c]-s[3*h])/o,u.y=(s[3*c+1]-s[3*h+1])/o,u.z=(s[3*c+2]-s[3*h+2])/o,n&&(d.x=(n[3*c]-n[3*h])/o,d.y=(n[3*c+1]-n[3*h+1])/o,d.z=(n[3*c+2]-n[3*h+2])/o),r&&(f.x=(r[2*c]-r[2*h])/o,f.y=(r[2*c+1]-r[2*h+1])/o),g[h][c].push(h);for(let A=1;A<o;A++)g[h][c].push(s.length/3),s[T++]=s[3*h]+A*u.x,s[T++]=s[3*h+1]+A*u.y,s[T++]=s[3*h+2]+A*u.z,n&&(n[C++]=n[3*h]+A*d.x,n[C++]=n[3*h+1]+A*d.y,n[C++]=n[3*h+2]+A*d.z),r&&(r[S++]=r[2*h]+A*f.x,r[S++]=r[2*h+1]+A*f.y);g[h][c].push(c),g[c][h]=new Array,x=g[h][c].length;for(let A=0;A<x;A++)g[c][h][A]=g[h][c][x-1-A]}l[0][0]=i[v],l[1][0]=g[i[v]][i[v+1]][1],l[1][1]=g[i[v]][i[v+2]][1];for(let b=2;b<o;b++){l[b][0]=g[i[v]][i[v+1]][b],l[b][b]=g[i[v]][i[v+2]][b],u.x=(s[3*l[b][b]]-s[3*l[b][0]])/b,u.y=(s[3*l[b][b]+1]-s[3*l[b][0]+1])/b,u.z=(s[3*l[b][b]+2]-s[3*l[b][0]+2])/b,n&&(d.x=(n[3*l[b][b]]-n[3*l[b][0]])/b,d.y=(n[3*l[b][b]+1]-n[3*l[b][0]+1])/b,d.z=(n[3*l[b][b]+2]-n[3*l[b][0]+2])/b),r&&(f.x=(r[2*l[b][b]]-r[2*l[b][0]])/b,f.y=(r[2*l[b][b]+1]-r[2*l[b][0]+1])/b);for(let A=1;A<b;A++)l[b][A]=s.length/3,s[T++]=s[3*l[b][0]]+A*u.x,s[T++]=s[3*l[b][0]+1]+A*u.y,s[T++]=s[3*l[b][0]+2]+A*u.z,n&&(n[C++]=n[3*l[b][0]]+A*d.x,n[C++]=n[3*l[b][0]+1]+A*d.y,n[C++]=n[3*l[b][0]+2]+A*d.z),r&&(r[S++]=r[2*l[b][0]]+A*f.x,r[S++]=r[2*l[b][0]+1]+A*f.y)}l[o]=g[i[v+1]][i[v+2]],_.push(l[0][0],l[1][0],l[1][1]);for(let b=1;b<o;b++){let A;for(A=0;A<b;A++)_.push(l[b][A],l[b+1][A],l[b+1][A+1]),_.push(l[b][A],l[b+1][A+1],l[b][A+1]);_.push(l[b][A],l[b+1][A],l[b+1][A+1])}}t.indices=_,t.applyToMesh(this,this.isVertexBufferUpdatable(y.PositionKind))}}forceSharedVertices(){const e=le.ExtractFromMesh(this),t=e.uvs,i=e.indices,s=e.positions,r=e.colors,n=e.matricesIndices,o=e.matricesWeights,l=e.matricesIndicesExtra,h=e.matricesWeightsExtra;if(i===void 0||s===void 0||i===null||s===null)O.Warn("VertexData contains empty entries");else{const c=new Array,u=new Array,d=new Array,f=new Array,_=new Array,p=new Array,g=new Array,x=new Array;let T=new Array,S=0;const C={};let v,b;for(let P=0;P<i.length;P+=3){b=[i[P],i[P+1],i[P+2]],T=[];for(let L=0;L<3;L++){T[L]="";for(let w=0;w<3;w++)Math.abs(s[3*b[L]+w])<1e-8&&(s[3*b[L]+w]=0),T[L]+=s[3*b[L]+w]+"|"}if(!(T[0]==T[1]||T[0]==T[2]||T[1]==T[2]))for(let L=0;L<3;L++){if(v=C[T[L]],v===void 0){C[T[L]]=S,v=S++;for(let w=0;w<3;w++)c.push(s[3*b[L]+w]);if(r!=null)for(let w=0;w<4;w++)f.push(r[4*b[L]+w]);if(t!=null)for(let w=0;w<2;w++)d.push(t[2*b[L]+w]);if(n!=null)for(let w=0;w<4;w++)_.push(n[4*b[L]+w]);if(o!=null)for(let w=0;w<4;w++)p.push(o[4*b[L]+w]);if(l!=null)for(let w=0;w<4;w++)g.push(l[4*b[L]+w]);if(h!=null)for(let w=0;w<4;w++)x.push(h[4*b[L]+w])}u.push(v)}}const A=new Array;le.ComputeNormals(c,u,A),e.positions=c,e.indices=u,e.normals=A,t!=null&&(e.uvs=d),r!=null&&(e.colors=f),n!=null&&(e.matricesIndices=_),o!=null&&(e.matricesWeights=p),l!=null&&(e.matricesIndicesExtra=g),o!=null&&(e.matricesWeightsExtra=x),e.applyToMesh(this,this.isVertexBufferUpdatable(y.PositionKind))}}static _instancedMeshFactory(e,t){throw Ge("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw Ge("PhysicsImpostor")}createInstance(e){return z._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++)this.instances[e]._syncSubMeshes();return this}optimizeIndices(e){const t=this.getIndices(),i=this.getVerticesData(y.PositionKind);if(!i||!t)return this;const s=[];for(let n=0;n<i.length;n=n+3)s.push(m.FromArray(i,n));const r=[];return Jr.SyncAsyncForLoop(s.length,40,n=>{const o=s.length-1-n,l=s[o];for(let h=0;h<o;++h){const c=s[h];if(l.equals(c)){r[o]=h;break}}},()=>{for(let o=0;o<t.length;++o)t[o]=r[t[o]]||t[o];const n=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=n,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),ft&&ft.HasTags(this)&&(e.tags=ft.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let i=0;i<this.subMeshes.length;i++){const s=this.subMeshes[i];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(he.NAME_PHYSICSENGINE)){const i=this.getPhysicsImpostor();i&&(e.physicsMass=i.getParam("mass"),e.physicsFriction=i.getParam("friction"),e.physicsRestitution=i.getParam("mass"),e.physicsImpostor=i.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let i=0;i<this.instances.length;i++){const s=this.instances[i];if(s.doNotSerialize)continue;const r={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(r),s.rotationQuaternion?r.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(r.rotation=s.rotation.asArray()),this.getScene()._getComponent(he.NAME_PHYSICSENGINE)){const n=s.getPhysicsImpostor();n&&(r.physicsMass=n.getParam("mass"),r.physicsFriction=n.getParam("friction"),r.physicsRestitution=n.getParam("mass"),r.physicsImpostor=n.type)}s.metadata&&(r.metadata=s.metadata),s.actionManager&&(r.actions=s.actionManager.serialize(s.name)),e.instances.push(r),_e.AppendSerializedAnimations(s,r),r.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const i={data:{},sizes:{},strides:{}};for(const s in this._userThinInstanceBuffersStorage.data)i.data[s]=Array.from(this._userThinInstanceBuffersStorage.data[s]),i.sizes[s]=this._userThinInstanceBuffersStorage.sizes[s],i.strides[s]=this._userThinInstanceBuffersStorage.strides[s];e.thinInstances.userThinInstance=i}return _e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){O.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const i=e.getActiveTarget(t),s=i.getPositions();if(!s){O.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(y.PositionKind+t,s,!1,3);const r=i.getNormals();r&&this.geometry.setVerticesData(y.NormalKind+t,r,!1,3);const n=i.getTangents();n&&this.geometry.setVerticesData(y.TangentKind+t,n,!1,3);const o=i.getUVs();o&&this.geometry.setVerticesData(y.UVKind+"_"+t,o,!1,2)}}else{let t=0;for(;this.geometry.isVerticesDataPresent(y.PositionKind+t);)this.geometry.removeVerticesData(y.PositionKind+t),this.geometry.isVerticesDataPresent(y.NormalKind+t)&&this.geometry.removeVerticesData(y.NormalKind+t),this.geometry.isVerticesDataPresent(y.TangentKind+t)&&this.geometry.removeVerticesData(y.TangentKind+t),this.geometry.isVerticesDataPresent(y.UVKind+t)&&this.geometry.removeVerticesData(y.UVKind+"_"+t),t++}}static Parse(e,t,i){let s;if(e.type&&e.type==="LinesMesh"?s=z._LinesMeshParser(e,t):e.type&&e.type==="GroundMesh"?s=z._GroundMeshParser(e,t):e.type&&e.type==="GoldbergMesh"?s=z._GoldbergMeshParser(e,t):e.type&&e.type==="GreasedLineMesh"?s=z._GreasedLineMeshParser(e,t):e.type&&e.type==="TrailMesh"?s=z._TrailMeshParser(e,t):s=new z(e.name,t),s.id=e.id,s._waitingParsedUniqueId=e.uniqueId,ft&&ft.AddTagsTo(s,e.tags),s.position=m.FromArray(e.position),e.metadata!==void 0&&(s.metadata=e.metadata),e.rotationQuaternion?s.rotationQuaternion=Q.FromArray(e.rotationQuaternion):e.rotation&&(s.rotation=m.FromArray(e.rotation)),s.scaling=m.FromArray(e.scaling),e.localMatrix?s.setPreTransformMatrix(D.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(D.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s.isVisible=e.isVisible,s.infiniteDistance=e.infiniteDistance,s.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,s.showBoundingBox=e.showBoundingBox,s.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,e.applyFog!==void 0&&(s.applyFog=e.applyFog),e.pickable!==void 0&&(s.isPickable=e.pickable),e.alphaIndex!==void 0&&(s.alphaIndex=e.alphaIndex),s.receiveShadows=e.receiveShadows,e.billboardMode!==void 0&&(s.billboardMode=e.billboardMode),e.visibility!==void 0&&(s.visibility=e.visibility),s.checkCollisions=e.checkCollisions,s.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(s.ellipsoid=m.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(s.ellipsoidOffset=m.FromArray(e.ellipsoidOffset)),e.overrideMaterialSideOrientation!==void 0&&(s.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation),e.isBlocker!==void 0&&(s.isBlocker=e.isBlocker),s._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(s._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.actions!==void 0&&(s._waitingData.actions=e.actions),e.overlayAlpha!==void 0&&(s.overlayAlpha=e.overlayAlpha),e.overlayColor!==void 0&&(s.overlayColor=q.FromArray(e.overlayColor)),e.renderOverlay!==void 0&&(s.renderOverlay=e.renderOverlay),s.isUnIndexed=!!e.isUnIndexed,s.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s.buildBoundingInfo(m.FromArray(e.boundingBoxMinimum),m.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(s._binaryInfo=e._binaryInfo),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(y.UVKind),e.hasUVs2&&s._delayInfo.push(y.UV2Kind),e.hasUVs3&&s._delayInfo.push(y.UV3Kind),e.hasUVs4&&s._delayInfo.push(y.UV4Kind),e.hasUVs5&&s._delayInfo.push(y.UV5Kind),e.hasUVs6&&s._delayInfo.push(y.UV6Kind),e.hasColors&&s._delayInfo.push(y.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(y.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(y.MatricesWeightsKind),s._delayLoadingFunction=zi._ImportGeometry,Qi.ForceFullSceneLoadingForIncremental&&s._checkDelayState()):zi._ImportGeometry(e,s),e.materialUniqueId?s._waitingMaterialId=e.materialUniqueId:e.materialId&&(s._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],o=Si("BABYLON.Animation");o&&s.animations.push(o.Parse(n))}Ct.ParseAnimationRanges(s,e,t)}if(e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?s.layerMask=Math.abs(parseInt(e.layerMask)):s.layerMask=268435455,e.physicsImpostor&&z._PhysicsImpostorParser(t,s,e),e.lodMeshIds&&(s._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let r=0;r<e.instances.length;r++){const n=e.instances[r],o=s.createInstance(n.name);if(n.id&&(o.id=n.id),ft&&(n.tags?ft.AddTagsTo(o,n.tags):ft.AddTagsTo(o,e.tags)),o.position=m.FromArray(n.position),n.metadata!==void 0&&(o.metadata=n.metadata),n.parentId!==void 0&&(o._waitingParentId=n.parentId),n.parentInstanceIndex!==void 0&&(o._waitingParentInstanceIndex=n.parentInstanceIndex),n.isEnabled!==void 0&&n.isEnabled!==null&&o.setEnabled(n.isEnabled),n.isVisible!==void 0&&n.isVisible!==null&&(o.isVisible=n.isVisible),n.isPickable!==void 0&&n.isPickable!==null&&(o.isPickable=n.isPickable),n.rotationQuaternion?o.rotationQuaternion=Q.FromArray(n.rotationQuaternion):n.rotation&&(o.rotation=m.FromArray(n.rotation)),o.scaling=m.FromArray(n.scaling),n.checkCollisions!=null&&n.checkCollisions!=null&&(o.checkCollisions=n.checkCollisions),n.pickable!=null&&n.pickable!=null&&(o.isPickable=n.pickable),n.showBoundingBox!=null&&n.showBoundingBox!=null&&(o.showBoundingBox=n.showBoundingBox),n.showSubMeshesBoundingBox!=null&&n.showSubMeshesBoundingBox!=null&&(o.showSubMeshesBoundingBox=n.showSubMeshesBoundingBox),n.alphaIndex!=null&&n.showSubMeshesBoundingBox!=null&&(o.alphaIndex=n.alphaIndex),n.physicsImpostor&&z._PhysicsImpostorParser(t,o,n),n.actions!==void 0&&(o._waitingData.actions=n.actions),n.animations){for(let l=0;l<n.animations.length;l++){const h=n.animations[l],c=Si("BABYLON.Animation");c&&o.animations.push(c.Parse(h))}Ct.ParseAnimationRanges(o,n,t),n.autoAnimate&&t.beginAnimation(o,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1)}}if(e.thinInstances){const r=e.thinInstances;if(s.thinInstanceEnablePicking=!!r.enablePicking,r.matrixData?(s.thinInstanceSetBuffer("matrix",new Float32Array(r.matrixData),16,!1),s._thinInstanceDataStorage.matrixBufferSize=r.matrixBufferSize,s._thinInstanceDataStorage.instancesCount=r.instancesCount):s._thinInstanceDataStorage.matrixBufferSize=r.matrixBufferSize,e.thinInstances.userThinInstance){const n=e.thinInstances.userThinInstance;for(const o in n.data)s.thinInstanceSetBuffer(o,new Float32Array(n.data[o]),n.strides[o],!1),s._userThinInstanceBuffersStorage.sizes[o]=n.sizes[o]}}return s}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(y.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(y.PositionKind)||this.setVerticesData(y.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(y.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(y.NormalKind)||this.setVerticesData(y.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(y.PositionKind))return this;if(!this.isVerticesDataPresent(y.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(y.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(y.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){const x=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=x}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let s=this.getVerticesData(y.PositionKind);if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s));let r=this.getVerticesData(y.NormalKind);if(t){if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r))}const n=this.getVerticesData(y.MatricesIndicesKind),o=this.getVerticesData(y.MatricesWeightsKind);if(!o||!n)return this;const l=this.numBoneInfluencers>4,h=l?this.getVerticesData(y.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(y.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=m.Zero(),f=new D,_=new D;let p=0,g;for(let x=0;x<s.length;x+=3,p+=4){let T;for(g=0;g<4;g++)T=o[p+g],T>0&&(D.FromFloat32ArrayToRefScaled(u,Math.floor(n[p+g]*16),T,_),f.addToSelf(_));if(l)for(g=0;g<4;g++)T=c[p+g],T>0&&(D.FromFloat32ArrayToRefScaled(u,Math.floor(h[p+g]*16),T,_),f.addToSelf(_));m.TransformCoordinatesFromFloatsToRef(i._sourcePositions[x],i._sourcePositions[x+1],i._sourcePositions[x+2],f,d),d.toArray(s,x),t&&(m.TransformNormalFromFloatsToRef(i._sourceNormals[x],i._sourceNormals[x+1],i._sourceNormals[x+2],f,d),d.toArray(r,x)),f.reset()}return this.updateVerticesData(y.PositionKind,s),t&&this.updateVerticesData(y.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach(function(s){const n=s.getBoundingInfo().boundingBox;!t||!i?(t=n.minimumWorld,i=n.maximumWorld):(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld))}),!t||!i?{min:m.Zero(),max:m.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?z.MinMax(e):e;return m.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return gm(z._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return LE(z._MergeMeshesCoroutine(e,t,i,s,r,n,!0),tb())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let A=0;for(l=0;l<e.length;l++)if(A+=e[l].getTotalVertices(),A>=65536)return O.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const h=new Array,c=new Array,u=new Array,d=e[0].overrideMaterialSideOrientation;for(l=0;l<e.length;l++){const A=e[l];if(A.isAnInstance)return O.Warn("Cannot merge instance meshes."),null;if(d!==A.overrideMaterialSideOrientation)return O.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),null;if(r&&u.push(A.getTotalIndices()),n)if(A.material){const P=A.material;if(P instanceof _a){for(let L=0;L<P.subMaterials.length;L++)h.indexOf(P.subMaterials[L])<0&&h.push(P.subMaterials[L]);for(let L=0;L<A.subMeshes.length;L++)c.push(h.indexOf(P.subMaterials[A.subMeshes[L].materialIndex])),u.push(A.subMeshes[L].indexCount)}else{h.indexOf(P)<0&&h.push(P);for(let L=0;L<A.subMeshes.length;L++)c.push(h.indexOf(P)),u.push(A.subMeshes[L].indexCount)}}else for(let P=0;P<A.subMeshes.length;P++)c.push(0),u.push(A.subMeshes[P].indexCount)}const f=e[0],_=A=>{const P=A.computeWorldMatrix(!0);return{vertexData:le.ExtractFromMesh(A,!1,!1),transform:P}},{vertexData:p,transform:g}=_(f);o&&(yield);const x=new Array(e.length-1);for(let A=1;A<e.length;A++)x[A-1]=_(e[A]),o&&(yield);const T=p._mergeCoroutine(g,x,i,o,!t);let S=T.next();for(;!S.done;)o&&(yield),S=T.next();const C=S.value;s||(s=new z(f.name+"_merged",f.getScene()));const v=C._applyToCoroutine(s,void 0,o);let b=v.next();for(;!b.done;)o&&(yield),b=v.next();if(s.checkCollisions=f.checkCollisions,s.overrideMaterialSideOrientation=f.overrideMaterialSideOrientation,t)for(l=0;l<e.length;l++)e[l].dispose();if(r||n){s.releaseSubMeshes(),l=0;let A=0;for(;l<u.length;)Ss.CreateFromIndices(0,A,u[l],s,void 0,!1),A+=u[l],l++;for(const P of s.subMeshes)P.refreshBoundingInfo();s.computeWorldMatrix(!0)}if(n){const A=new _a(f.name+"_merged",f.getScene());A.subMaterials=h;for(let P=0;P<s.subMeshes.length;P++)s.subMeshes[P].materialIndex=c[P];s.material=A}else s.material=f.material;return s}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(t!=-1){if(t!==this.instances.length-1){const i=this.instances[this.instances.length-1];this.instances[t]=i,i._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this.overrideMaterialSideOrientation===ee.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?ee.PointFillMode:t.forceWireframe?ee.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,s,r,n,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,s){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,s,r,n,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,s,r,n,o){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,s,r,n,o,l,h,c){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,s,r,n,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,s,r,n,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,s,r,n,o,l){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,s,r,n,o,l,h,c){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,s,r,n,o,l,h,c,u,d){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,s,r,n,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,s,r){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,s,r,n,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,s,r,n,o,l,h,c,u){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,s,r,n,o,l,h,c){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,s,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}z.FRONTSIDE=le.FRONTSIDE;z.BACKSIDE=le.BACKSIDE;z.DOUBLESIDE=le.DOUBLESIDE;z.DEFAULTSIDE=le.DEFAULTSIDE;z.NO_CAP=0;z.CAP_START=1;z.CAP_END=2;z.CAP_ALL=3;z.NO_FLIP=0;z.FLIP_TILE=1;z.ROTATE_TILE=2;z.FLIP_ROW=3;z.ROTATE_ROW=4;z.FLIP_N_ROTATE_TILE=5;z.FLIP_N_ROTATE_ROW=6;z.CENTER=0;z.LEFT=1;z.RIGHT=2;z.TOP=3;z.BOTTOM=4;z.INSTANCEDMESH_SORT_TRANSPARENT=!1;z._GroundMeshParser=(a,e)=>{throw Ge("GroundMesh")};z._GoldbergMeshParser=(a,e)=>{throw Ge("GoldbergMesh")};z._LinesMeshParser=(a,e)=>{throw Ge("LinesMesh")};z._GreasedLineMeshParser=(a,e)=>{throw Ge("GreasedLineMesh")};z._GreasedLineRibbonMeshParser=(a,e)=>{throw Ge("GreasedLineRibbonMesh")};z._TrailMeshParser=(a,e)=>{throw Ge("TrailMesh")};V("BABYLON.Mesh",z);z._instancedMeshFactory=(a,e)=>{const t=new ym(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class ym extends ut{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&X.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&X.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&X.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&X.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||O.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||O.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Ke.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new D);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,U.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(U.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{const i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,s){const r=(s||this._sourceMesh).createInstance(e);if(Cs.DeepCopy(this,r,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(r.parent=t),!i)for(let n=0;n<this.getScene().meshes.length;n++){const o=this.getScene().meshes[n];o.parent===this&&o.clone(o.name,r)}return r.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(r),r}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);s&&i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}}z.prototype.registerInstancedBuffer=function(a,e){var t,i;if((i=(t=this._userInstancedBuffersStorage)==null?void 0:t.vertexBuffers[a])==null||i.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(const s of this.instances)s.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[a]=null,this._userInstancedBuffersStorage.strides[a]=e,this._userInstancedBuffersStorage.sizes[a]=e*32,this._userInstancedBuffersStorage.data[a]=new Float32Array(this._userInstancedBuffersStorage.sizes[a]),this._userInstancedBuffersStorage.vertexBuffers[a]=new y(this.getEngine(),this._userInstancedBuffersStorage.data[a],a,!0,!1,e,!0);for(const s of this.instances)s.instancedBuffers[a]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()};z.prototype._processInstancedBuffers=function(a,e){const t=a?a.length:0;for(const i in this.instancedBuffers){let s=this._userInstancedBuffersStorage.sizes[i];const r=this._userInstancedBuffersStorage.strides[i],n=(t+1)*r;for(;s<n;)s*=2;this._userInstancedBuffersStorage.data[i].length!=s&&(this._userInstancedBuffersStorage.data[i]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[i]=s,this._userInstancedBuffersStorage.vertexBuffers[i]&&(this._userInstancedBuffersStorage.vertexBuffers[i].dispose(),this._userInstancedBuffersStorage.vertexBuffers[i]=null));const o=this._userInstancedBuffersStorage.data[i];let l=0;if(e){const h=this.instancedBuffers[i];h.toArray?h.toArray(o,l):h.copyToArray?h.copyToArray(o,l):o[l]=h,l+=r}for(let h=0;h<t;h++){const u=a[h].instancedBuffers[i];u.toArray?u.toArray(o,l):u.copyToArray?u.copyToArray(o,l):o[l]=u,l+=r}this._userInstancedBuffersStorage.vertexBuffers[i]?this._userInstancedBuffersStorage.vertexBuffers[i].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[i]=new y(this.getEngine(),this._userInstancedBuffersStorage.data[i],i,!0,!1,r,!0),this._invalidateInstanceVertexArrayObject())}};z.prototype._invalidateInstanceVertexArrayObject=function(){if(!(!this._userInstancedBuffersStorage||this._userInstancedBuffersStorage.vertexArrayObjects===void 0)){for(const a in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[a]);this._userInstancedBuffersStorage.vertexArrayObjects={}}};z.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(const a in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[a]&&this._userInstancedBuffersStorage.vertexBuffers[a].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};class st extends Ct{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t){super(e,t),this.diffuse=new q(1,1,1),this.specular=new q(1,1,1),this.falloffType=st.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=st.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new be(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,r=!0){const n=e.toString();let o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+n),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const l=this.getScaledIntensity();this.transferToEffect(i,n),this.diffuse.scaleToRef(l,gt.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",gt.Color3[0],this.range,n),s&&(this.specular.scaleToRef(l,gt.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",gt.Color3[1],this.radius,n)),o=!0}if(this.transferTexturesToEffect(i,n),t.shadowsEnabled&&this.shadowEnabled&&r){const l=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();l&&(l.bindShadowLight(n,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){return this._shadowGenerators===null?null:this._shadowGenerators.get(e)??null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return m.Zero()}canAffectMesh(e){return e?!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let s=i.next();s.done!==!0;s=i.next())s.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(const i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=st.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=_e.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=_e.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(t=>{e.excludedMeshesIds.push(t.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(t=>{e.includedOnlyMeshesIds.push(t.id)})),_e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=Ct.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=st.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=_e.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(s.falloffType=e.falloffType),e.lightmapMode!==void 0&&(s.lightmapMode=e.lightmapMode),e.animations){for(let r=0;r<e.animations.length;r++){const n=e.animations[r],o=Si("BABYLON.Animation");o&&s.animations.push(o.Parse(n))}Ct.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&s.setEnabled(e.isEnabled),s}_hookArrayForExcluded(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);for(const n of s)n._resyncLightSource(this);return r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);for(const o of n)o._resyncLightSource(this);return n};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._resyncMeshes(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._resyncMeshes(),n},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===st.INTENSITYMODE_AUTOMATIC&&(t===st.LIGHTTYPEID_DIRECTIONALLIGHT?i=st.INTENSITYMODE_ILLUMINANCE:i=st.INTENSITYMODE_LUMINOUSINTENSITY),t){case st.LIGHTTYPEID_POINTLIGHT:case st.LIGHTTYPEID_SPOTLIGHT:switch(i){case st.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case st.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case st.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case st.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case st.INTENSITYMODE_ILLUMINANCE:e=1;break;case st.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case st.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}st.FALLOFF_DEFAULT=Nt.FALLOFF_DEFAULT;st.FALLOFF_PHYSICAL=Nt.FALLOFF_PHYSICAL;st.FALLOFF_GLTF=Nt.FALLOFF_GLTF;st.FALLOFF_STANDARD=Nt.FALLOFF_STANDARD;st.LIGHTMAP_DEFAULT=Nt.LIGHTMAP_DEFAULT;st.LIGHTMAP_SPECULAR=Nt.LIGHTMAP_SPECULAR;st.LIGHTMAP_SHADOWSONLY=Nt.LIGHTMAP_SHADOWSONLY;st.INTENSITYMODE_AUTOMATIC=Nt.INTENSITYMODE_AUTOMATIC;st.INTENSITYMODE_LUMINOUSPOWER=Nt.INTENSITYMODE_LUMINOUSPOWER;st.INTENSITYMODE_LUMINOUSINTENSITY=Nt.INTENSITYMODE_LUMINOUSINTENSITY;st.INTENSITYMODE_ILLUMINANCE=Nt.INTENSITYMODE_ILLUMINANCE;st.INTENSITYMODE_LUMINANCE=Nt.INTENSITYMODE_LUMINANCE;st.LIGHTTYPEID_POINTLIGHT=Nt.LIGHTTYPEID_POINTLIGHT;st.LIGHTTYPEID_DIRECTIONALLIGHT=Nt.LIGHTTYPEID_DIRECTIONALLIGHT;st.LIGHTTYPEID_SPOTLIGHT=Nt.LIGHTTYPEID_SPOTLIGHT;st.LIGHTTYPEID_HEMISPHERICLIGHT=Nt.LIGHTTYPEID_HEMISPHERICLIGHT;E([li()],st.prototype,"diffuse",void 0);E([li()],st.prototype,"specular",void 0);E([I()],st.prototype,"falloffType",void 0);E([I()],st.prototype,"intensity",void 0);E([I()],st.prototype,"range",null);E([I()],st.prototype,"intensityMode",null);E([I()],st.prototype,"radius",null);E([I()],st.prototype,"_renderPriority",void 0);E([te("_reorderLightsInScene")],st.prototype,"renderPriority",void 0);E([I("shadowEnabled")],st.prototype,"_shadowEnabled",void 0);E([I("excludeWithLayerMask")],st.prototype,"_excludeWithLayerMask",void 0);E([I("includeOnlyWithLayerMask")],st.prototype,"_includeOnlyWithLayerMask",void 0);E([I("lightmapMode")],st.prototype,"_lightmapMode",void 0);class gb extends wi{}class xb{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach(e=>{e.dispose()}),this.rootNodes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0}}class Df extends wi{constructor(e){super(),this._wasAddedToScene=!1,e=e||Ae.LastCreatedScene,e&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(const t of this.geometries)t._rebuild();for(const t of this.meshes)t._rebuild();for(const t of this.particleSystems)t.rebuild();for(const t of this.textures)t._rebuild()}))}_topologicalSort(e){const t=new Map;for(const o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const o of e){const l=o.uniqueId,h=i.dependsOn.get(l);if(o instanceof ym){const u=o.sourceMesh;t.has(u.uniqueId)&&(h.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(l))}const c=i.dependedBy.get(l);for(const u of o.getDescendants()){const d=u.uniqueId;t.has(d)&&(c.add(d),i.dependsOn.get(d).add(l))}}const s=[],r=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(r.push(o),t.delete(l))}const n=r;for(;n.length>0;){const o=n.shift();s.push(o);const l=i.dependedBy.get(o.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(o.uniqueId),c.size===0&&t.get(h)&&(n.push(t.get(h)),t.delete(h))}}return t.size>0&&(O.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>O.Error(o.name))),s}_addNodeAndDescendantsToList(e,t,i,s){if(!(!i||s&&!s(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof ut&&this.meshes.indexOf(e)!==-1||e instanceof Ke&&this.transformNodes.indexOf(e)!==-1||e instanceof st&&this.lights.indexOf(e)!==-1||e instanceof ve&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return O.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return O.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return O.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return O.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||X.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new xb,o=[],l=[],h={doNotInstantiate:!0,...i},c=(p,g)=>{if(s[p.uniqueId]=g.uniqueId,r[g.uniqueId]=g,e&&(g.name=e(p.name)),g instanceof z){const x=g;if(x.morphTargetManager){const T=p.morphTargetManager;x.morphTargetManager=T.clone();for(let S=0;S<T.numTargets;S++){const C=T.getTarget(S),v=x.morphTargetManager.getTarget(S);s[C.uniqueId]=v.uniqueId,r[v.uniqueId]=v}}}},u=[],d=new Set;for(const p of this.transformNodes)p.parent===null&&this._addNodeAndDescendantsToList(u,d,p,h.predicate);for(const p of this.meshes)p.parent===null&&this._addNodeAndDescendantsToList(u,d,p,h.predicate);const f=this._topologicalSort(u),_=(p,g)=>{if(c(p,g),p.parent){const x=s[p.parent.uniqueId],T=r[x];T?g.parent=T:g.parent=p.parent}if(g.position&&p.position&&g.position.copyFrom(p.position),g.rotationQuaternion&&p.rotationQuaternion&&g.rotationQuaternion.copyFrom(p.rotationQuaternion),g.rotation&&p.rotation&&g.rotation.copyFrom(p.rotation),g.scaling&&p.scaling&&g.scaling.copyFrom(p.scaling),g.material){const x=g;if(x.material)if(t){const T=p.material;if(l.indexOf(T)===-1){let S=T.clone(e?e(T.name):"Clone of "+T.name);if(l.push(T),s[T.uniqueId]=S.uniqueId,r[S.uniqueId]=S,T.getClassName()==="MultiMaterial"){const C=T;for(const v of C.subMaterials)v&&(S=v.clone(e?e(v.name):"Clone of "+v.name),l.push(v),s[v.uniqueId]=S.uniqueId,r[S.uniqueId]=S);C.subMaterials=C.subMaterials.map(v=>v&&r[s[v.uniqueId]])}}x.getClassName()!=="InstancedMesh"&&(x.material=r[s[T.uniqueId]])}else x.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(x.material)===-1&&this.scene.addMultiMaterial(x.material):this.scene.materials.indexOf(x.material)===-1&&this.scene.addMaterial(x.material)}g.parent===null&&n.rootNodes.push(g)};return f.forEach(p=>{if(p.getClassName()==="InstancedMesh"){const g=p,x=g.sourceMesh,T=s[x.uniqueId],C=(typeof T=="number"?r[T]:x).createInstance(g.name);_(g,C)}else{let g=!0;p.getClassName()==="TransformNode"||p.getClassName()==="Node"||p.skeleton||!p.getTotalVertices||p.getTotalVertices()===0?g=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?g=!h.doNotInstantiate(p):g=!h.doNotInstantiate);const x=g?p.createInstance(`instance of ${p.name}`):p.clone(`Clone of ${p.name}`,null,!0);if(!x)throw new Error(`Could not clone or instantiate node on Asset Container ${p.name}`);_(p,x)}}),this.skeletons.forEach(p=>{if(h.predicate&&!h.predicate(p))return;const g=p.clone(e?e(p.name):"Clone of "+p.name);for(const x of this.meshes)if(x.skeleton===p&&!x.isAnInstance){const T=r[s[x.uniqueId]];if(!T||T.isAnInstance||(T.skeleton=g,o.indexOf(g)!==-1))continue;o.push(g);for(const S of g.bones)S._linkedTransformNode&&(S._linkedTransformNode=r[s[S._linkedTransformNode.uniqueId]])}n.skeletons.push(g)}),this.animationGroups.forEach(p=>{if(h.predicate&&!h.predicate(p))return;const g=p.clone(e?e(p.name):"Clone of "+p.name,x=>r[s[x.uniqueId]]||x);n.animationGroups.push(g)}),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||X.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach(i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(i=>{e&&!e(i)||this.scene.addSkeleton(i)}),this.animations.forEach(i=>{e&&!e(i)||this.scene.addAnimation(i)}),this.animationGroups.forEach(i=>{e&&!e(i)||this.scene.addAnimationGroup(i)}),this.multiMaterials.forEach(i=>{e&&!e(i)||this.scene.addMultiMaterial(i)}),this.materials.forEach(i=>{e&&!e(i)||this.scene.addMaterial(i)}),this.morphTargetManagers.forEach(i=>{e&&!e(i)||this.scene.addMorphTargetManager(i)}),this.geometries.forEach(i=>{e&&!e(i)||this.scene.addGeometry(i)}),this.transformNodes.forEach(i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(i=>{e&&!e(i)||this.scene.addActionManager(i)}),this.textures.forEach(i=>{e&&!e(i)||this.scene.addTexture(i)}),this.reflectionProbes.forEach(i=>{e&&!e(i)||this.scene.addReflectionProbe(i)});for(const i of t)i.parent&&this.scene.getNodes().indexOf(i.parent)===-1&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){this._isValidHierarchy()||X.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{e&&!e(t)||this.scene.removeCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.removeLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.removeActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)})}dispose(){this.cameras.slice(0).forEach(e=>{e.dispose()}),this.cameras.length=0,this.lights.slice(0).forEach(e=>{e.dispose()}),this.lights.length=0,this.meshes.slice(0).forEach(e=>{e.dispose()}),this.meshes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach(e=>{e.dispose()}),this.multiMaterials.length=0,this.materials.slice(0).forEach(e=>{e.dispose()}),this.materials.length=0,this.geometries.slice(0).forEach(e=>{e.dispose()}),this.geometries.length=0,this.transformNodes.slice(0).forEach(e=>{e.dispose()}),this.transformNodes.length=0,this.actionManagers.slice(0).forEach(e=>{e.dispose()}),this.actionManagers.length=0,this.textures.slice(0).forEach(e=>{e.dispose()}),this.textures.length=0,this.reflectionProbes.slice(0).forEach(e=>{e.dispose()}),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach(e=>{e.dispose()}),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(const s of e){let r=!0;if(i){for(const n of i)if(s===n){r=!1;break}}r&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new gb);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new z("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Ae.LastCreatedScene,t,i=null){if(!e)return O.Error("No scene available to merge animations to"),[];const s=i||(o=>{let l=null;const h=o.animations.length?o.animations[0].targetProperty:"",c=o.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(o=>{const l=s(o);if(l!==null){for(const h of o.animations){const c=l.animations.filter(u=>u.targetProperty===h.targetProperty);for(const u of c){const d=l.animations.indexOf(u,0);d>-1&&l.animations.splice(d,1)}}l.animations=l.animations.concat(o.animations)}});const n=[];return this.animationGroups.slice().forEach(o=>{n.push(o.clone(o.name,s)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=s(o.target);l&&(e.beginAnimation(l,o.fromFrame,o.toFrame,o.loopAnimation,o.speedRatio,o.onAnimationEnd?o.onAnimationEnd:void 0,void 0,!0,void 0,o.onAnimationLoop?o.onAnimationLoop:void 0),e.stopAnimation(o.target))}),n}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.lights.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.cameras.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const s=t.pop();if(s instanceof z?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof Ke?this.transformNodes.push(s):s instanceof st?this.lights.push(s):s instanceof ve&&this.cameras.push(s),s instanceof ut){if(s.material&&this.materials.indexOf(s.material)===-1){this.materials.push(s.material);for(const r of s.material.getActiveTextures())this.textures.indexOf(r)===-1&&this.textures.push(r)}s.skeleton&&this.skeletons.indexOf(s.skeleton)===-1&&this.skeletons.push(s.skeleton),s.morphTargetManager&&this.morphTargetManagers.indexOf(s.morphTargetManager)===-1&&this.morphTargetManagers.push(s.morphTargetManager)}for(const r of s.getChildren())i.has(r)||t.push(r);i.add(s)}this.populateRootNodes()}}H.AudioEngineFactory=(a,e,t)=>new Tb(a,e,t);class Tb{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new G,this.onAudioLockedObservable=new G,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!ls())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)==null?void 0:e.state)==="running"){this._hideMuteButton(),this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this));return}this._tryToRun?(t=this._audioContext)==null||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(e=this._audioContext)!=null&&e.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,O.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)}).catch(()=>{this._tryToRun=!1,this.unlocked=!1}))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+");  background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Tn{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((e=H.audioEngine)!=null&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:H.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+t}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,r){var n;if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new G,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=m.Zero(),this._localDirection=new m(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||Ae.LastCreatedScene,!!i)if(this._scene=i,Tn._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(o,l,h,c,u)=>l<h?o*(1-l/h):0,r&&(this.autoplay=r.autoplay||!1,this._loop=r.loop||!1,r.volume!==void 0&&(this._volume=r.volume),this._spatialSound=r.spatialSound??!1,this.maxDistance=r.maxDistance??100,this.useCustomAttenuation=r.useCustomAttenuation??!1,this.rolloffFactor=r.rolloffFactor||1,this.refDistance=r.refDistance||1,this.distanceModel=r.distanceModel||"linear",this._playbackRate=r.playbackRate||1,this._streaming=r.streaming??!1,this._length=r.length,this._offset=r.offset),(n=H.audioEngine)!=null&&n.canUseWebAudio&&H.audioEngine.audioContext){this._soundGain=H.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let o=!0;if(t)try{typeof t=="string"?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let l=[],h=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=H.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=H.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(h=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":l.push(t);case"Array":l.length===0&&(l=t);for(let c=0;c<l.length;c++){const u=l[c];if(h=r&&r.skipCodecCheck||u.indexOf(".mp3",u.length-4)!==-1&&H.audioEngine.isMP3supported||u.indexOf(".ogg",u.length-4)!==-1&&H.audioEngine.isOGGsupported||u.indexOf(".wav",u.length-4)!==-1||u.indexOf(".m4a",u.length-4)!==-1||u.indexOf(".mp4",u.length-4)!==-1||u.indexOf("blob:")!==-1,h){this._streaming?(this._htmlAudioElement=new Audio(u),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,X.SetCorsBehavior(u,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(u,d=>{this._soundLoaded(d)},void 0,!0,!0,d=>{d&&O.Error("XHR "+d.status+" error on: "+u+"."),O.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:o=!1;break}o?h||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):O.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{O.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),H.audioEngine&&!H.audioEngine.WarnedWebAudioUnsupported&&(O.Error("Web Audio is not supported by your browser."),H.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(e=H.audioEngine)!=null&&e.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(t=H.audioEngine)!=null&&t.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(t=H.audioEngine)!=null&&t.audioContext&&H.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{O.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;(t=H.audioEngine)!=null&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),this._offset!==void 0&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),this._length!==void 0&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(this._offset|0)+this._length))))}_createSpatialParameters(){var e;(e=H.audioEngine)!=null&&e.canUseWebAudio&&H.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??H.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,(e=this._soundPanner)==null||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(e=H.audioEngine)!=null&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t<e){O.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e){O.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle){O.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=e,(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){var t;e.equals(this._position)||(this._position.copyFrom(e),(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){var t;this._localDirection=e,(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;const e=this._connectedTransformNode.getWorldMatrix(),t=m.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){var e;if((e=H.audioEngine)!=null&&e.canUseWebAudio&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){const t=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){var s,r,n,o;if(this._isReadyToPlay&&this._scene.audioEnabled&&((s=H.audioEngine)!=null&&s.audioContext))try{this._clearTimeoutsAndObservers();let l=e?((r=H.audioEngine)==null?void 0:r.audioContext.currentTime)+e:(n=H.audioEngine)==null?void 0:n.audioContext.currentTime;if((!this._soundSource||!this._streamingSource)&&this._spatialSound&&this._soundPanner&&(!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=H.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const h=()=>{var c,u;if((c=H.audioEngine)!=null&&c.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,_;(f=H.audioEngine)==null||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(_=H.audioEngine)==null?void 0:_.onAudioUnlockedObservable.addOnce(()=>{h()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=H.audioEngine)==null?void 0:u.onAudioUnlockedObservable.addOnce(()=>{h()}))};h()}}else{const h=()=>{var c,u,d;if((c=H.audioEngine)!=null&&c.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const f=this._soundSource;f.onended=()=>{f.disconnect()}}if(this._soundSource=(u=H.audioEngine)==null?void 0:u.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,t!==void 0&&(this._soundSource.loopStart=t),i!==void 0&&(this._soundSource.loopEnd=(t|0)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},l=e?((d=H.audioEngine)==null?void 0:d.audioContext.currentTime)+e:H.audioEngine.audioContext.currentTime;const f=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(l,f,this.loop?void 0:i)}}};((o=H.audioEngine)==null?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var c;((c=H.audioEngine)==null?void 0:c.audioContext.state)==="suspended"?(H.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=H.audioEngine.onAudioUnlockedObservable.addOnce(()=>{h()}))):h()},500):h()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){O.Error("Error while trying to play audio: "+this.name+", "+l.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((t=H.audioEngine)!=null&&t.audioContext&&this._soundSource){const i=e?H.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(i)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(e=H.audioEngine)!=null&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=H.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(i=H.audioEngine)!=null&&i.canUseWebAudio&&this._soundGain&&(t&&H.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(H.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,H.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,H.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=t=>this._onRegisterAfterWorldMatrixUpdate(t),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){var t;if(!e.getBoundingInfo)this.setPosition(e.absolutePosition);else{const s=e.getBoundingInfo();this.setPosition(s.boundingSphere.centerWorld)}(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Tn(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;e.url?n=i+e.url:n=i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let l;if(!s)l=new Tn(r,n,t,()=>{t.removePendingData(l)},o),t.addPendingData(l);else{const h=()=>{s._isReadyToPlay?(l._audioBuffer=s.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(h,300)};l=new Tn(r,new ArrayBuffer(0),t,null,o),h()}if(e.position){const h=m.FromArray(e.position);l.setPosition(h)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const h=m.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(h)}if(e.connectedMeshId){const h=t.getMeshById(e.connectedMeshId);h&&l.attachToMesh(h)}return e.metadata&&(l.metadata=e.metadata),l}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&((e=H.audioEngine)==null||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Tn._SceneComponentInitialization=a=>{throw Ge("AudioSceneComponent")};class Eb{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||Ae.LastCreatedScene,e&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(e=H.audioEngine)!=null&&e.canUseWebAudio&&H.audioEngine.audioContext&&(this._outputAudioNode=H.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(H.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(H.audioEngine&&H.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId!==void 0&&(e.soundTrackId===-1?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)}setVolume(e){var t;(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if((e=H.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){var e;if((e=H.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()}connectToAnalyser(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(t=H.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,H.audioEngine.masterGain))}}wi.AddParser(he.NAME_AUDIO,(a,e,t,i)=>{var n;let s=[],r;if(t.sounds=t.sounds||[],a.sounds!==void 0&&a.sounds!==null)for(let o=0,l=a.sounds.length;o<l;o++){const h=a.sounds[o];(n=H.audioEngine)!=null&&n.canUseWebAudio?(h.url||(h.url=h.name),s[h.url]?t.sounds.push(Tn.Parse(h,e,i,s[h.url])):(r=Tn.Parse(h,e,i),s[h.url]=r,t.sounds.push(r))):t.sounds.push(new Tn(h.name,null,e))}s=[]});Object.defineProperty(Ee.prototype,"mainSoundTrack",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),this._mainSoundTrack||(this._mainSoundTrack=new Eb(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0});Ee.prototype.getSoundByName=function(a){let e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)if(this.mainSoundTrack.soundCollection[e].name===a)return this.mainSoundTrack.soundCollection[e];if(this.soundTracks){for(let t=0;t<this.soundTracks.length;t++)for(e=0;e<this.soundTracks[t].soundCollection.length;e++)if(this.soundTracks[t].soundCollection[e].name===a)return this.soundTracks[t].soundCollection[e]}return null};Object.defineProperty(Ee.prototype,"audioEnabled",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),a.audioEnabled},set:function(a){let e=this._getComponent(he.NAME_AUDIO);e||(e=new lr(this),this._addComponent(e)),a?e.enableAudio():e.disableAudio()},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"headphone",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),a.headphone},set:function(a){let e=this._getComponent(he.NAME_AUDIO);e||(e=new lr(this),this._addComponent(e)),a?e.switchAudioModeForHeadphones():e.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"audioListenerPositionProvider",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),a.audioListenerPositionProvider},set:function(a){let e=this._getComponent(he.NAME_AUDIO);if(e||(e=new lr(this),this._addComponent(e)),a&&typeof a!="function")throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");e.audioListenerPositionProvider=a},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"audioListenerRotationProvider",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),a.audioListenerRotationProvider},set:function(a){let e=this._getComponent(he.NAME_AUDIO);if(e||(e=new lr(this),this._addComponent(e)),a&&typeof a!="function")throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");e.audioListenerRotationProvider=a},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"audioPositioningRefreshRate",{get:function(){let a=this._getComponent(he.NAME_AUDIO);return a||(a=new lr(this),this._addComponent(a)),a.audioPositioningRefreshRate},set:function(a){let e=this._getComponent(he.NAME_AUDIO);e||(e=new lr(this),this._addComponent(e)),e.audioPositioningRefreshRate=a},enumerable:!0,configurable:!0});class lr{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){this.name=he.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new m,this._cachedCameraPosition=new m,this._lastCheck=0,this._invertMatrixTemp=new D,this._cameraDirectionTemp=new m,e=e||Ae.LastCreatedScene,e&&(this.scene=e,e.soundTracks=[],e.sounds=[])}register(){this.scene._afterRenderStage.registerStep(he.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(e){if(e.sounds=[],this.scene.soundTracks)for(let t=0;t<this.scene.soundTracks.length;t++){const i=this.scene.soundTracks[t];for(let s=0;s<i.soundCollection.length;s++)e.sounds.push(i.soundCollection[s].serialize())}}addFromContainer(e){e.sounds&&e.sounds.forEach(t=>{t.play(),t.autoplay=!0,this.scene.mainSoundTrack.addSound(t)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(i=>{i.stop(),i.autoplay=!1,this.scene.mainSoundTrack.removeSound(i),t&&i.dispose()})}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()}disableAudio(){const e=this.scene;this._audioEnabled=!1,H.audioEngine&&H.audioEngine.audioContext&&H.audioEngine.audioContext.suspend();let t;for(t=0;t<e.mainSoundTrack.soundCollection.length;t++)e.mainSoundTrack.soundCollection[t].pause();if(e.soundTracks)for(t=0;t<e.soundTracks.length;t++)for(let i=0;i<e.soundTracks[t].soundCollection.length;i++)e.soundTracks[t].soundCollection[i].pause()}enableAudio(){const e=this.scene;this._audioEnabled=!0,H.audioEngine&&H.audioEngine.audioContext&&H.audioEngine.audioContext.resume();let t;for(t=0;t<e.mainSoundTrack.soundCollection.length;t++)e.mainSoundTrack.soundCollection[t].isPaused&&e.mainSoundTrack.soundCollection[t].play();if(e.soundTracks)for(t=0;t<e.soundTracks.length;t++)for(let i=0;i<e.soundTracks[t].soundCollection.length;i++)e.soundTracks[t].soundCollection[i].isPaused&&e.soundTracks[t].soundCollection[i].play()}switchAudioModeForHeadphones(){const e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){const e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()}_afterRender(){const e=Zi.Now;if(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=e;const t=this.scene;if(!this._audioEnabled||!t._mainSoundTrack||!t.soundTracks||t._mainSoundTrack.soundCollection.length===0&&t.soundTracks.length===1)return;const i=H.audioEngine;if(i&&i.audioContext){let s=t.activeCamera;if(t.activeCameras&&t.activeCameras.length>0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const n=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(n.x||0,n.y||0,n.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const n=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(n.x||0,n.y||0,n.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),m.TransformNormalToRef(lr._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),!isNaN(this._cameraDirectionTemp.x)&&!isNaN(this._cameraDirectionTemp.y)&&!isNaN(this._cameraDirectionTemp.z)&&(this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0)))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);let r;for(r=0;r<t.mainSoundTrack.soundCollection.length;r++){const n=t.mainSoundTrack.soundCollection[r];n.useCustomAttenuation&&n.updateDistanceFromListener()}if(t.soundTracks)for(r=0;r<t.soundTracks.length;r++)for(let n=0;n<t.soundTracks[r].soundCollection.length;n++){const o=t.soundTracks[r].soundCollection[n];o.useCustomAttenuation&&o.updateDistanceFromListener()}}}}lr._CameraDirection=new m(0,0,-1);Tn._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_AUDIO);e||(e=new lr(a),a._addComponent(e))};class Sb{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const n of i)s+=n;const r=s>0?1/s:0;for(let n=0;n<this._weights.length;n++)this._weights[n]*=r;this._sounds=t;for(const n of this._sounds)n.onEndedObservable.add(()=>{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e){O.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e;for(const t of this._sounds)t.directionalConeInnerAngle=e}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle){O.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=e;for(const t of this._sounds)t.directionalConeOuterAngle=e}}get volume(){return this._volume}set volume(e){if(e!==this._volume)for(const t of this._sounds)t.setVolume(e)}_onended(){this._currentIndex!==void 0&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPaused=!0,this._currentIndex!==void 0&&this._sounds[this._currentIndex].pause()}stop(){this.isPlaying=!1,this._currentIndex!==void 0&&this._sounds[this._currentIndex].stop()}play(e){if(!this.isPaused){this.stop();const i=Math.random();let s=0;for(let r=0;r<this._weights.length;r++)if(s+=this._weights[r],i<=s){this._currentIndex=r;break}}const t=this._sounds[this._currentIndex];t.isReady()?t.play(0,this.isPaused?void 0:e):t.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}class Cc{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,e=e||Ae.LastCreatedScene,e&&(this._scene=e,this.animationParameters=new we(0,0,0,30))}_markSubMeshesAsAttributesDirty(){for(const e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;const i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){const e=new Cc(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,s=30){this.animationParameters=new we(e,t,i,s)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){_e.Clone(()=>e,this)}serialize(){return _e.Serialize(this)}parse(e,t,i){_e.Parse(()=>this,e,t,i)}}E([ht(),te("_markSubMeshesAsAttributesDirty")],Cc.prototype,"texture",void 0);E([I(),te("_markSubMeshesAsAttributesDirty")],Cc.prototype,"isEnabled",void 0);E([I()],Cc.prototype,"animationParameters",void 0);E([I()],Cc.prototype,"time",void 0);class Ao{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Dr.Zero(),this._cachedBaseSize=Dr.Zero(),this._initialSamplingMode=2,this._texture=Ao._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Et extends Ao{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=en()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=Et.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new G,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Et._IsScene(e)?this._scene=e:this._engine=e:this._scene=Ae.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}checkTransformsAreIdentical(e){return e!==null}getTextureMatrix(){return D.IdentityReadOnly}getReflectionTextureMatrix(){return D.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!r,t),h=o.getLoadedTexturesCache();for(let c=0;c<h.length;c++){const u=h[c];if((r===void 0||l===u._useSRGBBuffer)&&(s===void 0||s===u.invertY)&&u.url===e&&u.generateMipMaps===!t&&(!i||i===u.samplingMode)&&(n===void 0||n===u.isCube))return u.incrementReferences(),u}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&this._texture.type!==void 0?this._texture.type:0}get textureFormat(){return this._texture&&this._texture.format!==void 0?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,s=!0,r=!1,n=0,o=0,l=Number.MAX_VALUE,h=Number.MAX_VALUE){if(!this._texture)return null;const c=this._getEngine();if(!c)return null;const u=this.getSize();let d=u.width,f=u.height;t!==0&&(d=d/Math.pow(2,t),f=f/Math.pow(2,t),d=Math.round(d),f=Math.round(f)),l=Math.min(d,l),h=Math.min(f,h);try{return this._texture.isCube?c._readTexturePixels(this._texture,l,h,e,t,i,s,r,n,o):c._readTexturePixels(this._texture,l,h,-1,t,i,s,r,n,o)}catch{return null}}_readPixelsSync(e=0,t=0,i=null,s=!0,r=!1){if(!this._texture)return null;const n=this.getSize();let o=n.width,l=n.height;const h=this._getEngine();if(!h)return null;t!=0&&(o=o/Math.pow(2,t),l=l/Math.pow(2,t),o=Math.round(o),l=Math.round(l));try{return this._texture.isCube?h._readTexturePixelsSync(this._texture,o,l,e,t,i,s,r):h._readTexturePixelsSync(this._texture,o,l,-1,t,i,s,r)}catch{return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=_e.Serialize(this);return _e.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s<e.length;s++){const r=e[s];if(r.isReady())--i===0&&t();else{const n=r.onLoadObservable;n?n.addOnce(()=>{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Et.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;E([I()],Et.prototype,"uniqueId",void 0);E([I()],Et.prototype,"name",void 0);E([I()],Et.prototype,"metadata",void 0);E([I("hasAlpha")],Et.prototype,"_hasAlpha",void 0);E([I("getAlphaFromRGB")],Et.prototype,"_getAlphaFromRGB",void 0);E([I()],Et.prototype,"level",void 0);E([I("coordinatesIndex")],Et.prototype,"_coordinatesIndex",void 0);E([I()],Et.prototype,"optimizeUVAllocation",void 0);E([I("coordinatesMode")],Et.prototype,"_coordinatesMode",void 0);E([I()],Et.prototype,"wrapU",null);E([I()],Et.prototype,"wrapV",null);E([I()],Et.prototype,"wrapR",void 0);E([I()],Et.prototype,"anisotropicFilteringLevel",void 0);E([I()],Et.prototype,"isCube",null);E([I()],Et.prototype,"is3D",null);E([I()],Et.prototype,"is2DArray",null);E([I()],Et.prototype,"gammaSpace",null);E([I()],Et.prototype,"invertZ",void 0);E([I()],Et.prototype,"lodLevelInAlpha",void 0);E([I()],Et.prototype,"lodGenerationOffset",null);E([I()],Et.prototype,"lodGenerationScale",null);E([I()],Et.prototype,"linearSpecularLOD",null);E([ht()],Et.prototype,"irradianceTexture",null);E([I()],Et.prototype,"isRenderTarget",void 0);function WE(a,e,t=!1){const i=e.width,s=e.height;if(a instanceof Float32Array){let h=a.byteLength/a.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=a[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}a=c}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const o=n.createImageData(i,s);if(o.data.set(a),n.putImageData(o,0,0),t){const h=document.createElement("canvas");h.width=i,h.height=s;const c=h.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(r,0,0),h.toDataURL("image/png")):null}return r.toDataURL("image/png")}function Cb(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?WE(s,a.getSize(),i.invertY):null}async function vb(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?WE(s,a.getSize(),i.invertY):null}class k extends Et{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=k.TRILINEAR_SAMPLINGMODE,o={},l,h=5){throw Ge("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=k.TRILINEAR_SAMPLINGMODE,n=null,o=null,l=null,h=!1,c,u,d,f,_){super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new G,this._isBlocking=!0,this.name=e||"",this.url=e;let p,g=!1,x=null,T=!0;typeof i=="object"&&i!==null?(p=i.noMipmap??!1,s=i.invertY??!mt.UseOpenGLOrientationForUV,r=i.samplingMode??k.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,l=i.buffer??null,h=i.deleteBuffer??!1,c=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,g=i.useSRGBBuffer??!1,x=i.internalTexture??null,T=i.gammaSpace??T):p=!!i,this._gammaSpace=T,this._noMipmap=p,this._invertY=s===void 0?!mt.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=g,this._forcedExtension=_,c&&(this._format=c);const S=this.getScene(),C=this._getEngine();if(!C)return;C.onBeforeTextureInitObservable.notifyObservers(this);const v=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&S&&S.resetCachedMaterial()},b=(A,P)=>{this._loadingError=!0,this._errorObject={message:A,exception:P},o&&o(A,P),k.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!x){this._delayedOnLoad=v,this._delayedOnError=b;return}if(this._texture=x??this._getFromCache(this.url,p,r,this._invertY,g,this.isCube),this._texture)if(this._texture.isReady)wl.SetImmediate(()=>v());else{const A=this._texture.onLoadedObservable.add(v);this._texture.onErrorObservable.add(P=>{var L;b(P.message,P.exception),(L=this._texture)==null||L.onLoadedObservable.remove(A)})}else if(!S||!S.useDelayedTextureLoading){try{this._texture=C.createTexture(this.url,p,this._invertY,S,r,v,b,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,g)}catch(A){throw b("error loading",A),A}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=v,this._delayedOnError=b}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,r=>r.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?wl.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,m.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return e!==null&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=D.Zero(),this._rowGenerationMatrix=new D,this._t0=m.Zero(),this._t1=m.Zero(),this._t2=m.Zero()),D.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(D.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,U.Matrix[0]),D.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,U.Matrix[1]),D.ScalingToRef(this._cachedUScale,this._cachedVScale,0,U.Matrix[2]),D.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,U.Matrix[3]),U.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),D.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedTextureMatrix):this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===k.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=D.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=D.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case k.PLANAR_MODE:{D.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case k.PROJECTION_MODE:{D.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:D.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return _e.Clone(()=>new k(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i;const e=this.name;k.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(k._SerializeInternalTextureUniqueId);return t?((k.SerializeBuffers||k.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+TE(this._buffer):(k.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Cb(this):vb(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,k._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=((i=this._texture)==null?void 0:i.uniqueId)??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const h=Zc.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&h.updateSamplingMode&&h._samplingMode&&h._samplingMode!==e.samplingMode&&h.updateSamplingMode(e.samplingMode),h}if(e.isCube&&!e.isRenderTarget)return k._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const l=t.getEngine().getLoadedTexturesCache();for(const h of l)if(h.uniqueId===e.internalTextureUniqueId){r=h;break}}const n=l=>{var h;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c<e.animations.length;c++){const u=e.animations[c],d=Si("BABYLON.Animation");d&&l.animations.push(d.Parse(u))}s&&!r&&((h=l==null?void 0:l._texture)==null||h._setUniqueId(e.internalTextureUniqueId))};return _e.Parse(()=>{let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const h=k._CreateMirror(e.name,e.renderTargetSize,t,l);return h._waitingRenderList=e.renderList,h.mirrorPlane=Ks.FromArray(e.mirrorPlane),n(h),h}else if(e.isRenderTarget){let h=null;if(e.isCube){if(t.reflectionProbes)for(let c=0;c<t.reflectionProbes.length;c++){const u=t.reflectionProbes[c];if(u.name===e.name)return u.cubeTexture}}else h=k._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,l,e._creationFlags??0),h._waitingRenderList=e.renderList;return n(h),h}else if(e.isVideo){const h=k._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,l,e.invertY,e.samplingMode,e.settings||{});return n(h),h}else{let h;if(e.base64String&&!r)h=k.CreateFromBase64String(e.base64String,e.base64String,t,!l,e.invertY,e.samplingMode,()=>{n(h)},e._creationFlags??0,e._useSRGBBuffer??!1),h.name=e.name;else{let c;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?c=e.name:c=i+e.name,e.url&&(e.url.startsWith("data:")||k.UseSerializedUrlIfAny)&&(c=e.url);const u={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(h)},internalTexture:r};h=new k(c,t,u)}return h}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=k.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return new k("data:"+t,i,s,r,n,o,l,e,!1,h,void 0,void 0,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=k.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new k(e,i,r,n,o,l,h,t,s,c,void 0,void 0,u)}}k.SerializeBuffers=!0;k.ForceSerializeBuffers=!1;k.OnTextureLoadErrorObservable=new G;k._SerializeInternalTextureUniqueId=!1;k._CubeTextureParser=(a,e,t)=>{throw Ge("CubeTexture")};k._CreateMirror=(a,e,t,i)=>{throw Ge("MirrorTexture")};k._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw Ge("RenderTargetTexture")};k.NEAREST_SAMPLINGMODE=1;k.NEAREST_NEAREST_MIPLINEAR=8;k.BILINEAR_SAMPLINGMODE=2;k.LINEAR_LINEAR_MIPNEAREST=11;k.TRILINEAR_SAMPLINGMODE=3;k.LINEAR_LINEAR_MIPLINEAR=3;k.NEAREST_NEAREST_MIPNEAREST=4;k.NEAREST_LINEAR_MIPNEAREST=5;k.NEAREST_LINEAR_MIPLINEAR=6;k.NEAREST_LINEAR=7;k.NEAREST_NEAREST=1;k.LINEAR_NEAREST_MIPNEAREST=9;k.LINEAR_NEAREST_MIPLINEAR=10;k.LINEAR_LINEAR=2;k.LINEAR_NEAREST=12;k.EXPLICIT_MODE=0;k.SPHERICAL_MODE=1;k.PLANAR_MODE=2;k.CUBIC_MODE=3;k.PROJECTION_MODE=4;k.SKYBOX_MODE=5;k.INVCUBIC_MODE=6;k.EQUIRECTANGULAR_MODE=7;k.FIXED_EQUIRECTANGULAR_MODE=8;k.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;k.CLAMP_ADDRESSMODE=0;k.WRAP_ADDRESSMODE=1;k.MIRROR_ADDRESSMODE=2;k.UseSerializedUrlIfAny=!1;E([I()],k.prototype,"url",void 0);E([I()],k.prototype,"uOffset",void 0);E([I()],k.prototype,"vOffset",void 0);E([I()],k.prototype,"uScale",void 0);E([I()],k.prototype,"vScale",void 0);E([I()],k.prototype,"uAng",void 0);E([I()],k.prototype,"vAng",void 0);E([I()],k.prototype,"wAng",void 0);E([I()],k.prototype,"uRotationCenter",void 0);E([I()],k.prototype,"vRotationCenter",void 0);E([I()],k.prototype,"wRotationCenter",void 0);E([I()],k.prototype,"homogeneousRotationInUVTransform",void 0);E([I()],k.prototype,"isBlocking",null);V("BABYLON.Texture",k);_e._TextureParser=k.Parse;pe.prototype.updateRawTexture=function(a,e,t,i,s=null,r=0,n=!1){if(!a)return;const o=this._getRGBABufferInternalSizedFormat(r,t,n),l=this._getInternalFormat(t),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.type=r,a.invertY=i,a._compression=s),a.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],a.width,a.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,a.width,a.height,0,l,h,e),a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0};pe.prototype.createRawTexture=function(a,e,t,i,s,r,n,o=null,l=0,h=0,c=!1){const u=new Tt(this,et.Raw);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=n,u.invertY=r,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=a),this.updateRawTexture(u,a,i,r,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(n,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};pe.prototype.createRawCubeTexture=function(a,e,t,i,s,r,n,o=null){const l=this._gl,h=new Tt(this,et.CubeRaw);h.isCube=!0,h.format=t,h.type=i,this._doNotHandleContextLost||(h._bufferViewArray=a);const c=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===l.RGB&&(u=l.RGBA),c===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,n=1,O.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,n=1,O.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===l.FLOAT&&!this._caps.textureFloatRender?(s=!1,O.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,O.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const d=e,f=d;if(h.width=d,h.height=f,h.invertY=r,h._compression=o,!this.needPOTTextures||vu(h.width)&&vu(h.height)||(s=!1),a)this.updateRawCubeTexture(h,a,t,i,r,o);else{const g=this._getRGBABufferInternalSizedFormat(i),x=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let T=0;T<6;T++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+T,x,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+T,x,g,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),a&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=n,h.isReady=!0,h};pe.prototype.updateRawCubeTexture=function(a,e,t,i,s,r=null,n=0){a._bufferViewArray=e,a.format=t,a.type=i,a.invertY=s,a._compression=r;const o=this._gl,l=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;h===o.RGB&&(h=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0),this._unpackFlipY(s===void 0?!0:!!s),a.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let _=e[f];r?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,this.getCaps().s3tc[r],a.width,a.height,0,_):(u&&(_=HE(_,a.width,a.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,c,a.width,a.height,0,h,l,_))}(!this.needPOTTextures||vu(a.width)&&vu(a.height))&&a.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),a.isReady=!0};pe.prototype.createRawCubeTextureFromUrl=function(a,e,t,i,s,r,n,o,l=null,h=null,c=3,u=!1){const d=this._gl,f=this.createRawCubeTexture(null,t,i,s,!r,u,c,null);e==null||e.addPendingData(f),f.url=a,f.isReady=!1,this._internalTexturesCache.push(f);const _=(g,x)=>{e==null||e.removePendingData(f),h&&g&&h(g.status+" "+g.statusText,x)},p=g=>{const x=f.width,T=n(g);if(T){if(o){const S=this._getWebGLTextureType(s);let C=this._getInternalFormat(i);const v=this._getRGBABufferInternalSizedFormat(s);let b=!1;C===d.RGB&&(C=d.RGBA,b=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const A=o(T);for(let P=0;P<A.length;P++){const L=x>>P;for(let w=0;w<6;w++){let $=A[P][w];b&&($=HE($,L,L,s)),d.texImage2D(w,P,v,L,L,0,C,S,$)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,T,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(a,g=>{p(g)},void 0,e==null?void 0:e.offlineProvider,!0,_),f};function HE(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n<e;n++)for(let o=0;o<t;o++){const l=(o*e+n)*3,h=(o*e+n)*4;s[h+0]=a[l+0],s[h+1]=a[l+1],s[h+2]=a[l+2],s[h+3]=r}return s}function XE(a){return function(e,t,i,s,r,n,o,l,h=null,c=0){const u=a?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=a?et.Raw3D:et.Raw2DArray,f=new Tt(this,d);f.baseWidth=t,f.baseHeight=i,f.baseDepth=s,f.width=t,f.height=i,f.depth=s,f.format=r,f.type=c,f.generateMipMaps=n,f.samplingMode=l,a?f.is3D=!0:f.is2DArray=!0,this._doNotHandleContextLost||(f._bufferView=e),a?this.updateRawTexture3D(f,e,r,o,h,c):this.updateRawTexture2DArray(f,e,r,o,h,c),this._bindTextureDirectly(u,f,!0);const _=this._getSamplingParameters(l,n);return this._gl.texParameteri(u,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(u,this._gl.TEXTURE_MIN_FILTER,_.min),n&&this._gl.generateMipmap(u),this._bindTextureDirectly(u,null),this._internalTexturesCache.push(f),f}}pe.prototype.createRawTexture2DArray=XE(!1);pe.prototype.createRawTexture3D=XE(!0);function YE(a){return function(e,t,i,s,r=null,n=0){const o=a?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(n),h=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(n,i);this._bindTextureDirectly(o,e,!0),this._unpackFlipY(s===void 0?!0:!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),e.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[r],e.width,e.height,e.depth,0,t):this._gl.texImage3D(o,0,c,e.width,e.height,e.depth,0,h,l,t),e.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),e.isReady=!0}}pe.prototype.updateRawTexture2DArray=YE(!1);pe.prototype.updateRawTexture3D=YE(!0);class Fi extends k{constructor(e,t,i,s,r,n=!0,o=!1,l=3,h=0,c,u){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,c),this.format=s,this._engine&&(!this._engine._caps.textureFloatLinearFiltering&&h===1&&(l=1),!this._engine._caps.textureHalfFloatLinearFiltering&&h===2&&(l=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,l,null,h,c??0,u??!1),this.wrapU=k.CLAMP_ADDRESSMODE,this.wrapV=k.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new Fi(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Fi(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Fi(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,l=0,h=0,c=!1){return new Fi(e,t,i,4,s,r,n,o,l,h,c)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,l=0,h=0,c=!1){return new Fi(e,t,i,5,s,r,n,o,l,h,c)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,l=0,h=!1){return new Fi(e,t,i,5,s,r,n,o,l,1,h)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=k.TRILINEAR_SAMPLINGMODE,l=1){return new Fi(e,t,i,6,s,r,n,o,l)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=k.TRILINEAR_SAMPLINGMODE,l=1){return new Fi(e,t,i,6,s,r,n,o,l,1)}}class eo{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=D.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new G,this.bones=[],this._scene=i||Ae.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(const s in this._ranges)i&&(t+=", ",i=!1),t+=s;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new Nl(e,t,i);for(let s=0,r=this.bones.length;s<r;s++)this.bones[s].animations[0]&&this.bones[s].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,s=this.bones.length;i<s;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,i=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let s=!0;const r=this._getHighestAnimationFrame()+1,n={},o=e.bones;let l,h;for(h=0,l=o.length;h<l;h++)n[o[h].name]=o[h];this.bones.length!==o.length&&(O.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${o.length}`),s=!1);const c=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(h=0,l=this.bones.length;h<l;h++){const d=this.bones[h].name,f=n[d];f?s=s&&this.bones[h].copyAnimationRange(f,t,r,i,c):(O.Warn("copyAnimationRange: not same rig, missing source bone "+d),s=!1)}const u=e.getAnimationRange(t);return u&&(this._ranges[t]=new Nl(t,u.from+r,u.to+r)),s}returnToRest(){for(const e of this.bones)e._index!==-1&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){const s=this.bones[t].animations[0].getHighestFrame();e<s&&(e=s)}return e}beginAnimation(e,t,i,s){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,i,s):null}static MakeAnimationAdditive(e,t=0,i){const s=e.getAnimationRange(i);if(!s)return null;const r=e._scene.getAllAnimatablesByTarget(e);let n=null;for(let l=0;l<r.length;l++){const h=r[l];if(h.fromFrame===(s==null?void 0:s.from)&&h.toFrame===(s==null?void 0:s.to)){n=h;break}}const o=e.getAnimatables();for(let l=0;l<o.length;l++){const c=o[l].animations;if(c)for(let u=0;u<c.length;u++)K.MakeAnimationAdditive(c[u],t,i)}return n&&(n.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){const t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){const s=this.bones[i];s._childUpdateId++;const r=s.getParent();if(r?s.getLocalMatrix().multiplyToRef(r.getFinalMatrix(),s.getFinalMatrix()):t?s.getLocalMatrix().multiplyToRef(t,s.getFinalMatrix()):s.getFinalMatrix().copyFrom(s.getLocalMatrix()),s._index!==-1){const n=s._index===null?i:s._index;s.getAbsoluteInverseBindMatrix().multiplyToArray(s.getFinalMatrix(),e,n*16)}}this._identity.copyToArray(e,this.bones.length*16)}prepare(e=!1){if(!e){const t=this.getScene().getRenderId();if(this._currentRenderId===t)return;this._currentRenderId=t}if(this._numBonesWithLinkedTransformNode>0){for(const t of this.bones)if(t._linkedTransformNode){const i=t._linkedTransformNode;t.position=i.position,i.rotationQuaternion?t.rotationQuaternion=i.rotationQuaternion:t.rotation=i.rotation,t.scaling=i.scaling}}if(this.needInitialSkinMatrix)for(const t of this._meshesWithPoseMatrix){const i=t.getPoseMatrix();let s=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),s=!0),!!s){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const r of this.bones)r.getParent()||(r.getBindMatrix().multiplyToRef(i,U.Matrix[1]),r._updateAbsoluteBindMatrices(U.Matrix[1]));if(this.isUsingTextureForMatrices){const r=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==r)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=Fi.CreateRGBATexture(t._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(t._bonesTransformMatrices,i),this.isUsingTextureForMatrices&&t._transformMatrixTexture&&t._transformMatrixTexture.update(t._bonesTransformMatrices)}}else{if(!this._isDirty)return;(!this._transformMatrices||this._transformMatrices.length!==16*(this.bones.length+1))&&(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Fi.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){const i=new eo(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let s=0;s<this.bones.length;s++){const r=this.bones[s];let n=null;const o=r.getParent();if(o){const h=this.bones.indexOf(o);n=i.bones[h]}const l=new Ut(r.name,i,n,r.getBindMatrix().clone(),r.getRestMatrix().clone());l._index=r._index,r._linkedTransformNode&&l.linkTransformNode(r._linkedTransformNode),Cs.DeepCopy(r.animations,l.animations)}if(this._ranges){i._ranges={};for(const s in this._ranges){const r=this._ranges[s];r&&(i._ranges[s]=r.clone())}}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach(t=>{t.animations.forEach(i=>{i.enableBlending=!0,i.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t;const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i<this.bones.length;i++){const s=this.bones[i],r=s.getParent(),n={parentBoneIndex:r?this.bones.indexOf(r):-1,index:s.getIndex(),name:s.name,id:s.id,matrix:s.getBindMatrix().asArray(),rest:s.getRestMatrix().asArray(),linkedTransformNodeId:(t=s.getTransformNode())==null?void 0:t.id};e.bones.push(n),s.length&&(n.length=s.length),s.metadata&&(n.metadata=s.metadata),s.animations&&s.animations.length>0&&(n.animation=s.animations[0].serialize()),e.ranges=[];for(const o in this._ranges){const l=this._ranges[o];if(!l)continue;const h={};h.name=o,h.from=l.from,h.to=l.to,e.ranges.push(h)}}return e}static Parse(e,t){const i=new eo(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=m.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let s;for(s=0;s<e.bones.length;s++){const r=e.bones[s],n=e.bones[s].index;let o=null;r.parentBoneIndex>-1&&(o=i.bones[r.parentBoneIndex]);const l=r.rest?D.FromArray(r.rest):null,h=new Ut(r.name,i,o,D.FromArray(r.matrix),l,null,n);r.id!==void 0&&r.id!==null&&(h.id=r.id),r.length&&(h.length=r.length),r.metadata&&(h.metadata=r.metadata),r.animation&&h.animations.push(K.Parse(r.animation)),r.linkedTransformNodeId!==void 0&&r.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,h._waitingTransformNodeId=r.linkedTransformNodeId)}if(e.ranges)for(s=0;s<e.ranges.length;s++){const r=e.ranges[s];i.createAnimationRange(r.name,r.from,r.to)}return i}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;const s=this.bones[e];if(!s)return;s._index===void 0&&(s._index=e);const r=s.getParent();r&&this._sortBones(this.bones.indexOf(r),t,i),t.push(s)}setCurrentPoseAsRest(){this.bones.forEach(e=>{e.setCurrentPoseAsRest()})}}class bb{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=Zi.Now;let s=0;this._lastFrameTime!=null&&(s=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const r=i-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(r/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(s/1e3))})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??Zi.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)<rt:!1}_userIsZooming(){return this._attachedCamera?this._attachedCamera.inertialRadiusOffset!==0:!1}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&this._attachedCamera.inertialRadiusOffset!==0&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=Zi.Now)}_userIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}class Mo{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(i=>{if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const s=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=s*.05,this.upperRadiusTransitionRange=s*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Mo.EasingFunction.setEasingMode(Mo.EasingMode),this._radiusBounceTransition=K.CreateAnimation("radius",K.ANIMATIONTYPE_FLOAT,60,Mo.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=K.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Mo.EasingFunction=new Qv(.3);Mo.EasingMode=Us.EASINGMODE_EASEOUT;class rr{constructor(){this.onTargetFramingAnimationEndObservable=new G,this._mode=rr.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();rr.EasingFunction.setEasingMode(rr.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n<e.length;n++){const o=e[n].getHierarchyBoundingVectors(!0);m.CheckExtends(o.min,s,r),m.CheckExtends(o.max,s,r)}this.zoomOnBoundingInfo(s,r,t,i)}zoomOnBoundingInfo(e,t,i=!1,s=null){let r;if(!this._attachedCamera)return!1;const n=e.y,o=t.y,l=n+(o-n)*this._positionScale,h=t.subtract(e).scale(.5);if(i)r=new m(0,l,0);else{const d=e.add(h);r=new m(d.x,l,d.z)}this._vectorTransition||(this._vectorTransition=K.CreateAnimation("target",K.ANIMATIONTYPE_VECTOR3,60,rr.EasingFunction)),this._betaIsAnimating=!0;let c=K.TransitionTo("target",r,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);c&&this._animatables.push(c);let u=0;if(this._mode===rr.FitFrustumSidesMode){const d=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=h.length()+this._attachedCamera.minZ),u=d}else this._mode===rr.IgnoreBoundsSizeMode&&(u=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&this._attachedCamera.lowerRadiusLimit===null&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const d=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/d,this._attachedCamera.wheelPrecision=100/u}return this._radiusTransition||(this._radiusTransition=K.CreateAnimation("radius",K.ANIMATIONTYPE_FLOAT,60,rr.EasingFunction)),c=K.TransitionTo("radius",u,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),c&&this._animatables.push(c),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===rr.IgnoreBoundsSizeMode&&(s=s<i.lowerRadiusLimit?i.lowerRadiusLimit:s),i.upperRadiusLimit&&(s=s>i.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Zi.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=K.CreateAnimation("beta",K.ANIMATIONTYPE_FLOAT,60,rr.EasingFunction));const s=K.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});s&&this._animatables.push(s)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Zi.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}rr.EasingFunction=new Zv;rr.EasingMode=Us.EASINGMODE_EASEINOUT;rr.IgnoreBoundsSizeMode=0;rr.FitFrustumSidesMode=1;class tt{constructor(e,t,i=Number.MAX_VALUE,s=rt){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new tt(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=tt._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=tt._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n=0,o=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<s.x||this.origin.x>r.x)return!1}else if(l=1/this.direction.x,h=(s.x-this.origin.x)*l,c=(r.x-this.origin.x)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<s.y||this.origin.y>r.y)return!1}else if(l=1/this.direction.y,h=(s.y-this.origin.y)*l,c=(r.y-this.origin.y)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<s.z||this.origin.z>r.z)return!1}else if(l=1/this.direction.z,h=(s.z-this.origin.z)*l,c=(r.z-this.origin.z)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,l=o*o;if(n<=l)return!0;const h=i*this.direction.x+s*this.direction.y+r*this.direction.z;return h<0?!1:n-h*h<=l}intersectsTriangle(e,t,i){const s=tt._TmpVector3[0],r=tt._TmpVector3[1],n=tt._TmpVector3[2],o=tt._TmpVector3[3],l=tt._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),m.CrossToRef(this.direction,r,n);const h=m.Dot(s,n);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,o);const u=m.Dot(o,n)*c;if(u<-this.epsilon||u>1+this.epsilon)return null;m.CrossToRef(o,s,l);const d=m.Dot(this.direction,l)*c;if(d<-this.epsilon||u+d>1+this.epsilon)return null;const f=m.Dot(r,l)*c;return f>this.length?null:new rp(1-u-d,u,f)}intersectsPlane(e){let t;const i=m.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=m.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const i=(this.origin.y-t)/this.direction.y;return i>0?null:new m(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{const i=(this.origin.x-t)/this.direction.x;return i>0?null:new m(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{const i=(this.origin.z-t)/this.direction.z;return i>0?null:new m(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=U.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?tt.TransformToRef(this,o,this._tmpRay):this._tmpRay=tt.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;s<e.length;s++){const r=this.intersectsMesh(e[s],t);r.hit&&i.push(r)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2],l=U.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(tt._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,l);const h=m.Dot(r,r),c=m.Dot(r,o),u=m.Dot(o,o),d=m.Dot(r,l),f=m.Dot(o,l),_=h*u-c*c;let p,g=_,x,T=_;_<tt._Smallnum?(p=0,g=1,x=f,T=u):(p=c*f-u*d,x=h*f-c*d,p<0?(p=0,x=f,T=u):p>g&&(p=g,x=f+c,T=u)),x<0?(x=0,-d<0?p=0:-d>h?p=g:(p=-d,g=h)):x>T&&(x=T,-d+c<0?p=0:-d+c>h?p=g:(p=-d+c,g=h));const S=Math.abs(p)<tt._Smallnum?0:p/g,C=Math.abs(x)<tt._Smallnum?0:x/T,v=U.Vector3[4];o.scaleToRef(C,v);const b=U.Vector3[5];r.scaleToRef(S,b),b.addInPlace(l);const A=U.Vector3[6];return b.subtractToRef(v,A),C>0&&C<=this.length&&A.lengthSquared()<i*i?b.length():-1}update(e,t,i,s,r,n,o,l=!1){if(l){tt._RayDistant||(tt._RayDistant=tt.Zero()),tt._RayDistant.unprojectRayToRef(e,t,i,s,D.IdentityReadOnly,n,o);const h=U.Matrix[0];r.invertToRef(h),tt.TransformToRef(tt._RayDistant,h,this)}else this.unprojectRayToRef(e,t,i,s,r,n,o);return this}static Zero(){return new tt(m.Zero(),m.Zero())}static CreateNew(e,t,i,s,r,n,o){return tt.Zero().update(e,t,i,s,r,n,o)}static CreateNewFromTo(e,t,i=D.IdentityReadOnly){const s=new tt(new m(0,0,0),new m(0,0,0));return tt.CreateFromToToRef(e,t,s,i)}static CreateFromToToRef(e,t,i,s=D.IdentityReadOnly){i.origin.copyFrom(e);const r=t.subtractToRef(e,i.direction),n=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return i.length=n,i.direction.normalize(),tt.TransformToRef(i,s,i)}static Transform(e,t){const i=new tt(new m(0,0,0),new m(0,0,0));return tt.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){m.TransformCoordinatesToRef(e.origin,t,i.origin),m.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length,i.epsilon=e.epsilon;const s=i.direction,r=s.length();if(!(r===0||r===1)){const n=1/r;s.x*=n,s.y*=n,s.z*=n,i.length*=r}return i}unprojectRayToRef(e,t,i,s,r,n,o){const l=U.Matrix[0];r.multiplyToRef(n,l),l.multiplyToRef(o,l),l.invert();const h=Ae.LastCreatedEngine,c=U.Vector3[0];c.x=e/i*2-1,c.y=-(t/s*2-1),c.z=h!=null&&h.useReverseDepthBuffer?1:h!=null&&h.isNDCHalfZRange?0:-1;const u=U.Vector3[1].copyFromFloats(c.x,c.y,1-1e-8),d=U.Vector3[2],f=U.Vector3[3];m._UnprojectFromInvertedMatrixToRef(c,l,d),m._UnprojectFromInvertedMatrixToRef(u,l,f),this.origin.copyFrom(d),f.subtractToRef(d,this.direction),this.direction.normalize()}}tt._TmpVector3=Xi.BuildArray(6,m.Zero);tt._RayDistant=tt.Zero();tt._Smallnum=1e-8;tt._Rayl=1e9;Ee.prototype.createPickingRay=function(a,e,t,i,s=!1){const r=tt.Zero();return this.createPickingRayToRef(a,e,t,r,i,s),r};Ee.prototype.createPickingRayToRef=function(a,e,t,i,s,r=!1,n=!1){const o=this.getEngine();if(!s&&!(s=this.activeCamera))return this;const l=s.viewport,h=o.getRenderHeight(),{x:c,y:u,width:d,height:f}=l.toGlobal(o.getRenderWidth(),h),_=1/o.getHardwareScalingLevel();return a=a*_-c,e=e*_-(h-u-f),i.update(a,e,d,f,t||D.IdentityReadOnly,r?D.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),n),this};Ee.prototype.createPickingRayInCameraSpace=function(a,e,t){const i=tt.Zero();return this.createPickingRayInCameraSpaceToRef(a,e,i,t),i};Ee.prototype.createPickingRayInCameraSpaceToRef=function(a,e,t,i){if(!es)return this;const s=this.getEngine();if(!i&&!(i=this.activeCamera))throw new Error("Active camera not set");const r=i.viewport,n=s.getRenderHeight(),{x:o,y:l,width:h,height:c}=r.toGlobal(s.getRenderWidth(),n),u=D.Identity(),d=1/s.getHardwareScalingLevel();return a=a*d-o,e=e*d-(n-l-c),t.update(a,e,h,c,u,u,i.getProjectionMatrix()),this};Ee.prototype._internalPickForMesh=function(a,e,t,i,s,r,n,o){const l=e(i,t.enableDistantPicking),h=t.intersects(l,s,n,r,i,o);return!h||!h.hit||!s&&a!=null&&h.distance>=a.distance?null:h};Ee.prototype._internalPick=function(a,e,t,i,s){let r=null;const n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l<this.meshes.length;l++){const h=this.meshes[l];if(e){if(!e(h))continue}else if(!h.isEnabled()||!h.isVisible||!h.isPickable)continue;const c=n&&h.isWorldMatrixCameraDependent(),u=h.computeWorldMatrix(c,o);if(h.hasThinInstances&&h.thinInstanceEnablePicking){const d=this._internalPickForMesh(r,a,h,u,!0,!0,s);if(d){if(i)return d;const f=U.Matrix[1],_=h.thinInstanceGetWorldMatrices();for(let p=0;p<_.length;p++){_[p].multiplyToRef(u,f);const x=this._internalPickForMesh(r,a,h,f,t,i,s,!0);if(x&&(r=x,r.thinInstanceIndex=p,t))return r}}}else{const d=this._internalPickForMesh(r,a,h,u,t,i,s);if(d&&(r=d,t))return r}}return r||new es};Ee.prototype._internalMultiPick=function(a,e,t){if(!es)return null;const i=[],s=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n<this.meshes.length;n++){const o=this.meshes[n];if(e){if(!e(o))continue}else if(!o.isEnabled()||!o.isVisible||!o.isPickable)continue;const l=s&&o.isWorldMatrixCameraDependent(),h=o.computeWorldMatrix(l,r);if(o.hasThinInstances&&o.thinInstanceEnablePicking){if(this._internalPickForMesh(null,a,o,h,!0,!0,t)){const u=U.Matrix[1],d=o.thinInstanceGetWorldMatrices();for(let f=0;f<d.length;f++){d[f].multiplyToRef(h,u);const p=this._internalPickForMesh(null,a,o,u,!1,!1,t,!0);p&&(p.thinInstanceIndex=f,i.push(p))}}}else{const c=this._internalPickForMesh(null,a,o,h,!1,!1,t);c&&i.push(c)}}return i};Ee.prototype.pickWithBoundingInfo=function(a,e,t,i,s){if(!es)return null;const r=this._internalPick(n=>(this._tempPickingRay||(this._tempPickingRay=tt.Zero()),this.createPickingRayToRef(a,e,n,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return r&&(r.ray=this.createPickingRay(a,e,D.Identity(),s||null)),r};Object.defineProperty(Ee.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Ee.prototype.pick=function(a,e,t,i,s,r,n=!1){const o=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=tt.Zero()),this.createPickingRayToRef(a,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,r);return o&&(o.ray=this.createPickingRay(a,e,D.Identity(),s||null)),o};Ee.prototype.pickWithRay=function(a,e,t,i){const s=this._internalPick(r=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=D.Identity()),r.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=tt.Zero()),tt.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=a),s};Ee.prototype.multiPick=function(a,e,t,i,s){return this._internalMultiPick(r=>this.createPickingRay(a,e,r,i||null),t,s)};Ee.prototype.multiPickWithRay=function(a,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=D.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=tt.Zero()),tt.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};ve.prototype.getForwardRay=function(a=100,e,t){return this.getForwardRayToRef(new tt(m.Zero(),m.Zero(),a),a,e,t)};ve.prototype.getForwardRayToRef=function(a,e=100,t,i){t||(t=this.getWorldMatrix()),a.length=e,i?a.origin.copyFrom(i):a.origin.copyFrom(this.position);const s=U.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);const r=U.Vector3[3];return m.TransformNormalToRef(s,t,r),m.NormalizeToRef(r,a.direction),a};function Rm(a){const e=[],t=[],i=[],s=[],r=a.width||a.size||1,n=a.height||a.size||1,o=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,l=r/2,h=n/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,mt.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,mt.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,mt.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,mt.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),le._ComputeSides(o,t,e,i,s,a.frontUVs,a.backUVs);const c=new le;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Im(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Rm(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}le.CreatePlane=Rm;z.CreatePlane=(a,e,t,i,s)=>Im(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);class dt{}dt.ANCHOR_SYSTEM="xr-anchor-system";dt.BACKGROUND_REMOVER="xr-background-remover";dt.HIT_TEST="xr-hit-test";dt.MESH_DETECTION="xr-mesh-detection";dt.PHYSICS_CONTROLLERS="xr-physics-controller";dt.PLANE_DETECTION="xr-plane-detection";dt.POINTER_SELECTION="xr-controller-pointer-selection";dt.TELEPORTATION="xr-controller-teleportation";dt.FEATURE_POINTS="xr-feature-points";dt.HAND_TRACKING="xr-hand-tracking";dt.IMAGE_TRACKING="xr-image-tracking";dt.NEAR_INTERACTION="xr-near-interaction";dt.DOM_OVERLAY="xr-dom-overlay";dt.MOVEMENT="xr-controller-movement";dt.LIGHT_ESTIMATION="xr-light-estimation";dt.EYE_TRACKING="xr-eye-tracking";dt.WALKING_LOCOMOTION="xr-walking-locomotion";dt.LAYERS="xr-layers";dt.DEPTH_SENSING="xr-depth-sensing";dt.SPACE_WARP="xr-space-warp";dt.RAW_CAMERA_ACCESS="xr-raw-camera-access";class fi{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&!i.featureImplementation.attached&&!i.featureImplementation.disableAutoAttach&&this.attachFeature(t)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(t=>{const i=this._features[t];i.enabled&&i.featureImplementation.attached&&this.detachFeature(t)})})}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||X.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||X.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t=typeof e=="string"?e:e.Name,i=this._features[t];return i&&i.enabled?(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0):!1}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},s=!0,r=!0){const n=typeof e=="string"?e:e.Name;let o=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(t==="stable"?o=fi.GetStableVersionOfFeature(n):t==="latest"?o=fi.GetLatestVersionOfFeature(n):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const l=fi._ConflictingFeatures[n];if(l!==void 0&&this.getEnabledFeatures().indexOf(l)!==-1)throw new Error(`Feature ${n} cannot be enabled while ${l} is enabled.`);const h=this._features[n],c=fi.ConstructFeature(n,o,this._xrSessionManager,i);if(!c)throw new Error(`feature not found - ${n}`);h&&this.disableFeature(n);const u=c();if(u.dependsOn&&!u.dependsOn.every(f=>!!this._features[f]))throw new Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return X.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const s=this._features[i],r=s.featureImplementation.xrNativeFeatureName;if(r&&(s.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(r)===-1&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(r)===-1&&e.optionalFeatures.push(r))),s.featureImplementation.getXRSessionInitExtension){const n=await s.featureImplementation.getXRSessionInitExtension();e={...e,...n}}}return e}}fi._AvailableFeatures={};fi._ConflictingFeatures={[dt.TELEPORTATION]:dt.MOVEMENT,[dt.MOVEMENT]:dt.TELEPORTATION};class _s{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){var t;!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&((t=this._xrSessionManager.enabledFeatures)==null?void 0:t.indexOf(e))===-1&&O.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new G,this.onFeatureDetachObservable=new G}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(!this._xrSessionManager.enabledFeatures)O.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");else if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName)===-1)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,t=>this._onXRFrame(t)),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class Qt{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}Qt.DistanceJoint=0;Qt.HingeJoint=1;Qt.BallAndSocketJoint=2;Qt.WheelJoint=3;Qt.SliderJoint=4;Qt.PrismaticJoint=5;Qt.UniversalJoint=6;Qt.Hinge2Joint=Qt.WheelJoint;Qt.PointToPointJoint=8;Qt.SpringJoint=9;Qt.LockJoint=10;z._PhysicsImpostorParser=function(a,e,t){return new We(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},a)};class We{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){if(this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=m.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Q,this._tmpQuat2=new Q,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new Q),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(r=>{r(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(r=>{r(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,We._TmpVecs[0]),this.object.translate(We._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=r=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const n=this._physicsEngine.getImpostorWithPhysicsBody(r.body);n&&(this.onCollideEvent&&this.onCollideEvent(this,n),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(n)!==-1).forEach(o=>{o.callback(this,n,r.point,r.distance,r.impulse,r.normal)}))},!this.object){O.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&O.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=Q.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Q),this._options.mass=i.mass===void 0?0:i.mass,this._options.friction=i.friction===void 0?.2:i.friction,this._options.restitution=i.restitution===void 0?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=i.pressure===void 0?200:i.pressure,this._options.stiffness=i.stiffness===void 0?1:i.stiffness,this._options.velocityIterations=i.velocityIterations===void 0?20:i.velocityIterations,this._options.positionIterations=i.positionIterations===void 0?20:i.positionIterations,this._options.fixedPoints=i.fixedPoints===void 0?0:i.fixedPoints,this._options.margin=i.margin===void 0?0:i.margin,this._options.damping=i.damping===void 0?0:i.damping,this._options.path=i.path===void 0?null:i.path,this._options.shape=i.shape===void 0?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&O.Warn("You must affect impostors to children before affecting impostor to parent.")):O.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),!this._isDisposed&&(!this.parent||this._options.ignoreParent)&&this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof ut?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=We.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const r=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return r.x=Math.abs(r.x),r.y=Math.abs(r.y),r.z=Math.abs(r.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),r}else return We.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):m.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):m.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):O.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):O.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some((n,o)=>{if(n.callback===t&&n.otherImpostors.length===i.length){const l=n.otherImpostors.every(h=>i.indexOf(h)>-1);return l&&(s=o),l}return!1})?this._onPhysicsCollideCallbacks.splice(s,1):O.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):Q.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new Qt(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new We(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new Q),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=We._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const l=We._TmpQuat;o.rotationQuaternion.multiplyToRef(r,l),e.setRotationQuaternion(l,pt.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,pt.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),s==null&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const c=We._TmpQuat;e.getRotationQuaternionToRef(pt.WORLD,t,c),c.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(pt.WORLD,t,o.rotationQuaternion);const l=We._TmpVecs[0],h=We._TmpVecs[1];n||(n=We._TmpVecs[2],n.x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,h),e.getAbsolutePositionToRef(t,l),s==null&&i&&(s=i.length()),s!=null&&(l.x+=h.x*s,l.y+=h.y*s,l.z+=h.z*s),o.setAbsolutePosition(l)}}We.DEFAULT_OBJECT_SIZE=new m(1,1,1);We.IDENTITY_QUATERNION=Q.Identity();We._TmpVecs=Xi.BuildArray(3,m.Zero);We._TmpQuat=Q.Identity();We.NoImpostor=0;We.SphereImpostor=1;We.BoxImpostor=2;We.PlaneImpostor=3;We.MeshImpostor=4;We.CapsuleImpostor=6;We.CylinderImpostor=7;We.ParticleImpostor=8;We.HeightmapImpostor=9;We.ConvexHullImpostor=10;We.CustomImpostor=100;We.RopeImpostor=101;We.ClothImpostor=102;We.SoftbodyImpostor=103;var Pa;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(Pa||(Pa={}));class je{static get ForceFullSceneLoadingForIncremental(){return Qi.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Qi.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Qi.ShowLoadingScreen}static set ShowLoadingScreen(e){Qi.ShowLoadingScreen=e}static get loggingLevel(){return Qi.loggingLevel}static set loggingLevel(e){Qi.loggingLevel=e}static get CleanBoneMatrixWeights(){return Qi.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Qi.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return je._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=je._RegisteredPlugins[e];return t||(O.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),je.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in je._RegisteredPlugins){const i=je._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return je._RegisteredPlugins[t]}return je.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");t!==-1&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return je._GetPluginForExtension(s)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}static _LoadData(e,t,i,s,r,n,o,l){const h=je._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=o?je._GetPluginForExtension(o):h?je._GetPluginForDirectLoad(e.url):je._GetPluginForFilename(e.url);if(e.rawData&&!c.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let u;if(c.plugin.createPlugin!==void 0?u=c.plugin.createPlugin():u=c.plugin,!u)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(je.OnPluginActivatedObservable.notifyObservers(u),h&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!Sf(e.url))){if(u.directLoad){const C=u.directLoad(t,h);C.then?C.then(v=>{i(u,v)}).catch(v=>{r("Error in directLoad of _loadData: "+v,v)}):i(u,C)}else i(u,h);return u}const d=c.isBinary,f=(C,v)=>{if(t.isDisposed){r("Scene has been disposed");return}i(u,C,v)};let _=null,p=!1;const g=u.onDisposeObservable;g&&g.add(()=>{p=!0,_&&(_.abort(),_=null),n()});const x=()=>{if(p)return;const C=(v,b)=>{r(v==null?void 0:v.statusText,b)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,s,d,C,l):t._loadFile(e.file||e.url,f,s,!0,d,C)},T=t.getEngine();let S=T.enableOfflineSupport;if(S){let C=!1;for(const v of t.disableOfflineSupportExceptionRules)if(v.test(e.url)){C=!0;break}S=!C}return S&&H.OfflineProviderFactory?t.offlineProvider=H.OfflineProviderFactory(e.url,x,T.disableManifestCheck):x(),u}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(!t)i=e,s=X.GetFilename(e),e=X.GetFolderPath(e);else if(t.name){const o=t;i=`file:${o.name}`,s=o.name,r=o}else if(ArrayBuffer.isView(t))i="",s=en(),n=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const o=t;if(o.substr(0,1)==="/")return X.Error("Wrong sceneFilename parameter"),null;i=e+o,s=o}return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return je._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!je._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;je._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{je._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=Ae.LastCreatedScene,r=null,n=null,o=null,l=null,h=""){if(!s)return O.Error("No scene available to import mesh to"),null;const c=je._GetFileInfo(t,i);if(!c)return null;const u={};s.addPendingData(u);const d=()=>{s.removePendingData(u)},f=(g,x)=>{const T=je._FormatErrorMessage(c,g,x);o?o(s,T,new Sn(T,ca.SceneLoaderError,x)):O.Error(T),d()},_=n?g=>{try{n(g)}catch(x){f("Error in onProgress callback: "+x,x)}}:void 0,p=(g,x,T,S,C,v,b,A)=>{if(s.importedMeshesFiles.push(c.url),r)try{r(g,x,T,S,C,v,b,A)}catch(P){f("Error in onSuccess callback: "+P,P)}s.removePendingData(u)};return je._LoadData(c,s,(g,x,T)=>{if(g.rewriteRootURL&&(c.rootUrl=g.rewriteRootURL(c.rootUrl,T)),g.importMesh){const S=g,C=[],v=[],b=[];if(!S.importMesh(e,s,x,c.rootUrl,C,v,b,f))return;s.loadingPluginName=g.name,p(C,v,b,[],[],[],[],[])}else g.importMeshAsync(e,s,x,c.rootUrl,_,c.name).then(C=>{s.loadingPluginName=g.name,p(C.meshes,C.particleSystems,C.skeletons,C.animationGroups,C.transformNodes,C.geometries,C.lights,C.spriteManagers)}).catch(C=>{f(C.message,C)})},_,f,d,l,h)}static ImportMeshAsync(e,t,i="",s=Ae.LastCreatedScene,r=null,n=null,o=""){return new Promise((l,h)=>{je.ImportMesh(e,t,i,s,(c,u,d,f,_,p,g,x)=>{l({meshes:c,particleSystems:u,skeletons:d,animationGroups:f,transformNodes:_,geometries:p,lights:g,spriteManagers:x})},r,(c,u,d)=>{h(d||new Error(u))},n,o)})}static Load(e,t="",i=Ae.LastCreatedEngine,s=null,r=null,n=null,o=null,l=""){return i?je.Append(e,t,new Ee(i),s,r,n,o,l):(X.Error("No engine available"),null)}static LoadAsync(e,t="",i=Ae.LastCreatedEngine,s=null,r=null,n=""){return new Promise((o,l)=>{je.Load(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static Append(e,t="",i=Ae.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return O.Error("No scene available to append to"),null;const h=je._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};je.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const d=(p,g)=>{const x=je._FormatErrorMessage(h,p,g);n?n(i,x,new Sn(x,ca.SceneLoaderError,g)):O.Error(x),u()},f=r?p=>{try{r(p)}catch(g){d("Error in onProgress callback",g)}}:void 0,_=()=>{if(s)try{s(i)}catch(p){d("Error in onSuccess callback",p)}i.removePendingData(c)};return je._LoadData(h,i,(p,g)=>{if(p.load){if(!p.load(i,g,h.rootUrl,d))return;i.loadingPluginName=p.name,_()}else p.loadAsync(i,g,h.rootUrl,f,h.name).then(()=>{i.loadingPluginName=p.name,_()}).catch(T=>{d(T.message,T)})},f,d,u,o,l)}static AppendAsync(e,t="",i=Ae.LastCreatedScene,s=null,r=null,n=""){return new Promise((o,l)=>{je.Append(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static LoadAssetContainer(e,t="",i=Ae.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return O.Error("No scene available to load asset container to"),null;const h=je._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(p,g)=>{const x=je._FormatErrorMessage(h,p,g);n?n(i,x,new Sn(x,ca.SceneLoaderError,g)):O.Error(x),u()},f=r?p=>{try{r(p)}catch(g){d("Error in onProgress callback",g)}}:void 0,_=p=>{if(s)try{s(p)}catch(g){d("Error in onSuccess callback",g)}i.removePendingData(c)};return je._LoadData(h,i,(p,g)=>{if(p.loadAssetContainer){const T=p.loadAssetContainer(i,g,h.rootUrl,d);if(!T)return;T.populateRootNodes(),i.loadingPluginName=p.name,_(T)}else p.loadAssetContainerAsync?p.loadAssetContainerAsync(i,g,h.rootUrl,f,h.name).then(T=>{T.populateRootNodes(),i.loadingPluginName=p.name,_(T)}).catch(T=>{d(T.message,T)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,u,o,l)}static LoadAssetContainerAsync(e,t="",i=Ae.LastCreatedScene,s=null,r=null){return new Promise((n,o)=>{je.LoadAssetContainer(e,t,i,l=>{n(l)},s,(l,h,c)=>{o(c||new Error(h))},r)})}static ImportAnimations(e,t="",i=Ae.LastCreatedScene,s=!0,r=Pa.Clean,n=null,o=null,l=null,h=null,c=null){if(!i){O.Error("No scene available to load animations to");return}if(s){for(const _ of i.animatables)_.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(_=>{_.dispose()}),i.getNodes().forEach(_=>{_.animations&&(_.animations=[])})}else switch(r){case Pa.Clean:i.animationGroups.slice().forEach(f=>{f.dispose()});break;case Pa.Stop:i.animationGroups.forEach(f=>{f.stop()});break;case Pa.Sync:i.animationGroups.forEach(f=>{f.reset(),f.restart()});break;case Pa.NoSync:break;default:O.Error("Unknown animation group loading mode value '"+r+"'");return}const u=i.animatables.length,d=f=>{f.mergeAnimationsTo(i,i.animatables.slice(u),n),f.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,d,l,h,c)}static ImportAnimationsAsync(e,t="",i=Ae.LastCreatedScene,s=!0,r=Pa.Clean,n=null,o=null,l=null,h=null,c=null){return new Promise((u,d)=>{je.ImportAnimations(e,t,i,s,r,n,f=>{u(f)},l,(f,_,p)=>{d(p||new Error(_))},c)})}}je.NO_LOGGING=0;je.MINIMAL_LOGGING=1;je.SUMMARY_LOGGING=2;je.DETAILED_LOGGING=3;je.OnPluginActivatedObservable=new G;je._RegisteredPlugins={};je._ShowingLoadingScreen=!1;class vc extends ee{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new D,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){const t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var R;(function(a){a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=4]="Vector2",a[a.Vector3=8]="Vector3",a[a.Vector4=16]="Vector4",a[a.Color3=32]="Color3",a[a.Color4=64]="Color4",a[a.Matrix=128]="Matrix",a[a.Object=256]="Object",a[a.AutoDetect=1024]="AutoDetect",a[a.BasedOnInput=2048]="BasedOnInput",a[a.All=4095]="All"})(R||(R={}));var B;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Neutral=4]="Neutral",a[a.VertexAndFragment=3]="VertexAndFragment"})(B||(B={}));class fx{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===B.Fragment;this.compilationString=`
${t?`//Entry point
`:""}void main(void) {
${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`
${t?`//Constants
`:""}${this._constantDeclaration}
${this.compilationString}`);let s="";for(const r in this.functions)s+=this.functions[r]+`
`;this.compilationString=`
${s}
${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}
${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}
${this._injectAtEnd}`),this.compilationString=`${this.compilationString}
}`,this.sharedData.varyingDeclaration&&(this.compilationString=`
${t?`//Varyings
`:""}${this.sharedData.varyingDeclaration}
${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`
${t?`//Samplers
`:""}${this._samplerDeclaration}
${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`
${t?`//Uniforms
`:""}${this._uniformDeclaration}
${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`
${t?`//Attributes
`:""}${this._attributeDeclaration}
${this.compilationString}`),this.compilationString=`precision highp float;
`+this.compilationString,this.compilationString=`#if defined(WEBGL2) || defines(WEBGPU)
precision highp sampler2DArray;
#endif
`+this.compilationString,i&&(this.compilationString=`#if defined(PREPASS)\r
#extension GL_EXT_draw_buffers : require\r
layout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r
highp vec4 gl_FragColor;\r
#endif\r
`+this.compilationString);for(const r in this.extensions){const n=this.extensions[r];this.compilationString=`
${n}
${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),this.sharedData.variableNames[e]===void 0?(this.sharedData.variableNames[e]=0,e==="output"||e==="texture"?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return this.sharedData.defineNames[e]===void 0?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};
`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};
`,this.samplers.push(e))}_getGLType(e){switch(e){case R.Float:return"float";case R.Int:return"int";case R.Vector2:return"vec2";case R.Color3:case R.Vector3:return"vec3";case R.Color4:case R.Vector4:return"vec4";case R.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}
${t}
#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+`
`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]
`;let s=xt.IncludesShadersStore[e]+`
`;if(this.sharedData.emitComments&&(s=t+`
`+s),!i)return s;if(i.replaceStrings)for(let r=0;r<i.replaceStrings.length;r++){const n=i.replaceStrings[r];s=s.replace(n.search,n.replace)}return s}_emitFunctionFromInclude(e,t,i,s=""){const r=e+s;if(!this.functions[r]){if(!i||!i.removeAttributes&&!i.removeUniforms&&!i.removeVaryings&&!i.removeIfDef&&!i.replaceStrings){i&&i.repeatKey?this.functions[r]=`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]
`:this.functions[r]=`#include<${e}>${i!=null&&i.substitutionVars?"("+(i==null?void 0:i.substitutionVars)+")":""}
`,this.sharedData.emitComments&&(this.functions[r]=t+`
`+this.functions[r]);return}if(this.functions[r]=xt.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+`
`+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,`
`)),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,`
`)),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,`
`)),i.replaceStrings)for(let n=0;n<i.replaceStrings.length;n++){const o=i.replaceStrings[n];this.functions[r]=this.functions[r].replace(o.search,o.replace)}}}_registerTempVariable(e){return this.sharedData.temps.indexOf(e)!==-1?!1:(this.sharedData.temps.push(e),!0)}_emitVaryingFromString(e,t,i="",s=!1){return this.sharedData.varyings.indexOf(e)!==-1?!1:(this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+=`#if ${i}
`:this.sharedData.varyingDeclaration+=`${s?"#ifndef":"#ifdef"} ${i}
`),this.sharedData.varyingDeclaration+=`varying ${t} ${e};
`,i&&(this.sharedData.varyingDeclaration+=`#endif
`),!0)}_emitUniformFromString(e,t,i="",s=!1){this.uniforms.indexOf(e)===-1&&(this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+=`#if ${i}
`:this._uniformDeclaration+=`${s?"#ifndef":"#ifdef"} ${i}
`),this._uniformDeclaration+=`uniform ${t} ${e};
`,i&&(this._uniformDeclaration+=`#endif
`))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}}class Ab{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";!this.checks.emitVertex&&!this.allowEmptyVertexProgram&&(e+=`NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.
`),this.checks.emitFragment||(e+=`NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.
`);for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.
`;if(e)throw`Build of NodeMaterial failed:
`+e}}class Vs{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 s,r,n,o;const t=((r=(s=this._externalProperties)==null?void 0:s[e])==null?void 0:r.type)??typeof this[e],i=(o=(n=this._externalProperties)==null?void 0:n[e])==null?void 0:o.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!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+`
`;break;default:s&&(e+="#define "+i+`
`);break}}return e}}var Pr;(function(a){a[a.Compatible=0]="Compatible",a[a.TypeIncompatible=1]="TypeIncompatible",a[a.TargetIncompatible=2]="TargetIncompatible",a[a.HierarchyIssue=3]="HierarchyIssue"})(Pr||(Pr={}));var si;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(si||(si={}));class Ll{static AreEquivalentTypes(e,t){switch(e){case R.Vector3:{if(t===R.Color3)return!0;break}case R.Vector4:{if(t===R.Color4)return!0;break}case R.Color3:{if(t===R.Vector3)return!0;break}case R.Color4:{if(t===R.Vector4)return!0;break}}return!1}get direction(){return this._direction}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:(!this._enforceAssociatedVariableName||!this._associatedVariableName)&&this._connectedPoint?this._connectedPoint.associatedVariableName:this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===R.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===R.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get target(){return!this._prioritizeVertex||!this._ownerBlock?this._target:this._target!==B.VertexAndFragment?this._target:this._ownerBlock.target===B.Fragment?B.Fragment:B.Vertex}set target(e){this._target=e}get isConnected(){return this.connectedPoint!==null||this.hasEndpoints}get isConnectedToInputBlock(){return this.connectedPoint!==null&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return this._endpoints.length===0?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===B.Vertex||(e.ownerBlock.target===B.Neutral||e.ownerBlock.target===B.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===B.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===B.Vertex||e.target===B.Vertex||(e.ownerBlock.target===B.Neutral||e.ownerBlock.target===B.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===B.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===B.Fragment||(e.ownerBlock.target===B.Neutral||e.ownerBlock.target===B.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=R.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new G,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=B.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===Pr.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===B.Fragment){if(i.target===B.Vertex)return Pr.TargetIncompatible;for(const n of i.outputs)if(n.ownerBlock.target!=B.Neutral&&n.isConnectedInVertexShader)return Pr.TargetIncompatible}if(this.type!==e.type&&e.innerType!==R.AutoDetect)return Ll.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&Ll.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?Pr.Compatible:Pr.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Pr.TypeIncompatible;let s=i,r=t;return this.direction===si.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Pr.HierarchyIssue:Pr.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<R.All;)e&t||this.excludedConnectionPointTypes.push(t),t=t<<1}serialize(e=!0){const t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}class Pe{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}constructor(e,t=B.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===B.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=Yu.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===B.Neutral}initialize(e){}bind(e,t,i,s){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return t.indexOf(".")===-1&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,s,r){return r=r??new Ll(e,this,si.Input),r.type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return s=s??new Ll(e,this,si.Output),s.type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===R.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===B.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return t===-1||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(this._outputs.length===0)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===B.Vertex?!1:!!((this.target===B.VertexAndFragment||this.target===B.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=t._vertexState!=null,n=e._buildTarget===B.Vertex&&e.target!==B.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==B.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const o=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+o.associatedVariableName,t._getGLType(o.type))&&(t._vertexState.compilationString+=`${"v_"+o.associatedVariableName} = ${o.associatedVariableName};
`),i.associatedVariableName="v_"+o.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const i of this._outputs)i.associatedVariableName||(i.associatedVariableName=e._getFreeVariableName(i.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==B.Neutral&&(!(i.target&this.target)||!(i.target&e.target)))continue;const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&O.Log(`${e.target===B.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case B.Vertex:e.sharedData.checks.emitVertex=!0;break;case B.Fragment:e.sharedData.checks.emitFragment=!0;break}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`
//${this.name}
`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const r=s.ownerBlock;r&&r.target&e.target&&t.indexOf(r)!==-1&&this._processBuild(r,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};
${e}.visibleOnFrame = ${this.visibleOnFrame};
${e}.target = ${this.target};
`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let r=0;do r++,this._codeVariableName=i+r;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=`
// ${this.getClassName()}
`;this.comments&&(s+=`// ${this.comments}
`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");
`,s+=this._dumpPropertiesCode();for(const r of this.inputs){if(!r.isConnected)continue;const o=r.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}for(const r of this.outputs)if(r.hasEndpoints)for(const n of r.endpoints){const o=n.ownerBlock;o&&t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});
`}return t}clone(e,t=""){const i=this.serialize(),s=Si(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((s,r)=>{s.displayName&&(this.inputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.inputs[r].isExposedOnFrame=s.isExposedOnFrame,this.inputs[r].exposedPortPosition=s.exposedPortPosition)}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.exposedPortPosition)})}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class ap extends Pe{constructor(e){super(e,B.Neutral),this.complementW=1,this.complementZ=0,this.target=B.Vertex,this.registerInput("vector",R.AutoDetect),this.registerInput("transform",R.Matrix),this.registerOutput("output",R.Vector4),this.registerOutput("xyz",R.Vector3),this._inputs[0].onConnectionObservable.add(t=>{if(t.ownerBlock.isInput){const i=t.ownerBlock;(i.name==="normal"||i.name==="tangent")&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(this.complementW===0){const s=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",s),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName});
`,e.compilationString+=`#ifdef NONUNIFORMSCALING
`,e.compilationString+=`${r} = transposeMat3(inverseMat3(${r}));
`,e.compilationString+=`#endif
`,t.connectedPoint.type){case R.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});
`;break;case R.Vector3:case R.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});
`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});
`;break}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case R.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});
`;break;case R.Vector3:case R.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});
`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * ${t.associatedVariableName};
`;break}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;
`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=e.complementZ!==void 0?e.complementZ:0,this.complementW=e.complementW!==void 0?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};
`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};
`,e}}V("BABYLON.TransformBlock",ap);class Gd extends Pe{constructor(e){super(e,B.Vertex,!0),this.registerInput("vector",R.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const i of e)if(i.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};
`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w;
`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;
`),this}}V("BABYLON.VertexOutputBlock",Gd);var Ne;(function(a){a[a.Boolean=0]="Boolean",a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=3]="Vector2",a[a.List=4]="List"})(Ne||(Ne={}));function Le(a,e=Ne.Boolean,t="PROPERTIES",i){return(s,r)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:r,displayName:a,type:e,groupName:t,options:i??{}})}}class La extends Pe{constructor(e){super(e,B.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",R.Color4,!0),this.registerInput("rgb",R.AutoDetect,!0),this.registerInput("a",R.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&ao(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",r),t.connectedPoint)s.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${s.associatedVariableName});
`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};
`;else if(i.connectedPoint){let n="1.0";s.connectedPoint&&(n=s.associatedVariableName),i.connectedPoint.type===R.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${n});
`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${n});
`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}
`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor);
`,e.compilationString+=`#endif
`,e.compilationString+=`#ifdef ${this._gammaDefineName}
`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor);
`,e.compilationString+=`#endif
`,(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;
`),e.compilationString+=`#if defined(PREPASS)\r
`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r
`,e.compilationString+=`#endif\r
`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};
`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}E([Le("Convert to gamma space",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToGammaSpace",void 0);E([Le("Convert to linear space",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToLinearSpace",void 0);E([Le("Use logarithmic depth",Ne.Boolean,"PROPERTIES")],La.prototype,"useLogarithmicDepth",void 0);V("BABYLON.FragmentOutputBlock",La);var Rs;(function(a){a[a.Uniform=0]="Uniform",a[a.Attribute=1]="Attribute",a[a.Varying=2]="Varying",a[a.Undefined=3]="Undefined"})(Rs||(Rs={}));var nt;(function(a){a[a.World=1]="World",a[a.View=2]="View",a[a.Projection=3]="Projection",a[a.ViewProjection=4]="ViewProjection",a[a.WorldView=5]="WorldView",a[a.WorldViewProjection=6]="WorldViewProjection",a[a.CameraPosition=7]="CameraPosition",a[a.FogColor=8]="FogColor",a[a.DeltaTime=9]="DeltaTime",a[a.CameraParameters=10]="CameraParameters",a[a.MaterialAlpha=11]="MaterialAlpha"})(nt||(nt={}));var wa;(function(a){a[a.None=0]="None",a[a.Time=1]="Time",a[a.RealTime=2]="RealTime"})(wa||(wa={}));const yb={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},P_={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},_x={particle_texturemask:!0};class it extends Pe{get type(){if(this._type===R.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=R.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=R.Vector2,this._type;case"Vector3":return this._type=R.Vector3,this._type;case"Vector4":return this._type=R.Vector4,this._type;case"Color3":return this._type=R.Color3,this._type;case"Color4":return this._type=R.Color4,this._type;case"Matrix":return this._type=R.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=R.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=R.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=R.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=R.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case nt.World:case nt.WorldView:case nt.WorldViewProjection:case nt.View:case nt.ViewProjection:case nt.Projection:return this._type=R.Matrix,this._type;case nt.CameraPosition:return this._type=R.Vector3,this._type;case nt.FogColor:return this._type=R.Color3,this._type;case nt.DeltaTime:case nt.MaterialAlpha:return this._type=R.Float,this._type;case nt.CameraParameters:return this._type=R.Vector4,this._type}}return this._type}constructor(e,t=B.Vertex,i=R.AutoDetect){super(e,t,!1),this._mode=Rs.Undefined,this._animationType=wa.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new G,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return this.isAttribute?!0:super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Rs.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===R.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Rs.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Rs.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Rs.Undefined}get isUniform(){return this._mode===Rs.Uniform}set isUniform(e){this._mode=e?Rs.Uniform:Rs.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Rs.Attribute}set isAttribute(e){this._mode=e?Rs.Attribute:Rs.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Rs.Varying}set isVarying(e){this._mode=e?Rs.Varying:Rs.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Rs.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case wa.Time:{this.type===R.Float&&(this.value+=e.getAnimationRatio()*.01);break}case wa.RealTime:{this.type===R.Float&&(this.value=(Zi.Now-e.getEngine().startTime)/1e3);break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)}
`:`#ifdef ${e}
`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case R.Float:this.value=0;break;case R.Vector2:this.value=Z.Zero();break;case R.Vector3:this.value=m.Zero();break;case R.Vector4:this.value=we.Zero();break;case R.Color3:this.value=q.White();break;case R.Color4:this.value=new xe(1,1,1,1);break;case R.Matrix:this.value=D.Identity();break}}_emitConstant(e){switch(this.type){case R.Float:return`${e._emitFloat(this.value)}`;case R.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case R.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case R.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case R.Color3:return gt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&gt.Color3[0].toGammaSpaceToRef(gt.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gt.Color3[0].toLinearSpaceToRef(gt.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${gt.Color3[0].r}, ${gt.Color3[0].g}, ${gt.Color3[0].b})`;case R.Color4:return gt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&gt.Color4[0].toGammaSpaceToRef(gt.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gt.Color4[0].toLinearSpaceToRef(gt.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${gt.Color4[0].r}, ${gt.Color4[0].g}, ${gt.Color4[0].b}, ${gt.Color4[0].a})`}return""}get _noContextSwitch(){return P_[this.name]}_emit(e,t){if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(e.constants.indexOf(this.associatedVariableName)!==-1)return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};
`;return}if(e.uniforms.indexOf(this.associatedVariableName)!==-1)return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};
`,t&&(e._uniformDeclaration+=`#endif
`);const i=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case nt.WorldView:i.needWorldViewMatrix=!0;break;case nt.WorldViewProjection:i.needWorldViewProjectionMatrix=!0;break}else this._animationType!==wa.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=yb[this.name]??this.name,this.target===B.Vertex&&e._vertexState){P_[this.name]?_x[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(e.attributes.indexOf(this.associatedVariableName)!==-1)return;e.attributes.push(this.associatedVariableName),P_[this.name]?_x[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};
`,t&&(e._attributeDeclaration+=`#endif
`))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this.associatedVariableName;switch(this._systemValue){case nt.World:e.setMatrix(r,t);break;case nt.WorldView:e.setMatrix(r,i);break;case nt.WorldViewProjection:e.setMatrix(r,s);break}}_transmit(e,t,i){if(this.isAttribute)return;const s=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case nt.World:case nt.WorldView:case nt.WorldViewProjection:return;case nt.View:e.setMatrix(s,t.getViewMatrix());break;case nt.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case nt.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case nt.CameraPosition:t.bindEyePosition(e,s,!0);break;case nt.FogColor:e.setColor3(s,t.fogColor);break;case nt.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case nt.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case nt.MaterialAlpha:e.setFloat(s,i.alpha);break}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(r!==null)switch(this.type){case R.Float:e.setFloat(s,r);break;case R.Int:e.setInt(s,r);break;case R.Color3:gt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&gt.Color3[0].toGammaSpaceToRef(gt.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gt.Color3[0].toLinearSpaceToRef(gt.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,gt.Color3[0]);break;case R.Color4:gt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&gt.Color4[0].toGammaSpaceToRef(gt.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gt.Color4[0].toLinearSpaceToRef(gt.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,gt.Color4[0]);break;case R.Vector2:e.setVector2(s,r);break;case R.Vector3:e.setVector3(s,r);break;case R.Vector4:e.setVector4(s,r);break;case R.Matrix:e.setMatrix(s,r);break}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");
`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${nt[this._systemValue]});
`;if(this.isUniform){const t=[];let i="";switch(this.type){case R.Float:i=`${this.value}`;break;case R.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case R.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case R.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case R.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case R.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case R.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===R.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${wa[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(`;
`)}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this._storedValue!=null&&this._mode===Rs.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.name==="tangent"&&e.mode===Rs.Attribute&&e.type===R.Vector3&&(this._type=R.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const s=Si(e.valueType);s&&(this._storedValue=s.FromArray(e.value))}}}V("BABYLON.InputBlock",it);class $E extends Pe{constructor(e){super(e,B.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",R.AutoDetect,!1,B.VertexAndFragment),this.registerOutput("rgba",R.Color4,B.Neutral),this.registerOutput("rgb",R.Color3,B.Neutral),this.registerOutput("r",R.Float,B.Neutral),this.registerOutput("g",R.Float,B.Neutral),this.registerOutput("b",R.Float,B.Neutral),this.registerOutput("a",R.Float,B.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector2|R.Vector3|R.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?B.VertexAndFragment:B.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;
`,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===B.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});
`;return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});
`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});
`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===B.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`;return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`,e.compilationString+=`#ifdef ${this._linearDefineName}
`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});
`,e.compilationString+=`#endif
`,e.compilationString+=`#ifdef ${this._gammaDefineName}
`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});
`,e.compilationString+=`#endif
`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==B.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(i=>i.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=k.Parse(e.texture,t,i))}}V("BABYLON.CurrentScreenBlock",$E);class KE extends Pe{constructor(e){super(e,B.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",R.AutoDetect,!1,B.VertexAndFragment),this.registerOutput("rgba",R.Color4,B.Neutral),this.registerOutput("rgb",R.Color3,B.Neutral),this.registerOutput("r",R.Float,B.Neutral),this.registerOutput("g",R.Float,B.Neutral),this.registerOutput("b",R.Float,B.Neutral),this.registerOutput("a",R.Float,B.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector2|R.Vector3|R.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="particle_uv"&&t(s));i||(i=new it("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`,e.compilationString+=`#ifdef ${this._linearDefineName}
`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});
`,e.compilationString+=`#endif
`,e.compilationString+=`#ifdef ${this._gammaDefineName}
`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});
`,e.compilationString+=`#endif
`}_buildBlock(e){if(super._buildBlock(e),e.target===B.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});
`;for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=k.Parse(e.texture,t,i))}}V("BABYLON.ParticleTextureBlock",KE);class jE extends Pe{constructor(e){super(e,B.Fragment),this._isUnique=!0,this.registerInput("color",R.Color4,!1,B.Fragment),this.registerOutput("rampColor",R.Color4,B.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==B.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`
            #ifdef RAMPGRADIENT
                vec4 baseColor = ${this.color.associatedVariableName};
                float alpha = ${this.color.associatedVariableName}.a;

                float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);

                vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));
                baseColor.rgb *= rampColor.rgb;

                // Remapped alpha
                float finalAlpha = baseColor.a;
                baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);

                ${this._declareOutput(this.rampColor,e)} = baseColor;
            #else
                ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};
            #endif
        `,this}}V("BABYLON.ParticleRampGradientBlock",jE);class qE extends Pe{constructor(e){super(e,B.Fragment),this._isUnique=!0,this.registerInput("color",R.Color4,!1,B.Fragment),this.registerInput("alphaTexture",R.Float,!1,B.Fragment),this.registerInput("alphaColor",R.Float,!1,B.Fragment),this.registerOutput("blendColor",R.Color4,B.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==B.Vertex)return e.compilationString+=`
            #ifdef BLENDMULTIPLYMODE
                ${this._declareOutput(this.blendColor,e)};
                float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};
                ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);
                ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;
            #else
                ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};
            #endif
        `,this}}V("BABYLON.ParticleBlendMultiplyBlock",qE);class zo{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let s=0;s<i.meshes.length;s++){const r=i.meshes[s];if(!r.material){!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1);continue}if(!(!r.computeBonesUsingShaders||r.numBoneInfluencers===0)){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(const n of r.subMeshes)if(n.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;s<i.length;s++)e=e.replace("#define "+i[s],"");this._currentRank++}return e}}const Rb="postprocessVertexShader",Ib=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[Rb]=Ib;class Pm{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get texture(){var e;return((e=this._textures)==null?void 0:e[0])??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,s,r,n;let e=null;if(this._isMulti){const o=this.textures;if(o&&o.length>0){let l=!1,h=o.length,c=-1;const u=o[o.length-1]._source;(u===et.Depth||u===et.DepthStencil)&&(l=!0,c=o[o.length-1].format,h--);const d=[],f=[],_=[],p=[],g=[],x=[],T=[],S={};for(let b=0;b<h;++b){const A=o[b];d.push(A.samplingMode),f.push(A.type),_.push(A.format),S[A.uniqueId]!==void 0?(p.push(-1),T.push(0)):(S[A.uniqueId]=b,A.is2DArray?(p.push(35866),T.push(A.depth)):A.isCube?(p.push(34067),T.push(0)):A.is3D?(p.push(32879),T.push(A.depth)):(p.push(3553),T.push(0))),this._faceIndices&&g.push(this._faceIndices[b]??0),this._layerIndices&&x.push(this._layerIndices[b]??0)}const C={samplingModes:d,generateMipMaps:o[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:l,depthTextureFormat:c,types:f,formats:_,textureCount:h,targetTypes:p,faceIndex:g,layerIndex:x,layerCounts:T,label:this.label},v={width:this.width,height:this.height};e=this._engine.createMultipleRenderTarget(v,C);for(let b=0;b<h;++b){if(p[b]!==-1)continue;const A=S[o[b].uniqueId];e.setTexture(e.textures[A],b)}}}else{const o={};if(o.generateDepthBuffer=this._generateDepthBuffer,o.generateMipMaps=((t=this.texture)==null?void 0:t.generateMipMaps)??!1,o.generateStencilBuffer=this._generateStencilBuffer,o.samplingMode=(i=this.texture)==null?void 0:i.samplingMode,o.type=(s=this.texture)==null?void 0:s.type,o.format=(r=this.texture)==null?void 0:r.format,o.noColorAttachment=!this._textures,o.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,o);else{const l={width:this.width,height:this.height,layers:this.is2DArray?(n=this.texture)==null?void 0:n.depth:void 0};e=this._engine.createRenderTargetTexture(l,o)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,s=t===2||t===3||t===11;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,s,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e;if(this._textures)for(let t=0;t<((e=this._textures)==null?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)==null||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Pb extends Pm{constructor(e,t,i,s,r){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=r}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){if(this._depthStencilBuffer){const o=this._engine._currentFramebuffer,l=this._context;this._engine._bindUnboundFramebuffer(this._framebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.RENDERBUFFER,null),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.RENDERBUFFER,null),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.STENCIL_ATTACHMENT,l.RENDERBUFFER,null),this._engine._bindUnboundFramebuffer(o),l.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,s,r,n)}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const r=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,r,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){var o,l;if(!e._hardwareTexture)return;const r=this._framebuffer,n=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(r),this._engine.webGLVersion>1){const h=this._context,c=h["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??((o=this.layerIndices)==null?void 0:o[t])??0,h.framebufferTextureLayer(h.FRAMEBUFFER,c,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??((l=this.faceIndices)==null?void 0:l[t])??0,h.framebufferTexture2D(h.FRAMEBUFFER,c,h.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):h.framebufferTexture2D(h.FRAMEBUFFER,c,h.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const h=this._context,c=h["COLOR_ATTACHMENT"+t+"_WEBGL"],u=i!==void 0?h.TEXTURE_CUBE_MAP_POSITIVE_X+i:h.TEXTURE_2D;h.framebufferTexture2D(h.FRAMEBUFFER,c,u,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(n)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=((s=this._attachments)==null?void 0:s.length)??this.textures.length;for(let r=0;r<i;r++){const n=this.textures[r];n&&(n.is2DArray||n.is3D?this._bindTextureRenderTarget(n,r,this.layerIndices[r]):n.isCube?this._bindTextureRenderTarget(n,r,this.faceIndices[r]):this._bindTextureRenderTarget(n,r))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=this.textures[e];s.is2DArray||s.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):s.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}pe.prototype._createHardwareRenderTargetWrapper=function(a,e,t){const i=new Pb(a,e,t,this,this._gl);return this._renderTargetWrapperCache.push(i),i};pe.prototype.createRenderTargetTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!1,a);let i=!0,s=!1,r=!1,n,o=1,l;e!==void 0&&typeof e=="object"&&(i=e.generateDepthBuffer??!0,s=!!e.generateStencilBuffer,r=!!e.noColorAttachment,n=e.colorAttachment,o=e.samples??1,l=e.label);const h=n||(r?null:this._createInternalTexture(a,e,!0,et.RenderTarget)),c=a.width||a,u=a.height||a,d=this._currentFramebuffer,f=this._gl,_=f.createFramebuffer();return this._bindUnboundFramebuffer(_),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(s,i,c,u),h&&!h.is2DArray&&f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,h._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(d),t.label=l??"RenderTargetWrapper",t._framebuffer=_,t._generateDepthBuffer=i,t._generateStencilBuffer=s,t.setTextures(h),this.updateRenderTargetTextureSampleCount(t,o),t};pe.prototype.createDepthStencilTexture=function(a,e,t){if(e.isCube){const i=a.width||a;return this._createDepthStencilCubeTexture(i,e)}else return this._createDepthStencilTexture(a,e,t)};pe.prototype._createDepthStencilTexture=function(a,e){const t=this._gl,i=a.layers||0,s=i!==0?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D,r=new Tt(this,et.DepthStencil);if(r.label=e.label,!this._caps.depthTextureExtension)return O.Error("Depth texture is not supported by your browser or hardware."),r;const n={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(s,r,!0),this._setupDepthStencilTexture(r,a,n.generateStencil,n.comparisonFunction===0?!1:n.bilinearFiltering,n.comparisonFunction,n.samples),n.depthTextureFormat!==void 0){if(n.depthTextureFormat!==15&&n.depthTextureFormat!==16&&n.depthTextureFormat!==17&&n.depthTextureFormat!==13&&n.depthTextureFormat!==14&&n.depthTextureFormat!==18)return O.Error("Depth texture format is not supported."),r;r.format=n.depthTextureFormat}else r.format=n.generateStencil?13:16;const o=r.format===17||r.format===13||r.format===18;let l=t.UNSIGNED_INT;r.format===15?l=t.UNSIGNED_SHORT:r.format===17||r.format===13?l=t.UNSIGNED_INT_24_8:r.format===14?l=t.FLOAT:r.format===18&&(l=t.FLOAT_32_UNSIGNED_INT_24_8_REV);const h=o?t.DEPTH_STENCIL:t.DEPTH_COMPONENT;let c=h;return this.webGLVersion>1&&(r.format===15?c=t.DEPTH_COMPONENT16:r.format===16?c=t.DEPTH_COMPONENT24:r.format===17||r.format===13?c=t.DEPTH24_STENCIL8:r.format===14?c=t.DEPTH_COMPONENT32F:r.format===18&&(c=t.DEPTH32F_STENCIL8)),r.is2DArray?t.texImage3D(s,0,c,r.width,r.height,i,0,h,l,null):t.texImage2D(s,0,c,r.width,r.height,0,h,l,null),this._bindTextureDirectly(s,null),this._internalTexturesCache.push(r),r};pe.prototype.updateRenderTargetTextureSampleCount=function(a,e){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(t.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(t.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);const i=a.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const s=t.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=s,this._bindUnboundFramebuffer(a._MSAAFramebuffer);const r=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(a.texture.type,a.texture.format,a.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(a._framebuffer);return a.texture.samples=e,a._samples=e,a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e),this._bindUnboundFramebuffer(null),e};class De{static RegisterShaderCodeProcessing(e,t){if(!t){delete De._CustomShaderCodeProcessing[e??""];return}De._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return De._CustomShaderCodeProcessing[e]??De._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,l,h,c=null,u=0,d="postprocess",f,_=!1,p=5,g=Zt.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Wi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Z(1,1),this._texelSize=Z.Zero(),this.onActivateObservable=new G,this.onSizeChangedObservable=new G,this.onApplyObservable=new G,this.onBeforeRenderObservable=new G,this.onAfterRenderObservable=new G,this.name=e;let x=1,T=null;if(i&&!Array.isArray(i)){const S=i;i=S.uniforms??null,s=S.samplers??null,x=S.size??1,n=S.camera??null,o=S.samplingMode??1,l=S.engine,h=S.reusable,c=S.defines??null,u=S.textureType??0,d=S.vertexUrl??"postprocess",f=S.indexParameters,_=S.blockCompilation??!1,p=S.textureFormat??5,g=S.shaderLanguage??Zt.GLSL,T=S.uniformBuffers??null}else r&&(typeof r=="number"?x=r:x={width:r.width,height:r.height});n!=null?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=x,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=p,this._shaderLanguage=g,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=T||[],this._indexParameters=f,this._drawWrapper=new Bi(this._engine),_||this.updateEffect(c)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Wi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,l){const h=De._GetShaderCodeProcessing(this.name);if(h!=null&&h.defineCustomBindings){const c=(t==null?void 0:t.slice())??[];c.push(...this._parameters);const u=(i==null?void 0:i.slice())??[];u.push(...this._samplers),e=h.defineCustomBindings(this.name,e,c,u),t=c,i=u}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:l??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:h!=null&&h.processCodeAfterIncludes?(c,u)=>h.processCodeAfterIncludes(this.name,c,u):null,processFinalCode:h!=null&&h.processFinalCode?(c,u)=>h.processFinalCode(this.name,c,u):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;const s=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:s,postProcessChannel:i,lastUsedRenderId:-1}),s}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s<this._textures.length;s++)if(this._textures.data[s]===this._textureCache[t].texture){i=!0;break}i||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,i=null,s=!1,r=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let h=0;h<i._postProcesses.length;h++)if(i._postProcesses[h]!==null){n=i._postProcesses[h];break}}const o={width:this.width,height:this.height},l={generateMipMaps:s,generateDepthBuffer:r||n===this,generateStencilBuffer:(r||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(o,l,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(o,l,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{e=this.inputTexture;let t;for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,i){var f,_;e=e||this._camera;const s=e.getScene(),r=s.getEngine(),n=r.getCaps().maxTextureSize,o=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,l=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let h=this._options.width||o,c=this._options.height||l;const u=this.renderTargetSamplingMode!==7&&this.renderTargetSamplingMode!==1&&this.renderTargetSamplingMode!==2;let d=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const p=r.currentViewport;p&&(h*=p.width,c*=p.height)}(u||this.alwaysForcePOT)&&(this._options.width||(h=r.needPOTTextures?H.GetExponentOfTwo(h,n,this.scaleMode):h),this._options.height||(c=r.needPOTTextures?H.GetExponentOfTwo(c,n,this.scaleMode):c)),(this.width!==h||this.height!==c||!(d=this._getTarget()))&&this.resize(h,c,e,u,i),this._textures.forEach(p=>{p.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(p,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/h,l/c),this._engine.bindFramebuffer(d,0,o,l,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),(_=(f=this._engine)._debugInsertMarker)==null||_.call(f,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e;return((e=this._drawWrapper.effect)==null?void 0:e.isReady())??!1}apply(){var t,i,s;if(!((t=this._drawWrapper.effect)!=null&&t.isReady()))return null;this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(s=(i=De._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||s.call(i,this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._disposeTextures();let t;if(this._scene&&(t=this._scene.postProcesses.indexOf(this),t!==-1&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=_e.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=De.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=Si(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return _e.Parse(()=>new De(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,s)}}De._CustomShaderCodeProcessing={};E([I()],De.prototype,"uniqueId",void 0);E([I()],De.prototype,"name",void 0);E([I()],De.prototype,"width",void 0);E([I()],De.prototype,"height",void 0);E([I()],De.prototype,"renderTargetSamplingMode",void 0);E([cm()],De.prototype,"clearColor",void 0);E([I()],De.prototype,"autoClear",void 0);E([I()],De.prototype,"forceAutoClearInAlphaMode",void 0);E([I()],De.prototype,"alphaMode",void 0);E([I()],De.prototype,"alphaConstants",void 0);E([I()],De.prototype,"enablePixelPerfectMode",void 0);E([I()],De.prototype,"forceFullscreenViewport",void 0);E([I()],De.prototype,"scaleMode",void 0);E([I()],De.prototype,"alwaysForcePOT",void 0);E([I("samples")],De.prototype,"_samples",void 0);E([I()],De.prototype,"adaptScaleToCurrentViewport",void 0);V("BABYLON.PostProcess",De);class zd extends Pe{constructor(e){super(e,B.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",R.Vector4,!0),this.registerInput("xyz ",R.Vector3,!0),this.registerInput("xy ",R.Vector2,!0),this.registerInput("zw ",R.Vector2,!0),this.registerInput("x",R.Float,!0),this.registerInput("y",R.Float,!0),this.registerInput("z",R.Float,!0),this.registerInput("w",R.Float,!0),this.registerOutput("xyzw",R.Vector4),this.registerOutput("xyz",R.Vector3),this.registerOutput("xy",R.Vector2),this.registerOutput("zw",R.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this._outputs[0],u=this._outputs[1],d=this._outputs[2],f=this._outputs[3];return h.isConnected?(c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${h.associatedVariableName}${this._buildSwizzle(4)};
`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${h.associatedVariableName}${this._buildSwizzle(3)};
`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${h.associatedVariableName}${this._buildSwizzle(2)};
`)):l.isConnected?(c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec4(${l.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};
`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};
`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};
`)):n.isConnected?(c.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(c,e)+` = vec4(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};
`:e.compilationString+=this._declareOutput(c,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};
`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};
`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};
`),f.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(f,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};
`:e.compilationString+=this._declareOutput(f,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};
`)):(c.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(c,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};
`:e.compilationString+=this._declareOutput(c,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};
`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};
`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};
`),f.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(f,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};
`:e.compilationString+=this._declareOutput(f,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};
`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";
`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";
`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";
`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";
`,e}}V("BABYLON.VectorMergerBlock",zd);class Of extends Pe{constructor(e){super(e,B.Neutral),this.sourceRange=new Z(-1,1),this.targetRange=new Z(0,1),this.registerInput("input",R.AutoDetect),this.registerInput("sourceMin",R.Float,!0),this.registerInput("sourceMax",R.Float,!0),this.registerInput("targetMin",R.Float,!0),this.registerInput("targetMax",R.Float,!0),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});
`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});
`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});
`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=Z.FromArray(e.sourceRange),this.targetRange=Z.FromArray(e.targetRange)}}E([Le("From",Ne.Vector2)],Of.prototype,"sourceRange",void 0);E([Le("To",Ne.Vector2)],Of.prototype,"targetRange",void 0);V("BABYLON.RemapBlock",Of);class op extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(R.Float),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};
`,this}}V("BABYLON.MultiplyBlock",op);var Xs;(function(a){a[a.Material=0]="Material",a[a.PostProcess=1]="PostProcess",a[a.Particle=2]="Particle",a[a.ProceduralTexture=3]="ProceduralTexture"})(Xs||(Xs={}));class Mb extends Vs{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class as{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:m.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:m.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:m.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:m.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const r of t){if(r.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=m.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new m(10,10,10),this.onAnimationEnd=null,this.blendMode=as.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new Z(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new m(0,0,0),this._useLogarithmicDepth=!1,this.gravity=m.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new xe(1,1,1,1),this.color2=new xe(1,1,1,1),this.colorDead=new xe(0,0,0,1),this.textureMask=new xe(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Mb,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new m(0,1,0),i=new m(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new m(0,1,0),r=new m(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}as.BLENDMODE_ONEONE=0;as.BLENDMODE_STANDARD=1;as.BLENDMODE_ADD=2;as.BLENDMODE_MULTIPLY=3;as.BLENDMODE_MULTIPLYADD=4;class QE extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("rgba",R.Color4,!0),this.registerInput("rgb ",R.Color3,!0),this.registerOutput("rgb",R.Color3),this.registerOutput("r",R.Float),this.registerOutput("g",R.Float),this.registerOutput("b",R.Float),this.registerOutput("a",R.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return e==="rgb "?"rgbIn":e}_outputRename(e){return e==="rgb"?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;
`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.r;
`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.g;
`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b;
`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;
`),this}}V("BABYLON.ColorSplitterBlock",QE);pe.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const s=this._gl,r=new Tt(this,et.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const n=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,O.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),a,a,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,a,a),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=a,r.height=a,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),t};const M_={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Nf{constructor(e,t=M_){this._fullscreenViewport=new Vr(0,0,1,1);const i=t.positions??M_.positions,s=t.indices??M_.indices;this.engine=e,this._vertexBuffers={[y.PositionKind]:new y(e,i,y.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(s);for(const r in this._vertexBuffers)this._vertexBuffers[r]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[y.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[y.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class da{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new G;let t;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));const s=e.defines?e.defines.join(`
`):"";this._drawWrapper=new Bi(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new xt(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const ZE="passPixelShader",JE=`varying vec2 vUV;uniform sampler2D textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{gl_FragColor=texture2D(textureSampler,vUV);}`;W.ShadersStore[ZE]=JE;const px={name:ZE,shader:JE};class Fs{static _CreateDumpRenderer(){if(!Fs._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new pe(e,!1,i)}catch{e=document.createElement("canvas"),t=new pe(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new Nf(t),r=new da({engine:t,name:px.name,fragmentShader:px.shader,samplerNames:["textureSampler"]});Fs._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return Fs._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const l=await i.readPixels(0,0,e,t),h=new Uint8Array(l.buffer);Fs.DumpData(e,t,h,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,l){return new Promise(h=>{Fs.DumpData(e,t,i,c=>h(c),s,r,n,o,l)})}static DumpData(e,t,i,s,r="image/png",n,o=!1,l=!1,h){const c=Fs._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let f=i.length;for(;f--;){const _=i[f];d[f]=Math.round(ge.Clamp(_)*255)}i=d}const u=c.engine.createRawTexture(i,e,t,5,!1,!o,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?X.ToBlob(c.canvas,d=>{const f=new FileReader;f.onload=_=>{const p=_.target.result;s&&s(p)},f.readAsArrayBuffer(d)},r,h):X.EncodeScreenshotCanvasData(c.canvas,s,r,n,h),u.dispose()}static Dispose(){Fs._DumpToolsEngine&&(Fs._DumpToolsEngine.wrapper.dispose(),Fs._DumpToolsEngine.renderer.dispose(),Fs._DumpToolsEngine.engine.dispose()),Fs._DumpToolsEngine=null}}const Db=()=>{X.DumpData=Fs.DumpData,X.DumpDataAsync=Fs.DumpDataAsync,X.DumpFramebuffer=Fs.DumpFramebuffer};Db();class oi extends k{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=oE(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let s=0;s<i.length;++s)for(let r=0;r<this._renderPassIds.length;++r)i[s].setMaterialForRenderPass(this._renderPassIds[r],t!==void 0?Array.isArray(t)?t[r]:t:void 0)}get isMulti(){var e;return((e=this._renderTarget)==null?void 0:e.isMulti)??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e;return((e=this._renderTarget)==null?void 0:e._depthStencilTexture)??null}constructor(e,t,i,s=!1,r=!0,n=0,o=!1,l=k.TRILINEAR_SAMPLINGMODE,h=!0,c=!1,u=!1,d=5,f=!1,_,p,g=!1,x=!1){let T,S=!0;if(typeof s=="object"){const v=s;s=!!v.generateMipMaps,r=v.doNotChangeAspectRatio??!0,n=v.type??0,o=!!v.isCube,l=v.samplingMode??k.TRILINEAR_SAMPLINGMODE,h=v.generateDepthBuffer??!0,c=!!v.generateStencilBuffer,u=!!v.isMulti,d=v.format??5,f=!!v.delayAllocation,_=v.samples,p=v.creationFlags,g=!!v.noColorAttachment,x=!!v.useSRGBBuffer,T=v.colorAttachment,S=v.gammaSpace??S}if(super(null,i,!s,void 0,l,void 0,void 0,void 0,void 0,d),this._unObserveRenderList=null,this._renderListHasChanged=(v,b)=>{var P;const A=this._renderList?this._renderList.length:0;(b===0&&A>0||A===0)&&((P=this.getScene())==null||P.meshes.forEach(L=>{L._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new G,this.onAfterUnbindObservable=new G,this.onBeforeRenderObservable=new G,this.onAfterRenderObservable=new G,this.onClearObservable=new G,this.onResizeObservable=new G,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=m.Zero(),i=this.getScene(),!i)return;const C=this.getScene().getEngine();this._gammaSpace=S,this._coordinatesMode=k.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=C.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new Ts(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:_,creationFlags:p,noColorAttachment:g,useSRGBBuffer:x,colorAttachment:T,label:this.name},this.samplingMode===k.NEAREST_SAMPLINGMODE&&(this.wrapU=k.CLAMP_ADDRESSMODE,this.wrapV=k.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=k.INVCUBIC_MODE,this._textureMatrix=D.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,_!==void 0&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14){var n;(n=this._renderTarget)==null||n.createDepthStencilTexture(e,t,i,s,r)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();const e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){if(e.ratio){this._sizeRatio=e.ratio;const i=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(i.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(i.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()}get samples(){var e;return((e=this._renderTarget)==null?void 0:e.samples)??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){const t=this.getScene();if(!t)return;this._postProcessManager=new qd(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var s;const t=this.isCube;(s=this._renderTarget)==null||s.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let c=0;c<this._waitingRenderList.length;c++){const u=this._waitingRenderList[c],d=s.getMeshById(u);d&&this.renderList.push(d)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const c=this.getScene();if(!c)return i;const u=c.meshes;for(let d=0;d<u.length;d++){const f=u[d];this.renderListPredicate(f)&&this.renderList.push(f)}}const n=r.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);const o=this.activeCamera??s.activeCamera,l=s.activeCamera;o&&(o!==s.activeCamera&&(s.setTransformMatrix(o.getViewMatrix(),o.getProjectionMatrix(!0)),s.activeCamera=o),r.setViewport(o.rigParent?o.rigParent.viewport:o.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();const c=this.is2DArray?this.getRenderLayers():this.isCube?6:1;for(let u=0;u<c&&h;u++){let d=null;const f=this.renderList?this.renderList:s.getActiveMeshes().data,_=this.renderList?this.renderList.length:s.getActiveMeshes().length;r.currentRenderPassId=this._renderPassIds[u],this.onBeforeRenderObservable.notifyObservers(u),this.getCustomRenderList&&(d=this.getCustomRenderList(u,f,_)),d||(d=f),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let p=0;p<d.length&&h;++p){const g=d[p];if(!(!g.isEnabled()||g.isBlocked||!g.isVisible||!g.subMeshes)){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(g,this.refreshRate,i)){h=!1;continue}}else if(!g.isReady(!0)){h=!1;continue}}}this.onAfterRenderObservable.notifyObservers(u),(this.is2DArray||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(this.is2DArray&&!this.isMulti)for(let c=0;c<this.getRenderLayers();c++)this._renderToTarget(0,e,t,c,o),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let c=0;c<6;c++)this._renderToTarget(c,e,t,void 0,o),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,o);return this.onAfterUnbindObservable.notifyObservers(this),r.currentRenderPassId=n,l&&(s.activeCamera=l,this.activeCamera&&this.activeCamera!==s.activeCamera&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),r.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const s=e*t,r=H.NearestPOT(s+128*128/(128+s));return Math.min(H.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,s){const r=this.getScene();if(!r)return;this._renderingManager.reset();const n=r.getRenderId();for(let o=0;o<t;o++){const l=e[o];if(l&&!l.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(l,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!l.isReady(this.refreshRate===0)){this.resetRefreshCounter();continue}if(!l._internalAbstractMeshDataInfo._currentLODIsUpToDate&&r.activeCamera&&(l._internalAbstractMeshDataInfo._currentLOD=r.customLODSelector?r.customLODSelector(l,this.activeCamera||r.activeCamera):l.getLOD(this.activeCamera||r.activeCamera),l._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!l._internalAbstractMeshDataInfo._currentLOD)continue;let h=l._internalAbstractMeshDataInfo._currentLOD;h._preActivateForIntermediateRendering(n);let c;if(s&&i?c=(l.layerMask&i.layerMask)===0:c=!1,l.isEnabled()&&l.isVisible&&l.subMeshes&&!c&&(h!==l&&h._activate(n,!0),l._activate(n,!0)&&l.subMeshes.length)){l.isAnInstance?l._internalAbstractMeshDataInfo._actAsRegularMesh&&(h=l):h._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,h._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let u=0;u<h.subMeshes.length;u++){const d=h.subMeshes[u];this._renderingManager.dispatch(d,h)}}}}for(let o=0;o<r.particleSystems.length;o++){const l=r.particleSystems[o],h=l.emitter;!l.isStarted()||!h||h.position&&!h.isEnabled()||this._renderingManager.dispatchParticles(l)}}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const s=i.getEngine();this._renderTarget&&s.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){var h,c,u;const n=this.getScene();if(!n)return;const o=n.getEngine();if((h=o._debugPushGroup)==null||h.call(o,`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&o.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let d=null;const f=this.renderList?this.renderList:n.getActiveMeshes().data,_=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(d=this.getCustomRenderList(this.is2DArray?s:e,f,_)),d?this._prepareRenderingManager(d,d.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(f,_,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),d=f);for(const g of n._beforeRenderTargetClearStage)g.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const g of n._beforeRenderTargetDrawStage)g.action(this,e,s);this._renderingManager.render(this.customRenderFunction,d,this.renderParticles,this.renderSprites);for(const g of n._afterRenderTargetDrawStage)g.action(this,e,s);const p=((c=this._texture)==null?void 0:c.generateMipMaps)??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const g of n._afterRenderTargetPostProcessStage)g.action(this,e,s);this._texture&&(this._texture.generateMipMaps=p),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&Fs.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&e===5&&o.generateMipMapsForCubemap(this._texture),(u=o._debugPopGroup)==null||u.call(o,1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new oi(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;(e=this._renderTarget)==null||e.dispose(!0)}releaseInternalTexture(){var e;(e=this._renderTarget)==null||e.releaseTextures(),this._texture=null}dispose(){var i;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(const s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===oi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=oi.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}oi.REFRESHRATE_RENDER_ONCE=0;oi.REFRESHRATE_RENDER_ONEVERYFRAME=1;oi.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;k._CreateRenderTargetTexture=(a,e,t,i,s)=>new oi(a,e,t,i);class Ob{constructor(e){this.name=he.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(he.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){X.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e<this.scene.proceduralTextures.length;e++){const t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}X.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}}}const Nb="proceduralVertexShader",Fb=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[Nb]=Fb;class $n extends k{constructor(e,t,i,s,r=null,n=!0,o=!1,l=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new G,this.onBeforeGenerationObservable=new G,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,r!==null&&!(r instanceof k)?(this._options=r,this._fallbackTexture=r.fallbackTexture??null):(this._options={},this._fallbackTexture=r),s=this.getScene()||Ae.LastCreatedScene;let h=s._getComponent(he.NAME_PROCEDURALTEXTURE);h||(h=new Ob(s),s._addComponent(h)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=n,this._drawWrapper=new Bi(this._fullEngine),this.setFragment(i);const c=this._createRtWrapper(o,t,n,l);this._texture=c.texture;const u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[y.PositionKind]=new y(this._fullEngine,u,y.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId),this._contentData)}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[y.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===oi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=oi.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)==null||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}const t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:typeof this._fragment=="string"?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[y.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var s;(s=this._rtWrapper)==null||s.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return!this.isEnabled||!this.isReady()||!this._texture?(this._texture&&(this._texture.isReady=!1),!1):this._fallbackTextureUsed?!1:this._currentRefreshId===-1?(this._currentRefreshId=1,this._frameId++,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)}setTexture(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var r,n;const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const o in this._textures)this._drawWrapper.effect.setTexture(o,this._textures[o]);for(const o in this._ints)this._drawWrapper.effect.setInt(o,this._ints[o]);for(const o in this._floats)this._drawWrapper.effect.setFloat(o,this._floats[o]);for(const o in this._floatsArrays)this._drawWrapper.effect.setArray(o,this._floatsArrays[o]);for(const o in this._colors3)this._drawWrapper.effect.setColor3(o,this._colors3[o]);for(const o in this._colors4){const l=this._colors4[o];this._drawWrapper.effect.setFloat4(o,l.r,l.g,l.b,l.a)}for(const o in this._vectors2)this._drawWrapper.effect.setVector2(o,this._vectors2[o]);for(const o in this._vectors3)this._drawWrapper.effect.setVector3(o,this._vectors3[o]);for(const o in this._matrices)this._drawWrapper.effect.setMatrix(o,this._matrices[o])}if(!this._texture||!this._rtWrapper)return;(r=i._debugPushGroup)==null||r.call(i,`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let o=0;o<6;o++)i.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(ee.TriangleFillMode,0,6);else i.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(ee.TriangleFillMode,0,6);i.unBindFramebuffer(this._rtWrapper,this.isCube),s&&i.setViewport(s),this.isCube&&i.generateMipMapsForCubemap(this._texture),(n=i._debugPopGroup)==null||n.call(i,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new $n(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[y.PositionKind];i&&(i.dispose(),this._vertexBuffers[y.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}E([I()],$n.prototype,"isEnabled",void 0);E([I()],$n.prototype,"autoClear",void 0);E([I()],$n.prototype,"_generateMipMaps",void 0);E([I()],$n.prototype,"_size",void 0);E([I()],$n.prototype,"refreshRate",null);V("BABYLON.ProceduralTexture",$n);var $i;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Exp2=4]="Exp2",a[a.Round=5]="Round",a[a.Floor=6]="Floor",a[a.Ceiling=7]="Ceiling",a[a.Sqrt=8]="Sqrt",a[a.Log=9]="Log",a[a.Tan=10]="Tan",a[a.ArcTan=11]="ArcTan",a[a.ArcCos=12]="ArcCos",a[a.ArcSin=13]="ArcSin",a[a.Fract=14]="Fract",a[a.Sign=15]="Sign",a[a.Radians=16]="Radians",a[a.Degrees=17]="Degrees"})($i||($i={}));class eS extends Pe{constructor(e){super(e,B.Neutral),this.operation=$i.Cos,this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case $i.Cos:{i="cos";break}case $i.Sin:{i="sin";break}case $i.Abs:{i="abs";break}case $i.Exp:{i="exp";break}case $i.Exp2:{i="exp2";break}case $i.Round:{i="round";break}case $i.Floor:{i="floor";break}case $i.Ceiling:{i="ceil";break}case $i.Sqrt:{i="sqrt";break}case $i.Log:{i="log";break}case $i.Tan:{i="tan";break}case $i.ArcTan:{i="atan";break}case $i.ArcCos:{i="acos";break}case $i.ArcSin:{i="asin";break}case $i.Fract:{i="fract";break}case $i.Sign:{i="sign";break}case $i.Radians:{i="radians";break}case $i.Degrees:{i="degrees";break}}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});
`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${$i[this.operation]};
`}}V("BABYLON.TrigonometryBlock",eS);const D_={effect:null,subMesh:null};class Rd extends Vs{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){this[e]===void 0&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Ei extends vc{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||e.getClassName()==="ReflectionTextureBlock"||e.getClassName()==="ReflectionBlock"||e.getClassName()==="RefractionBlock"||e.getClassName()==="CurrentScreenBlock"||e.getClassName()==="ParticleTextureBlock"||e.getClassName()==="ImageSourceBlock"||e.getClassName()==="TriPlanarBlock"||e.getClassName()==="BiPlanarBlock"||e.getClassName()==="PrePassTextureBlock"}_getGlobalNodeMaterialEditor(){if(typeof NODEEDITOR<"u")return NODEEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeEditor<"u")return BABYLON}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||Ae.LastCreatedScene),this._buildId=Ei._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new D,this._cachedWorldViewProjectionMatrix=new D,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new G,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=Xs.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_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()})))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return X.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(t!==-1)return this._optimizers.splice(t,1),this}addOutputNode(e){if(e.target===null)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&B.Vertex&&this._addVertexOutputNode(e),e.target&B.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&B.Vertex&&this._removeVertexOutputNode(e),e.target&B.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=B.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(t!==-1)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(this._fragmentOutputNodes.indexOf(e)===-1)return e.target=B.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(t!==-1)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return this.ignoreAlpha?!1:this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===B.VertexAndFragment||t.target===B.Fragment&&e.target===B.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const r=e.getClassName();for(const n of this.attachedBlocks)if(n.getClassName()===r)throw`Cannot have multiple blocks of type ${r} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const o=n.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const r of e.outputs)r.associatedVariableName=""}_resetDualBlocks(e,t){e.target===B.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._resetDualBlocks(r,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){!this._vertexCompilationState&&!i&&(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===Xs.Particle;if(this._vertexOutputNodes.length===0&&!r)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new fx,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=B.Vertex,this._fragmentCompilationState=new fx,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=B.Fragment,this._sharedData=new Ab,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const c of this._vertexOutputNodes)n.push(c),this._initializeBlock(c,this._vertexCompilationState,o,i);for(const c of this._fragmentOutputNodes)o.push(c),this._initializeBlock(c,this._fragmentCompilationState,n,i);this.optimize();for(const c of n)c.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const c of o)this._resetDualBlocks(c,this._buildId-1);for(const c of o)c.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Ei._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(O.Log("Vertex shader:"),O.Log(this._vertexCompilationState.compilationString),O.Log("Fragment shader:"),O.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const l=this.getScene().meshes;for(const c of l)if(c.subMeshes)for(const u of c.subMeshes){if(u.getMaterial()!==this||!u.materialDefines)continue;const d=u.materialDefines;d.markAllAsDirty(),d.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const h=this.getScene().prePassRenderer;h&&h.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(y.NormalKind),t.TANGENT=e.isVerticesDataPresent(y.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(y.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let h=1;h<=6;++h){const c=t["UV"+h];t["UV"+h]=e.isVerticesDataPresent(`uv${h===1?"":h}`),o=o||t["UV"+h]!==c}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;bm(this.getScene(),t,!l),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate(i=>i.getClassName()==="PrePassOutputBlock"),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter(i=>i.getClassName()==="PrePassTextureBlock"),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const s of t)i.texturesRequired.includes(s)||i.texturesRequired.push(s);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==Xs.PostProcess?(O.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,l=5){let h=this.name+this._buildId;const c=new Rd,u=new ut(h+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(u,c),xt.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(c.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,h,h):e=new De(this.name+"PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,c.toString(),o,h,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete xt.ShadersStore[h+"VertexShader"],delete xt.ShadersStore[h+"PixelShader"],h=this.name+this._buildId,c.markAllAsDirty(),d=this._buildId),this._processDefines(u,c)&&(xt.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wl.SetImmediate(()=>e.updateEffect(c.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,h,h))),this._checkInternals(f)}),e}createProceduralTexture(e,t){if(this.mode!==Xs.ProceduralTexture)return O.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new $n(i,e,null,t),r=new ut(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new Rd,o=this._processDefines(r,n);xt.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[y.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o==null?void 0:o.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(l);let h=this._buildId;return s.onBeforeGenerationObservable.add(()=>{h!==this._buildId&&(delete xt.ShadersStore[i+"VertexShader"],delete xt.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),h=this._buildId);const c=this._processDefines(r,n);c&&(xt.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wl.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[y.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),c==null?void 0:c.fallbacks,void 0),s._setEffect(l)})),this._checkInternals(l)}),s}_createEffectForParticles(e,t,i,s,r,n,o,l=""){let h=this.name+this._buildId+"_"+t;n||(n=new Rd),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new ut(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let c=this._buildId;const u=[];let d=l;if(!r){const f=this._processDefines(o,n);xt.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),d=u.join(`
`),r=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+`
`+d,f==null?void 0:f.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add(f=>{c!==this._buildId&&(delete xt.ShadersStore[h+"PixelShader"],h=this.name+this._buildId+"_"+t,n.markAllAsDirty(),c=this._buildId),u.length=0,e.fillDefines(u,t);const _=u.join(`
`);_!==d&&(n.markAllAsDirty(),d=_);const p=this._processDefines(o,n);if(p){xt.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),f=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+`
`+d,p==null?void 0:p.fallbacks,i,s,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,s,f,n,o,l);return}this._checkInternals(f)})}_checkInternals(e){if(this._sharedData.animatedInputs){const t=this.getScene(),i=t.getFrameId();if(this._animationFrame!==i){for(const s of this._sharedData.animatedInputs)s.animate(t);this._animationFrame=i}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==Xs.Particle){O.Log("Incompatible material mode");return}this._createEffectForParticles(e,as.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,as.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==Xs.Material){O.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,s){let r=null;const n=this.getScene();if(GE(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(o=>{o.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(o=>{o.prepareDefines(e,this,t,i,s)}),t.isDirty){const o=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(d=>{d.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});const l=[];this._sharedData.dynamicUniformBlocks.forEach(d=>{d.updateUniformsAndSamples(this._vertexCompilationState,this,t,l)});const h=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(d=>{h.indexOf(d)===-1&&h.push(d)});const c=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(d=>{c.indexOf(d)===-1&&c.push(d)});const u=new zo;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,u)}),r={lightDisposed:o,uniformBuffers:l,mergedUniforms:h,mergedSamplers:c,fallbacks:u}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const h=s.getFrameId();if(this._animationFrame!==h){for(const c of this._sharedData.animatedInputs)c.animate(s);this._animationFrame=h}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Rd);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some(h=>!h.isReady(e,this,n,i)))return!1;const l=this._processDefines(e,n,i,t);if(l){const h=t.effect,c=n.toString();let u=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:l.mergedUniforms,uniformBuffersNames:l.uniformBuffers,samplers:l.mergedSamplers,defines:c,fallbacks:l.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS}},o);if(u)if(this._onEffectCreatedObservable&&(D_.effect=u,D_.subMesh=t,this._onEffectCreatedObservable.notifyObservers(D_)),this.allowShaderHotSwapping&&h&&!u.isReady()){if(u=h,n.markAsUnprocessed(),l.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(u,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader
${this._vertexCompilationState.compilationString}

// Fragment shader
${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const s of this._sharedData.inputBlocks)s._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const l of o.bindableBlocks)l.bind(r,this,t,i);for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);for(const l of o.inputBlocks)l._transmit(r,s,this)}else if(!this.isFrozen)for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(t=>t.texture).map(t=>t.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Ei._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const s of this.getTextureBlocks().filter(r=>r.texture).map(r=>r.texture))s.dispose();for(const s of this.attachedBlocks)s.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),typeof this.BJSNODEMATERIALEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Ei.EditorURL;X.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new it("Position");e.setAsAttribute("position");const t=new it("World");t.setAsSystemValue(nt.World);const i=new ap("WorldPos");e.connectTo(i),t.connectTo(i);const s=new it("ViewProjection");s.setAsSystemValue(nt.ViewProjection);const r=new ap("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Gd("VertexOutput");r.connectTo(n);const o=new it("color");o.value=new xe(.8,.8,.8,1);const l=new La("FragmentOutput");o.connectTo(l),this.addOutputNode(n),this.addOutputNode(l),this._mode=Xs.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new it("Position");e.setAsAttribute("position2d");const t=new it("Constant1");t.isConstant=!0,t.value=1;const i=new zd("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Gd("VertexOutput");i.connectTo(s);const r=new it("Scale");r.visibleInInspector=!0,r.value=new Z(1,1);const n=new Of("uv0");e.connectTo(n);const o=new op("UV scale");n.connectTo(o),r.connectTo(o);const l=new $E("CurrentScreen");o.connectTo(l),l.texture=new k("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new La("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(h),this._mode=Xs.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new it("Position");e.setAsAttribute("position2d");const t=new it("Constant1");t.isConstant=!0,t.value=1;const i=new zd("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Gd("VertexOutput");i.connectTo(s);const r=new it("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=wa.Time,r.isConstant=!1;const n=new it("Color3");n.value=new q(1,1,1),n.isConstant=!1;const o=new La("FragmentOutput"),l=new zd("VectorMerger");l.visibleInInspector=!1;const h=new eS("Cos");h.operation=$i.Cos,e.connectTo(l),r.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=Xs.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new it("uv");e.setAsAttribute("particle_uv");const t=new KE("ParticleTexture");e.connectTo(t);const i=new it("Color");i.setAsAttribute("particle_color");const s=new op("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new jE("ParticleRampGradient");s.connectTo(r);const n=new QE("ColorSplitter");i.connectTo(n);const o=new qE("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const l=new La("FragmentOutput");o.connectTo(l),this.addOutputNode(l),this._mode=Xs.Particle}async loadAsync(e,t=""){return Ei.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const n of this._vertexOutputNodes)this._gatherBlocks(n,t);const s=[];for(const n of this._fragmentOutputNodes)this._gatherBlocks(n,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");
`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${Xs[this.mode]};
`;for(const n of t)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));for(const n of s)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));e=[],r+=`
// Connections
`;for(const n of this._vertexOutputNodes)r+=n._dumpCodeForOutputConnections(e);for(const n of this._fragmentOutputNodes)r+=n._dumpCodeForOutputConnections(e);r+=`
// Output nodes
`;for(const n of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName});
`;for(const n of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName});
`;return r+=`nodeMaterial.build();
`,r}serialize(e){const t=e?{}:_e.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const s of this._vertexOutputNodes)this._gatherBlocks(s,i),t.outputNodes.push(s.uniqueId);for(const s of this._fragmentOutputNodes)this._gatherBlocks(s,i),t.outputNodes.indexOf(s.uniqueId)===-1&&t.outputNodes.push(s.uniqueId)}t.blocks=[];for(const s of i)t.blocks.push(s.serialize());if(!e)for(const s of this.attachedBlocks)i.indexOf(s)===-1&&t.blocks.push(s.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){i||this.clear();const s={};for(const r of e.blocks){const n=Si(r.customType);if(n){const o=new n;o._deserialize(r,this.getScene(),t),s[r.id]=o,this.attachedBlocks.push(o)}}for(const r of this.attachedBlocks)if(r.isTeleportOut){const n=r,o=n._tempEntryPointUniqueId;o&&s[o].attachToEndpoint(n)}for(let r=0;r<e.blocks.length;r++){const n=e.blocks[r],o=s[n.id];o&&(o.inputs.length&&!i||this._restoreConnections(o,e,s))}if(e.outputNodes)for(const r of e.outputNodes)this.addOutputNode(s[r]);if(e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const o of r)s[o.blockId]&&(o.blockId=s[o.blockId].uniqueId);i&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const n=[];for(const o in s)n[o]=s[o].uniqueId;this.editorData.map=n}this.comment=e.comment,e.forceAlphaBlending!==void 0&&(this.forceAlphaBlending=e.forceAlphaBlending),e.alphaMode!==void 0&&(this.alphaMode=e.alphaMode),i||(this._mode=e.mode??Xs.Material)}loadFromSerialization(e,t="",i=!1){this.parseSerializedObject(e,t,i)}clone(e,t=!1){const i=this.serialize(),s=_e.Clone(()=>new Ei(e,this.getScene(),this.options),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((s,r)=>{i.onLoadedObservable.addOnce(()=>{s()}),i.onErrorObservable.addOnce(n=>{r(n)})}))}),Promise.all(e)}static Parse(e,t,i=""){const s=_e.Parse(()=>new Ei(e.name,t),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,s="",r=!1,n){const o=n??new Ei(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return o.parseSerializedObject(h,s),r||o.build(),o}static ParseFromSnippetAsync(e,t=Ae.LastCreatedScene,i="",s,r=!1,n=!1){return e==="_BLANK"?Promise.resolve(Ei.CreateDefault("blank",t)):new Promise((o,l)=>{const h=new yi;h.addEventListener("readystatechange",()=>{if(h.readyState==4)if(h.status==200){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||(s=_e.Parse(()=>new Ei(e,t),u,t,i),s.uniqueId=t.getUniqueId()),s.parseSerializedObject(u),s.snippetId=e;try{r||s.build()}catch(d){l(d)}n?s.whenTexturesReadyAsync().then(()=>{o(s)}).catch(d=>{l(d)}):o(s)}else l("Unable to load the snippet "+e)}),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()})}static CreateDefault(e,t){const i=new Ei(e,t);return i.setToDefault(),i.build(),i}}Ei._BuildIdGenerator=0;Ei.EditorURL=`${X._DefaultCdnUrl}/v${H.Version}/nodeEditor/babylon.nodeEditor.js`;Ei.SnippetUrl="https://snippet.babylonjs.com";Ei.IgnoreTexturesAtLoadTime=!1;E([I()],Ei.prototype,"ignoreAlpha",void 0);E([I()],Ei.prototype,"maxSimultaneousLights",void 0);E([I("mode")],Ei.prototype,"_mode",void 0);E([I("comment")],Ei.prototype,"comment",void 0);E([I()],Ei.prototype,"forceAlphaBlending",void 0);V("BABYLON.NodeMaterial",Ei);function Mm(a){const e=a.sideOrientation||le.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=(a.subdivisions||4)|0,r=a.radiusX||t,n=a.radiusY||t,o=a.radiusZ||t,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=138/1024,_=239/1024,p=60/1024,g=26/1024,x=-40/1024,T=20/1024,S=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],C=[],v=[],b=[],A=[];let P=0;const L=new Array(3),w=new Array(3);let $;for($=0;$<3;$++)L[$]=m.Zero(),w[$]=Z.Zero();for(let ne=0;ne<20;ne++){for($=0;$<3;$++){const re=c[3*ne+$];L[$].copyFromFloats(h[3*u[re]],h[3*u[re]+1],h[3*u[re]+2]),L[$].normalize(),w[$].copyFromFloats(d[2*re]*f+p+S[ne]*x,d[2*re+1]*_+g+S[ne]*T)}const oe=(re,ce,Se,Ce)=>{const ae=m.Lerp(L[0],L[2],ce/s),ie=m.Lerp(L[1],L[2],ce/s),F=s===ce?L[2]:m.Lerp(ae,ie,re/(s-ce));F.normalize();let j;if(i){const $e=m.Lerp(L[0],L[2],Ce/s),fe=m.Lerp(L[1],L[2],Ce/s);j=m.Lerp($e,fe,Se/(s-Ce))}else j=new m(F.x,F.y,F.z);j.x/=r,j.y/=n,j.z/=o,j.normalize();const se=Z.Lerp(w[0],w[2],ce/s),Ie=Z.Lerp(w[1],w[2],ce/s),Ye=s===ce?w[2]:Z.Lerp(se,Ie,re/(s-ce));v.push(F.x*r,F.y*n,F.z*o),b.push(j.x,j.y,j.z),A.push(Ye.x,mt.UseOpenGLOrientationForUV?1-Ye.y:Ye.y),C.push(P),P++};for(let re=0;re<s;re++)for(let ce=0;ce+re<s;ce++)oe(ce,re,ce+1/3,re+1/3),oe(ce+1,re,ce+1/3,re+1/3),oe(ce,re+1,ce+1/3,re+1/3),ce+re+1<s&&(oe(ce+1,re,ce+2/3,re+2/3),oe(ce+1,re+1,ce+2/3,re+2/3),oe(ce,re+1,ce+2/3,re+2/3))}le._ComputeSides(e,v,C,b,A,a.frontUVs,a.backUVs);const J=new le;return J.indices=C,J.positions=v,J.normals=b,J.uvs=A,J}function tS(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Mm(e).applyToMesh(i,e.updatable),i}le.CreateIcoSphere=Mm;z.CreateIcoSphere=(a,e,t)=>tS(a,e,t);var Ma;(function(a){a.WRIST="wrist",a.THUMB="thumb",a.INDEX="index",a.MIDDLE="middle",a.RING="ring",a.LITTLE="little"})(Ma||(Ma={}));var He;(function(a){a.WRIST="wrist",a.THUMB_METACARPAL="thumb-metacarpal",a.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",a.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",a.THUMB_TIP="thumb-tip",a.INDEX_FINGER_METACARPAL="index-finger-metacarpal",a.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",a.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",a.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",a.INDEX_FINGER_TIP="index-finger-tip",a.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",a.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",a.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",a.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",a.MIDDLE_FINGER_TIP="middle-finger-tip",a.RING_FINGER_METACARPAL="ring-finger-metacarpal",a.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",a.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",a.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",a.RING_FINGER_TIP="ring-finger-tip",a.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",a.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",a.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",a.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",a.PINKY_FINGER_TIP="pinky-finger-tip"})(He||(He={}));const ln=[He.WRIST,He.THUMB_METACARPAL,He.THUMB_PHALANX_PROXIMAL,He.THUMB_PHALANX_DISTAL,He.THUMB_TIP,He.INDEX_FINGER_METACARPAL,He.INDEX_FINGER_PHALANX_PROXIMAL,He.INDEX_FINGER_PHALANX_INTERMEDIATE,He.INDEX_FINGER_PHALANX_DISTAL,He.INDEX_FINGER_TIP,He.MIDDLE_FINGER_METACARPAL,He.MIDDLE_FINGER_PHALANX_PROXIMAL,He.MIDDLE_FINGER_PHALANX_INTERMEDIATE,He.MIDDLE_FINGER_PHALANX_DISTAL,He.MIDDLE_FINGER_TIP,He.RING_FINGER_METACARPAL,He.RING_FINGER_PHALANX_PROXIMAL,He.RING_FINGER_PHALANX_INTERMEDIATE,He.RING_FINGER_PHALANX_DISTAL,He.RING_FINGER_TIP,He.PINKY_FINGER_METACARPAL,He.PINKY_FINGER_PHALANX_PROXIMAL,He.PINKY_FINGER_PHALANX_INTERMEDIATE,He.PINKY_FINGER_PHALANX_DISTAL,He.PINKY_FINGER_TIP],wb={[Ma.WRIST]:[He.WRIST],[Ma.THUMB]:[He.THUMB_METACARPAL,He.THUMB_PHALANX_PROXIMAL,He.THUMB_PHALANX_DISTAL,He.THUMB_TIP],[Ma.INDEX]:[He.INDEX_FINGER_METACARPAL,He.INDEX_FINGER_PHALANX_PROXIMAL,He.INDEX_FINGER_PHALANX_INTERMEDIATE,He.INDEX_FINGER_PHALANX_DISTAL,He.INDEX_FINGER_TIP],[Ma.MIDDLE]:[He.MIDDLE_FINGER_METACARPAL,He.MIDDLE_FINGER_PHALANX_PROXIMAL,He.MIDDLE_FINGER_PHALANX_INTERMEDIATE,He.MIDDLE_FINGER_PHALANX_DISTAL,He.MIDDLE_FINGER_TIP],[Ma.RING]:[He.RING_FINGER_METACARPAL,He.RING_FINGER_PHALANX_PROXIMAL,He.RING_FINGER_PHALANX_INTERMEDIATE,He.RING_FINGER_PHALANX_DISTAL,He.RING_FINGER_TIP],[Ma.LITTLE]:[He.PINKY_FINGER_METACARPAL,He.PINKY_FINGER_PHALANX_PROXIMAL,He.PINKY_FINGER_PHALANX_INTERMEDIATE,He.PINKY_FINGER_PHALANX_DISTAL,He.PINKY_FINGER_TIP]};class Lb{get handMesh(){return this._handMesh}getHandPartMeshes(e){return wb[e].map(t=>this._jointMeshes[ln.indexOf(t)])}getJointMesh(e){return this._jointMeshes[ln.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this._jointTransforms=new Array(ln.length),this._jointTransformMatrices=new Float32Array(ln.length*16),this._tempJointMatrix=new D,this._jointRadii=new Float32Array(ln.length),this._scene=t[0].getScene();for(let l=0;l<this._jointTransforms.length;l++){const h=this._jointTransforms[l]=new Ke(ln[l],this._scene);h.rotationQuaternion=new Q,t[l].rotationQuaternion=new Q}i&&this.setHandMesh(i,s),this.xrController.motionController&&this.xrController.motionController.rootMesh&&this.xrController.motionController.rootMesh.dispose(!1,!0),this.xrController.onMotionControllerInitObservable.add(l=>{l._doNotLoadControllerMesh=!0})}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(s=>{s.alwaysSelectAsActiveMesh=!0}),this._handMesh.skeleton){const s=this._handMesh.skeleton;ln.forEach((r,n)=>{const o=s.getBoneIndexByName(t?t[r]:r);o!==-1&&s.bones[o].linkTransformNode(this._jointTransforms[n])})}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=ln.map(o=>s[o]||i.get(o));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let o=0;o<r.length;o++){const l=e.getJointPose(r[o],t);if(l)this._jointTransformMatrices.set(l.transform.matrix,o*16),this._jointRadii[o]=l.radius||.008;else{n=!1;break}}}n&&(ln.forEach((o,l)=>{const h=this._jointTransforms[l];D.FromArrayToRef(this._jointTransformMatrices,l*16,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,h.rotationQuaternion,h.position);const c=this._jointRadii[l]*this._jointScaleFactor,u=this._jointMeshes[l];u.isVisible=!this._handMesh&&!this._jointsInvisible,u.position.copyFrom(h.position),u.rotationQuaternion.copyFrom(h.rotationQuaternion),u.scaling.setAll(c),this._scene.useRightHandedSystem||(u.position.z*=-1,u.rotationQuaternion.z*=-1,u.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(h.position.z*=-1,h.rotationQuaternion.z*=-1,h.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){var t;this._handMesh&&(e?((t=this._handMesh.skeleton)==null||t.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Ft extends _s{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var n,o,l,h,c;const s=[],r=((n=e.jointMeshes)==null?void 0:n.sourceMesh)||tS("jointParent",Ft._ICOSPHERE_PARAMS);r.isVisible=!!((o=e.jointMeshes)!=null&&o.keepOriginalVisible);for(let u=0;u<ln.length;++u){let d=r.createInstance(`${i}-handJoint-${u}`);if((l=e.jointMeshes)!=null&&l.onHandJointMeshGenerated){const f=e.jointMeshes.onHandJointMeshGenerated(d,u,i);f&&f!==d&&(d.dispose(),d=f)}if(d.isPickable=!1,(h=e.jointMeshes)!=null&&h.enablePhysics){const f=((c=e.jointMeshes)==null?void 0:c.physicsProps)||{};d.scaling.setAll(.02);const _=f.impostorType!==void 0?f.impostorType:We.SphereImpostor;d.physicsImpostor=new We(d,_,{mass:0,...f})}d.rotationQuaternion=new Q,d.isVisible=!1,s.push(d)}t[i]=s}),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t,i){return new Promise(async s=>{var d,f,_,p,g,x;const r={};(f=(d=Ft._RightHandGLB)==null?void 0:d.meshes[1])!=null&&f.isDisposed()&&(Ft._RightHandGLB=null),(p=(_=Ft._LeftHandGLB)==null?void 0:_.meshes[1])!=null&&p.isDisposed()&&(Ft._LeftHandGLB=null);const n=!!(Ft._RightHandGLB&&Ft._LeftHandGLB),o=await Promise.all([Ft._RightHandGLB||je.ImportMeshAsync("",Ft.DEFAULT_HAND_MODEL_BASE_URL,Ft.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Ft._LeftHandGLB||je.ImportMeshAsync("",Ft.DEFAULT_HAND_MODEL_BASE_URL,Ft.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Ft._RightHandGLB=o[0],Ft._LeftHandGLB=o[1];const l=await Ei.ParseFromFileAsync("handShader",Ft.DEFAULT_HAND_MODEL_SHADER_URL,e);l.needDepthPrePass=!0,l.transparencyMode=ee.MATERIAL_ALPHABLEND,l.alphaMode=2,l.build(!1);const h={base:q.FromInts(116,63,203),fresnel:q.FromInts(149,102,229),fingerColor:q.FromInts(177,130,255),tipFresnel:q.FromInts(220,200,255),...(g=i==null?void 0:i.handMeshes)==null?void 0:g.customColors},c={base:l.getBlockByName("baseColor"),fresnel:l.getBlockByName("fresnelColor"),fingerColor:l.getBlockByName("fingerColor"),tipFresnel:l.getBlockByName("tipFresnelColor")};c.base.value=h.base,c.fresnel.value=h.fresnel,c.fingerColor.value=h.fingerColor,c.tipFresnel.value=h.tipFresnel;const u=(x=t._getBaseLayerWrapper())==null?void 0:x.isMultiview;["left","right"].forEach(T=>{const S=T=="left"?Ft._LeftHandGLB:Ft._RightHandGLB;if(!S)throw new Error("Could not load hand model");const C=S.meshes[1];C._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,u||(C.material=l.clone(`${T}HandShaderClone`,!0)),C.isVisible=!1,r[T]=C,!n&&!e.useRightHandedSystem&&S.meshes[1].rotate(Bs.Y,Math.PI)}),l.dispose(),s({left:r.left,right:r.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[He.WRIST]:`wrist_${t}`,[He.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[He.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[He.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[He.THUMB_TIP]:`thumb_tip_${t}`,[He.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[He.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[He.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[He.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[He.INDEX_FINGER_TIP]:`index_tip_${t}`,[He.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[He.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[He.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[He.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[He.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[He.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[He.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[He.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[He.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[He.RING_FINGER_TIP]:`ring_tip_${t}`,[He.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[He.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[He.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[He.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[He.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return typeof XRHand<"u"}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return e=="none"?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new G,this.onHandRemovedObservable=new G,this._attachHand=r=>{var l,h,c;if(!r.inputSource.hand||r.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const n=r.inputSource.handedness,o=new Lb(r,this._handResources.jointMeshes[n],this._handResources.handMeshes&&this._handResources.handMeshes[n],this._handResources.rigMappings&&this._handResources.rigMappings[n],(l=this.options.handMeshes)==null?void 0:l.meshesUseLeftHandedCoordinates,(h=this.options.jointMeshes)==null?void 0:h.invisible,(c=this.options.jointMeshes)==null?void 0:c.scaleFactor);this._attachedHands[r.uniqueId]=o,this._trackingHands[n]=o,this.onHandAddedObservable.notifyObservers(o)},this._detachHand=r=>{this._detachHandById(r.uniqueId)},this.xrNativeFeatureName="hand-tracking";const s=t.jointMeshes;if(s&&(typeof s.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=s.disableDefaultHandMesh),typeof s.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=s.handMeshes),typeof s.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=s.leftHandedSystemMeshes),typeof s.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const r={},n={};[[s.rigMapping.left,r],[s.rigMapping.right,n]].forEach(o=>{const l=o[0],h=o[1];l.forEach((c,u)=>{h[ln[u]]=c})}),t.handMeshes.customRigMappings={left:r,right:n}}}attach(){var e,t,i,s;return super.attach()?(this._handResources={jointMeshes:Ft._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)==null?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)==null?void 0:t.customRigMappings)||null},!((i=this.options.handMeshes)!=null&&i.customMeshes)&&!((s=this.options.handMeshes)!=null&&s.disableDefaultMeshes)&&(Ft._GenerateDefaultHandMeshesAsync(Ae.LastCreatedScene,this._xrSessionManager,this.options).then(r=>{var n,o;this._handResources.handMeshes=r,this._handResources.rigMappings={left:Ft._GenerateDefaultHandMeshRigMapping("left"),right:Ft._GenerateDefaultHandMeshRigMapping("right")},(n=this._trackingHands.left)==null||n.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),(o=this._trackingHands.right)==null||o.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)}),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add(r=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(r.newScaleFactor/r.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(r.newScaleFactor/r.previousScaleFactor))})),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0):!1}_onXRFrame(e){var t,i;(t=this._trackingHands.left)==null||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)==null||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){var s;const i=this.getHandByControllerId(e);if(i){const r=i.xrController.inputSource.handedness=="left"?"left":"right";((s=this._trackingHands[r])==null?void 0:s.xrController.uniqueId)===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){var e;return super.detach()?(Object.keys(this._attachedHands).forEach(t=>{var i;return this._detachHandById(t,(i=this.options.handMeshes)==null?void 0:i.disposeOnSessionEnd)}),(e=this.options.handMeshes)!=null&&e.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose())),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!((e=this.options.handMeshes)!=null&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Ft._RightHandGLB=null,Ft._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}Ft.Name=dt.HAND_TRACKING;Ft.Version=1;Ft.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";Ft.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";Ft.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";Ft.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";Ft._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};Ft._RightHandGLB=null;Ft._LeftHandGLB=null;fi.AddWebXRFeature(Ft.Name,(a,e)=>()=>new Ft(a,e),Ft.Version,!1);var mx;(function(a){a[a.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",a[a.RADIAL_SIDE=1]="RADIAL_SIDE",a[a.ULNAR_SIDE=2]="ULNAR_SIDE",a[a.BELOW_WRIST=3]="BELOW_WRIST"})(mx||(mx={}));var gx;(function(a){a[a.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",a[a.HAND_ROTATION=1]="HAND_ROTATION"})(gx||(gx={}));var xx;(function(a){a[a.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",a[a.PALM_UP=1]="PALM_UP",a[a.GAZE_FOCUS=2]="GAZE_FOCUS",a[a.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(xx||(xx={}));m.Zero(),m.Zero(),m.Zero(),m.Zero(),m.Zero(),m.Zero();Q.Identity();D.Identity(),D.Identity();Xi.BuildArray(10,m.Zero);Q.Identity();Xi.BuildArray(5,D.Identity);class Bb{constructor(e,t,i=3,s){this._engine=e,this._label=s,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i,s){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,s)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);t!==-1&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}const Gc=(()=>{const a=new Uint8Array(4),e=new Uint32Array(a.buffer);return!!((e[0]=1)&a[0])})();Object.defineProperty(y.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(y.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(y.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});y.prototype._rebuild=function(){var a,e;(a=this._buffer)==null||a._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};y.prototype.dispose=function(){var a;this._ownsBuffer&&this._buffer.dispose(),(a=this._alignedBuffer)==null||a.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};y.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};y.prototype._alignBuffer=function(){var u;const a=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!a)return;const e=y.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,s=this._maxVerticesCount,n=s*t/e;let o;if(Array.isArray(a)){const d=new Float32Array(a);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else a instanceof ArrayBuffer?o=new DataView(a,0,a.byteLength):o=new DataView(a.buffer,a.byteOffset,a.byteLength);let l;this.type===y.BYTE?l=new Int8Array(n):this.type===y.UNSIGNED_BYTE?l=new Uint8Array(n):this.type===y.SHORT?l=new Int16Array(n):this.type===y.UNSIGNED_SHORT?l=new Uint16Array(n):this.type===y.INT?l=new Int32Array(n):this.type===y.UNSIGNED_INT?l=new Uint32Array(n):l=new Float32Array(n);const h=this.getSize();let c=this.byteOffset;for(let d=0;d<s;++d){for(let f=0;f<h;++f)switch(this.type){case y.BYTE:l[d*i+f]=o.getInt8(c+f);break;case y.UNSIGNED_BYTE:l[d*i+f]=o.getUint8(c+f);break;case y.SHORT:l[d*i+f]=o.getInt16(c+f*2,Gc);break;case y.UNSIGNED_SHORT:l[d*i+f]=o.getUint16(c+f*2,Gc);break;case y.INT:l[d*i+f]=o.getInt32(c+f*4,Gc);break;case y.UNSIGNED_INT:l[d*i+f]=o.getUint32(c+f*4,Gc);break;case y.FLOAT:l[d*i+f]=o.getFloat32(c+f*4,Gc);break}c+=this.byteStride}(u=this._alignedBuffer)==null||u.dispose(),this._alignedBuffer=new Ji(this.engine,l,!1,t,!1,this.getIsInstanced(),!0,this.instanceDivisor,(this._label??"VertexBuffer")+"_aligned")};class Ff{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new G,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Sc.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}E([I()],Ff.prototype,"wheelPrecisionX",void 0);E([I()],Ff.prototype,"wheelPrecisionY",void 0);E([I()],Ff.prototype,"wheelPrecisionZ",void 0);class Dm{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var u,d;const l=o.event,h=l.pointerType==="touch";if(o.type!==Re.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;const c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const f=l.movementX,_=l.movementY;this.onTouch(null,f,_),this._pointA=null,this._pointB=null}else{if(o.type!==Re.POINTERDOWN&&h&&((u=this._pointA)==null?void 0:u.pointerId)!==l.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==l.pointerId)return;if(o.type===Re.POINTERDOWN&&(this._currentActiveButton===-1||h)){try{c==null||c.setPointerCapture(l.pointerId)}catch{}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else return;this._currentActiveButton===-1&&!h&&(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===Re.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===Re.POINTERUP&&(this._currentActiveButton===l.button||h)){try{c==null||c.releasePointerCapture(l.pointerId)}catch{}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(s!==0||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===Re.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){const f=l.clientX-this._pointA.x,_=l.clientY-this._pointA.y;this.onTouch(this._pointA,f,_),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const f=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;f.x=l.clientX,f.y=l.clientY;const _=this._pointA.x-this._pointB.x,p=this._pointA.y-this._pointB.y,g=_*_+p*p,x={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,s,g,r,x),r=x,s=g}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE|Re.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&X.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&X.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}E([I()],Dm.prototype,"buttons",void 0);var Ds={};class wf{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){O.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=ve.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const i in this.attached){const s=this.attached[i],r=_e.Serialize(s);t[s.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=Ds[i];if(s){const r=t[i],n=_e.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=Ds[this.attached[i].getClassName()];if(s){const r=_e.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class us{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=us.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}us.GAMEPAD=0;us.GENERIC=1;us.XBOX=2;us.POSE_ENABLED=3;us.DUALSHOCK=4;class Ub extends us{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new G,this.onButtonUpObservable=new G,this.type=us.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()}}class Lf{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return this._yAxisScale!==1}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(t=>{t.type!==us.POSE_ENABLED&&(!this.gamepad||t.type===us.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(us.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(t.x!=0){const s=t.x/this.gamepadRotationSensibility;s!=0&&Math.abs(s)>.005&&(e.inertialAlphaOffset+=s)}if(t.y!=0){const s=t.y/this.gamepadRotationSensibility*this._yAxisScale;s!=0&&Math.abs(s)>.005&&(e.inertialBetaOffset+=s)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const s=i.y/this.gamepadMoveSensibility;s!=0&&Math.abs(s)>.005&&(this.camera.inertialRadiusOffset-=s)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}E([I()],Lf.prototype,"gamepadRotationSensibility",void 0);E([I()],Lf.prototype,"gamepadMoveSensibility",void 0);Ds.ArcRotateCameraGamepadInput=Lf;class vn{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Ja.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t];this.keysLeft.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:this.keysUp.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:this.keysRight.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:this.keysDown.indexOf(i)!==-1?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:this.keysReset.indexOf(i)!==-1&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}E([I()],vn.prototype,"keysUp",void 0);E([I()],vn.prototype,"keysDown",void 0);E([I()],vn.prototype,"keysLeft",void 0);E([I()],vn.prototype,"keysRight",void 0);E([I()],vn.prototype,"keysReset",void 0);E([I()],vn.prototype,"panningSensibility",void 0);E([I()],vn.prototype,"zoomingSensibility",void 0);E([I()],vn.prototype,"useAltToZoom",void 0);E([I()],vn.prototype,"angularSpeed",void 0);Ds.ArcRotateCameraKeyboardMoveInput=vn;const Vb=40;class Qu{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new m(0,0,0),this._globalOffset=new m(0,0,0),this._inertialPanning=m.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=0;const s=e*.01*this.wheelDeltaPercentage*t;return e>0?i=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Sc.DOM_DELTA_LINE?Vb:1,n=-(i.deltaY*r);if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)o-=l,l*=this.camera.inertia;o=ge.Clamp(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,o)}}else s=n/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Ks.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,D.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=m.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const l=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i<l&&(e=(t.radius-l)*i-t.inertialRadiusOffset)}if(t.upperRadiusLimit){const l=t.upperRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i>l&&(e=(t.radius-l)*i-t.inertialRadiusOffset)}const r=e/i/t.radius,n=this._getPosition(),o=U.Vector3[6];n.subtractToRef(t.target,o),o.scaleInPlace(r),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<rt&&(e.x=0),Math.abs(e.y)<rt&&(e.y=0),Math.abs(e.z)<rt&&(e.z=0)}}E([I()],Qu.prototype,"wheelPrecision",void 0);E([I()],Qu.prototype,"zoomToMouseLocation",void 0);E([I()],Qu.prototype,"wheelDeltaPercentage",void 0);Ds.ArcRotateCameraMouseWheelInput=Qu;class cr extends Dm{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(this.panningSensibility!==0&&e&&t){const i=t.x-e.x,s=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||cr.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,s,r,n){i===0&&r===null||s===0&&n===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(r,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(s)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}cr.MinimumRadiusForPinch=.001;E([I()],cr.prototype,"buttons",void 0);E([I()],cr.prototype,"angularSensibilityX",void 0);E([I()],cr.prototype,"angularSensibilityY",void 0);E([I()],cr.prototype,"pinchPrecision",void 0);E([I()],cr.prototype,"pinchDeltaPercentage",void 0);E([I()],cr.prototype,"useNaturalPinchZoom",void 0);E([I()],cr.prototype,"pinchZoom",void 0);E([I()],cr.prototype,"panningSensibility",void 0);E([I()],cr.prototype,"multiTouchPanning",void 0);E([I()],cr.prototype,"multiTouchPanAndZoom",void 0);Ds.ArcRotateCameraPointersInput=cr;class Om extends wf{constructor(e){super(e)}addMouseWheel(){return this.add(new Qu),this}addPointers(){return this.add(new cr),this}addKeyboard(){return this.add(new vn),this}}Om.prototype.addVRDeviceOrientation=function(){return this.add(new iS),this};class iS{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&(typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t.addEventListener("deviceorientation",this._deviceOrientationHandler):X.Warn("Permission not granted.")}).catch(i=>{X.Error(i)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){e.alpha!==null&&(this._alpha=(+e.alpha|0)*this.alphaCorrection),e.gamma!==null&&(this._gamma=(+e.gamma|0)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ds.ArcRotateCameraVRDeviceOrientationInput=iS;class lo{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(t.type===Ja.KEYDOWN)(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysForward.indexOf(i.keyCode)!==-1||this.keysBackward.indexOf(i.keyCode)!==-1||this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),e||i.preventDefault()}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=e._computeLocalCameraSpeed();this.keysForward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,s):this.keysBackward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,-s):this.keysUp.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,s,0):this.keysDown.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,-s,0):this.keysRight.indexOf(i)!==-1?e._localDirection.copyFromFloats(s,0,0):this.keysLeft.indexOf(i)!==-1&&e._localDirection.copyFromFloats(-s,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),m.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}}E([I()],lo.prototype,"keysForward",void 0);E([I()],lo.prototype,"keysBackward",void 0);E([I()],lo.prototype,"keysUp",void 0);E([I()],lo.prototype,"keysDown",void 0);E([I()],lo.prototype,"keysRight",void 0);E([I()],lo.prototype,"keysLeft",void 0);Ds.FlyCameraKeyboardInput=lo;class Bf{constructor(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(t=>{this._pointerInput(t)},Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,s=this.camera.getEngine();if(!this.touchEnabled&&t.pointerType==="touch"||e.type!==Re.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const r=t.target;if(e.type===Re.POINTERDOWN){try{r==null||r.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),s.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Re.POINTERUP){try{r==null||r.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Re.POINTERMOVE){if(!this._previousPosition){s.isPointerLock&&this._onMouseMove(e.event);return}const n=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(n,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const s=e.movementX,r=e.movementY;this._rotateCamera(s,r),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=i._calculateHandednessMultiplier();e*=s;const r=e/this.angularSensibility,n=t/this.angularSensibility,o=Q.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(h=>h===this.activeButton)&&(l=Q.RotationAxis(Bs.X,n),o.multiplyInPlace(l)),this.buttonsYaw.some(h=>h===this.activeButton)){l=Q.RotationAxis(Bs.Y,r),o.multiplyInPlace(l);const h=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-h<i.rotation.z&&i.rotation.z<h){const c=i.bankedTurnMultiplier*-r;l=Q.RotationAxis(Bs.Z,c),o.multiplyInPlace(l)}}this.buttonsRoll.some(h=>h===this.activeButton)&&(l=Q.RotationAxis(Bs.Z,-r),i._trackRoll-=r,o.multiplyInPlace(l)),o.toEulerAnglesToRef(i.rotation)}}E([I()],Bf.prototype,"buttons",void 0);E([I()],Bf.prototype,"angularSensibility",void 0);Ds.FlyCameraMouseInput=Bf;class As{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Ja.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysHeightOffsetIncr.indexOf(i.keyCode)!==-1||this.keysHeightOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetIncr.indexOf(i.keyCode)!==-1||this.keysRotationOffsetDecr.indexOf(i.keyCode)!==-1||this.keysRadiusIncr.indexOf(i.keyCode)!==-1||this.keysRadiusDecr.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach(e=>{this.keysHeightOffsetIncr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:this.keysHeightOffsetDecr.indexOf(e)!==-1&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:this.keysRotationOffsetIncr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRotationOffsetDecr.indexOf(e)!==-1&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):this.keysRadiusIncr.indexOf(e)!==-1&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:this.keysRadiusDecr.indexOf(e)!==-1&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}E([I()],As.prototype,"keysHeightOffsetIncr",void 0);E([I()],As.prototype,"keysHeightOffsetDecr",void 0);E([I()],As.prototype,"keysHeightOffsetModifierAlt",void 0);E([I()],As.prototype,"keysHeightOffsetModifierCtrl",void 0);E([I()],As.prototype,"keysHeightOffsetModifierShift",void 0);E([I()],As.prototype,"keysRotationOffsetIncr",void 0);E([I()],As.prototype,"keysRotationOffsetDecr",void 0);E([I()],As.prototype,"keysRotationOffsetModifierAlt",void 0);E([I()],As.prototype,"keysRotationOffsetModifierCtrl",void 0);E([I()],As.prototype,"keysRotationOffsetModifierShift",void 0);E([I()],As.prototype,"keysRadiusIncr",void 0);E([I()],As.prototype,"keysRadiusDecr",void 0);E([I()],As.prototype,"keysRadiusModifierAlt",void 0);E([I()],As.prototype,"keysRadiusModifierCtrl",void 0);E([I()],As.prototype,"keysRadiusModifierShift",void 0);E([I()],As.prototype,"heightSensibility",void 0);E([I()],As.prototype,"rotationSensibility",void 0);E([I()],As.prototype,"radiusSensibility",void 0);Ds.FollowCameraKeyboardMoveInput=As;class Wo{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&O.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=r*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=r*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=r*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}E([I()],Wo.prototype,"axisControlRadius",void 0);E([I()],Wo.prototype,"axisControlHeight",void 0);E([I()],Wo.prototype,"axisControlRotation",void 0);E([I()],Wo.prototype,"wheelPrecision",void 0);E([I()],Wo.prototype,"wheelDeltaPercentage",void 0);Ds.FollowCameraMouseWheelInput=Wo;class ur extends Dm{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(i===0&&r===null||s===0&&n===null)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!==0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&O.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&O.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&O.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}E([I()],ur.prototype,"angularSensibilityX",void 0);E([I()],ur.prototype,"angularSensibilityY",void 0);E([I()],ur.prototype,"pinchPrecision",void 0);E([I()],ur.prototype,"pinchDeltaPercentage",void 0);E([I()],ur.prototype,"axisXControlRadius",void 0);E([I()],ur.prototype,"axisXControlHeight",void 0);E([I()],ur.prototype,"axisXControlRotation",void 0);E([I()],ur.prototype,"axisYControlRadius",void 0);E([I()],ur.prototype,"axisYControlHeight",void 0);E([I()],ur.prototype,"axisYControlRotation",void 0);E([I()],ur.prototype,"axisPinchControlRadius",void 0);E([I()],ur.prototype,"axisPinchControlHeight",void 0);E([I()],ur.prototype,"axisPinchControlRotation",void 0);Ds.FollowCameraPointersInput=ur;class zr{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const i=t.event;if(!i.metaKey){if(t.type===Ja.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=e._computeLocalCameraSpeed();this.keysLeft.indexOf(i)!==-1?e._localDirection.copyFromFloats(-s,0,0):this.keysUp.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,s):this.keysRight.indexOf(i)!==-1?e._localDirection.copyFromFloats(s,0,0):this.keysDown.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,0,-s):this.keysUpward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,s,0):this.keysDownward.indexOf(i)!==-1?e._localDirection.copyFromFloats(0,-s,0):this.keysRotateLeft.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):this.keysRotateRight.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):this.keysRotateUp.indexOf(i)!==-1?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):this.keysRotateDown.indexOf(i)!==-1&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),m.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){const e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}}E([I()],zr.prototype,"keysUp",void 0);E([I()],zr.prototype,"keysUpward",void 0);E([I()],zr.prototype,"keysDown",void 0);E([I()],zr.prototype,"keysDownward",void 0);E([I()],zr.prototype,"keysLeft",void 0);E([I()],zr.prototype,"keysRight",void 0);E([I()],zr.prototype,"rotationSpeed",void 0);E([I()],zr.prototype,"keysRotateLeft",void 0);E([I()],zr.prototype,"keysRotateRight",void 0);E([I()],zr.prototype,"keysRotateUp",void 0);E([I()],zr.prototype,"keysRotateDown",void 0);Ds.FreeCameraKeyboardMoveInput=zr;class Uf{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new G,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=s=>{const r=s.event,n=r.pointerType==="touch";if(!this.touchEnabled&&n||s.type!==Re.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const o=r.target;if(s.type===Re.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{o==null||o.setPointerCapture(r.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===Re.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o==null||o.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===Re.POINTERMOVE&&(this._activePointerId===r.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const l=this.camera._calculateHandednessMultiplier(),h=(r.clientX-this._previousPosition.x)*l,c=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=h/this.angularSensibility,this.camera.cameraRotation.x+=c/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:h,offsetY:c}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}}),this._onMouseMove=s=>{if(!t.isPointerLock)return;const r=this.camera._calculateHandednessMultiplier(),n=s.movementX*r;this.camera.cameraRotation.y+=n/this.angularSensibility;const o=s.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE),i&&(this._contextMenuBind=s=>this.onContextMenu(s),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}E([I()],Uf.prototype,"buttons",void 0);E([I()],Uf.prototype,"angularSensibility",void 0);Ds.FreeCameraMouseInput=Uf;var Kt;(function(a){a[a.MoveRelative=0]="MoveRelative",a[a.RotateRelative=1]="RotateRelative",a[a.MoveScene=2]="MoveScene"})(Kt||(Kt={}));class bn extends Ff{constructor(){super(...arguments),this._moveRelative=m.Zero(),this._rotateRelative=m.Zero(),this._moveScene=m.Zero(),this._wheelXAction=Kt.MoveRelative,this._wheelXActionCoordinate=Eo.X,this._wheelYAction=Kt.MoveRelative,this._wheelYActionCoordinate=Eo.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Kt.MoveRelative||(this._wheelXAction=Kt.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Kt.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Kt.MoveRelative||(this._wheelYAction=Kt.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Kt.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Kt.MoveRelative||(this._wheelZAction=Kt.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Kt.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Kt.RotateRelative||(this._wheelXAction=Kt.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Kt.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Kt.RotateRelative||(this._wheelYAction=Kt.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Kt.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Kt.RotateRelative||(this._wheelZAction=Kt.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Kt.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Kt.MoveScene||(this._wheelXAction=Kt.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Kt.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Kt.MoveScene||(this._wheelYAction=Kt.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Kt.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Kt.MoveScene||(this._wheelZAction=Kt.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Kt.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=D.Zero();this.camera.getViewMatrix().invertToRef(e);const t=m.Zero();m.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let s=null;switch(t){case Kt.MoveRelative:s=this._moveRelative;break;case Kt.RotateRelative:s=this._rotateRelative;break;case Kt.MoveScene:s=this._moveScene;break}switch(i){case Eo.X:s.set(e,0,0);break;case Eo.Y:s.set(0,e,0);break;case Eo.Z:s.set(0,0,e);break}}}E([I()],bn.prototype,"wheelXMoveRelative",null);E([I()],bn.prototype,"wheelYMoveRelative",null);E([I()],bn.prototype,"wheelZMoveRelative",null);E([I()],bn.prototype,"wheelXRotateRelative",null);E([I()],bn.prototype,"wheelYRotateRelative",null);E([I()],bn.prototype,"wheelZRotateRelative",null);E([I()],bn.prototype,"wheelXMoveScene",null);E([I()],bn.prototype,"wheelYMoveScene",null);E([I()],bn.prototype,"wheelZMoveScene",null);Ds.FreeCameraMouseWheelInput=bn;class Vf{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=X.IsSafari()}attachControl(e){e=X.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r=s.pointerType==="mouse"||this._isSafari&&typeof s.pointerType>"u";if(!(!this.allowMouse&&r)){if(i.type===Re.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),this._pointerPressed.length!==1)return;t={x:s.clientX,y:s.clientY}}else if(i.type===Re.POINTERUP){e||s.preventDefault();const n=this._pointerPressed.indexOf(s.pointerId);if(n===-1||(this._pointerPressed.splice(n,1),n!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Re.POINTERMOVE){if(e||s.preventDefault(),!t||this._pointerPressed.indexOf(s.pointerId)!=0)return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE),this._onLostFocus){const s=this.camera.getEngine().getInputElement();s&&s.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const s=e._computeLocalCameraSpeed(),r=new m(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);D.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(m.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}E([I()],Vf.prototype,"touchAngularSensibility",void 0);E([I()],Vf.prototype,"touchMoveSensibility",void 0);Ds.FreeCameraTouchInput=Vf;class kf extends wf{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new zr),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Uf(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new bn,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Vf),this}clear(){super.clear(),this._mouseInput=null}}kf.prototype.addDeviceOrientation=function(a){return this._deviceOrientationInput||(this._deviceOrientationInput=new sS,a&&(this._deviceOrientationInput.smoothFactor=a),this.add(this._deviceOrientationInput)),this};class sS{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout(()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(n=>{n=="granted"?window.addEventListener("deviceorientation",r):X.Warn("Permission not granted.")}).catch(n=>{X.Error(n)}):window.addEventListener("deviceorientation",r)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new Q,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new G,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-X.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=e.alpha!==null?X.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?X.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?X.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=e.alpha!==null?e.alpha:0,this._beta=e.beta!==null?e.beta:0,this._gamma=e.gamma!==null?e.gamma:0),e.alpha!==null&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new Q(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,this._camera!=null&&!this._camera.rotationQuaternion&&(this._camera.rotationQuaternion=new Q),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(i=>{i==="granted"?t():X.Warn("Permission not granted.")}).catch(i=>{X.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(Q.RotationYawPitchRollToRef(X.ToRadians(this._alpha),X.ToRadians(this._beta),-X.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ds.FreeCameraDeviceOrientationInput=sS;class Gf{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=D.Identity(),this._deltaTransform=m.Zero(),this._vector3=m.Zero(),this._vector2=Z.Zero()}get invertYAxis(){return this._yAxisScale!==1}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(t=>{t.type!==us.POSE_ENABLED&&(!this.gamepad||t.type===us.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(us.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;this.gamepadMoveSensibility!==0&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&this.gamepadAngularSensibility!==0?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):D.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*s,0,-t.y*s),m.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}E([I()],Gf.prototype,"gamepadAngularSensibility",void 0);E([I()],Gf.prototype,"gamepadMoveSensibility",void 0);Ds.FreeCameraGamepadInput=Gf;var rs;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(rs||(rs={}));class Be{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...Be._GetDefaultOptions(),...t};if(e?this._leftJoystick=!0:this._leftJoystick=!1,Be._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=rs.X,this._axisTargetedByUpAndDown=rs.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new ip,this.deltaPosition=m.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Be._VJCanvasWidth=window.innerWidth,Be._VJCanvasHeight=window.innerHeight,Be.Canvas&&(Be.Canvas.width=Be._VJCanvasWidth,Be.Canvas.height=Be._VJCanvasHeight),Be._HalfWidth=Be._VJCanvasWidth/2},!Be.Canvas){window.addEventListener("resize",this._onResize,!1),Be.Canvas=document.createElement("canvas"),Be._VJCanvasWidth=window.innerWidth,Be._VJCanvasHeight=window.innerHeight,Be.Canvas.width=window.innerWidth,Be.Canvas.height=window.innerHeight,Be.Canvas.style.width="100%",Be.Canvas.style.height="100%",Be.Canvas.style.position="absolute",Be.Canvas.style.backgroundColor="transparent",Be.Canvas.style.top="0px",Be.Canvas.style.left="0px",Be.Canvas.style.zIndex="5",Be.Canvas.style.touchAction="none",Be.Canvas.setAttribute("touch-action","none");const s=Be.Canvas.getContext("2d");if(!s)throw new Error("Unable to create canvas for virtual joystick");Be._VJCanvasContext=s,Be._VJCanvasContext.strokeStyle="#ffffff",Be._VJCanvasContext.lineWidth=2,document.body.appendChild(Be.Canvas)}Be._HalfWidth=Be.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&Be._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Z(0,0),this._joystickPreviousPointerPos=new Z(0,0),this._joystickPointerStartPos=new Z(0,0),this._deltaJoystickVector=new Z(0,0),this._onPointerDownHandlerRef=s=>{this._onPointerDown(s)},this._onPointerMoveHandlerRef=s=>{this._onPointerMove(s)},this._onPointerUpHandlerRef=s=>{this._onPointerUp(s)},Be.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Be.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Be.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Be.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Be.Canvas.addEventListener("contextmenu",s=>{s.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),this._leftJoystick===!0?t=e.clientX<Be._HalfWidth:t=e.clientX>Be._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):Be._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const n=new Z(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),o=n.length();o>this.containerSize&&n.scaleInPlace(this.containerSize/o),this._joystickPointerPos.x=this._joystickPointerStartPos.x+n.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+n.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0<Be._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(Be._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(Be._HalfWidth,this._joystickPointerPos.x));const i=(this.reverseLeftRight?-1:1)*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case rs.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case rs.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case rs.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i));break}const r=(this.reverseUpDown?1:-1)*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case rs.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case rs.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case rs.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r));break}}else{const t=this._touches.get(e.pointerId.toString());t&&(t.x=e.clientX,t.y=e.clientY)}}_onPointerUp(e){if(this._joystickPointerId==e.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{const t=this._touches.get(e.pointerId.toString());t&&Be._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())}setJoystickColor(e){this._joystickColor=e}set containerSize(e){this._joystickContainerSize=e,this._clearContainerSize=~~(this._joystickContainerSize*2.1),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)}get containerSize(){return this._joystickContainerSize}set puckSize(e){this._joystickPuckSize=e,this._clearPuckSize=~~(this._joystickPuckSize*2.1),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)}get puckSize(){return this._joystickPuckSize}clearPosition(){this.alwaysVisible=!1,this._joystickPosition=null}set alwaysVisible(e){this._alwaysVisible!==e&&(e&&this._joystickPosition?(Be._AlwaysVisibleSticks++,this._alwaysVisible=!0):(Be._AlwaysVisibleSticks--,this._alwaysVisible=!1))}get alwaysVisible(){return this._alwaysVisible}setPosition(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new Z(e,t)}setActionOnTouch(e){this._action=e}setAxisForLeftRight(e){switch(e){case rs.X:case rs.Y:case rs.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=rs.X;break}}setAxisForUpDown(e){switch(e){case rs.X:case rs.Y:case rs.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=rs.Y;break}}_clearPreviousDraw(){const e=this._joystickPosition||this._joystickPointerStartPos;Be._VJCanvasContext.clearRect(e.x-this._clearContainerSizeOffset,e.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),Be._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)}setContainerImage(e){const t=new Image;t.src=e,t.onload=()=>this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?Be._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(Be._VJCanvasContext.beginPath(),Be._VJCanvasContext.strokeStyle=this._joystickColor,Be._VJCanvasContext.lineWidth=2,Be._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),Be._VJCanvasContext.stroke(),Be._VJCanvasContext.closePath(),Be._VJCanvasContext.beginPath(),Be._VJCanvasContext.lineWidth=6,Be._VJCanvasContext.strokeStyle=this._joystickColor,Be._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),Be._VJCanvasContext.stroke(),Be._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Be._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(Be._VJCanvasContext.beginPath(),Be._VJCanvasContext.strokeStyle=this._joystickColor,Be._VJCanvasContext.lineWidth=2,Be._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),Be._VJCanvasContext.stroke(),Be._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(Be._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Be._VJCanvasContext.beginPath(),Be._VJCanvasContext.fillStyle="white",Be._VJCanvasContext.beginPath(),Be._VJCanvasContext.strokeStyle="red",Be._VJCanvasContext.lineWidth=6,Be._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),Be._VJCanvasContext.stroke(),Be._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){Be.Canvas&&(Be.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Be.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Be.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Be.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Be.Canvas),Be.Canvas=null),this._released=!0}}Be._GlobalJoystickIndex=0;Be._AlwaysVisibleSticks=0;kf.prototype.addVirtualJoystick=function(){return this.add(new rS),this};class rS{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=D.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=m.TransformCoordinates(new m(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new Be(!0),this._leftjoystick.setAxisForUpDown(rs.Z),this._leftjoystick.setAxisForLeftRight(rs.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Be(!1),this._rightjoystick.setAxisForUpDown(rs.X),this._rightjoystick.setAxisForLeftRight(rs.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ds.FreeCameraVirtualJoystickInput=rS;Ct.AddNodeConstructor("TargetCamera",(a,e)=>()=>new Ai(a,m.Zero(),e));class Ai extends ve{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=m.Zero(),this._tmpTargetVector=m.Zero(),this.cameraDirection=new m(0,0,0),this.cameraRotation=new Z(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new Q,this.rotation=new m(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=m.Zero(),this._initialFocalDistance=1,this._viewMatrix=D.Zero(),this._camMatrix=D.Zero(),this._cameraTransformMatrix=D.Zero(),this._cameraRotationMatrix=D.Zero(),this._referencePoint=new m(0,0,1),this._transformedReferencePoint=m.Zero(),this._deferredPositionUpdate=new m,this._deferredRotationQuaternionUpdate=new Q,this._deferredRotationUpdate=new m,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=m.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Q(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=rt),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),D.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&Q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(U.Matrix[0]),m.TransformNormalToRef(this.cameraDirection,U.Matrix[0],U.Vector3[0]),this._deferredPositionUpdate.addInPlace(U.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(Q.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))),t&&(Math.abs(this.cameraDirection.x)<this.speed*rt&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*rt&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*rt&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*rt&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*rt&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):D.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return m.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),m.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Bs.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(Q.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Bs.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){const s=this.parent.getWorldMatrix();m.TransformCoordinatesToRef(e,s,this._globalPosition),m.TransformCoordinatesToRef(t,s,this._tmpTargetVector),m.TransformNormalToRef(i,s,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?D.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):D.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?D.LookAtRHToRef(e,t,i,this._viewMatrix):D.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){const s=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(s,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==ve.RIG_MODE_NONE){const i=new Ai(e,this.position.clone(),this.getScene());return i.isRigCamera=!0,i.rigParent=this,this.cameraRigMode===ve.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new Q),i._cameraRigParams={},i.rotationQuaternion=new Q),i.mode=this.mode,i.orthoLeft=this.orthoLeft,i.orthoRight=this.orthoRight,i.orthoTop=this.orthoTop,i.orthoBottom=this.orthoBottom,i}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:{const i=this.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,s=this.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,t);break}case ve.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position);break}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,Ai._TargetFocalPoint),Ai._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const s=Ai._TargetFocalPoint.addInPlace(this.position);D.TranslationToRef(-s.x,-s.y,-s.z,Ai._TargetTransformMatrix),Ai._TargetTransformMatrix.multiplyToRef(D.RotationAxis(t.upVector,e),Ai._RigCamTransformMatrix),D.TranslationToRef(s.x,s.y,s.z,Ai._TargetTransformMatrix),Ai._RigCamTransformMatrix.multiplyToRef(Ai._TargetTransformMatrix,Ai._RigCamTransformMatrix),m.TransformCoordinatesToRef(this.position,Ai._RigCamTransformMatrix,t.position),t.setTarget(s)}getClassName(){return"TargetCamera"}}Ai._RigCamTransformMatrix=new D;Ai._TargetTransformMatrix=new D;Ai._TargetFocalPoint=new m;E([bs()],Ai.prototype,"rotation",void 0);E([I()],Ai.prototype,"speed",void 0);E([Wu("lockedTargetId")],Ai.prototype,"lockedTarget",void 0);class qs extends Ai{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new m(.5,1,.5),this.ellipsoidOffset=new m(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=m.Zero(),this._diffPosition=m.Zero(),this._newPosition=m.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,o=null)=>{this._newPosition.copyFrom(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>H.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new kf(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=X.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new m(0,0,0),this.cameraRotation=new Z(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=m.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=m.Zero(),this._transformedDirection=m.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}E([bs()],qs.prototype,"ellipsoid",void 0);E([bs()],qs.prototype,"ellipsoidOffset",void 0);E([I()],qs.prototype,"checkCollisions",void 0);E([I()],qs.prototype,"applyGravity",void 0);Ct.AddNodeConstructor("TouchCamera",(a,e)=>()=>new nS(a,m.Zero(),e));class nS extends qs{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Ct.AddNodeConstructor("ArcRotateCamera",(a,e)=>()=>new $t(a,0,0,1,m.Zero(),e));class $t extends Ai{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new D,this._upToYMatrix=new D,this._upVector=m.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){D.RotationAlignToRef(m.UpReadOnly,this._upVector,this._yToUpMatrix),D.RotationAlignToRef(this._upVector,m.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Mo,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new rr,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new bb,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,m.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=m.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Z.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new D,this.panningAxis=new m(1,1,0),this._transformedDirection=new m,this.mapPanning=!1,this.onMeshTargetChangedObservable=new G,this.checkCollisions=!1,this.collisionRadius=new m(.5,.5,.5),this._previousPosition=m.Zero(),this._collisionVelocity=m.Zero(),this._newPosition=m.Zero(),this._computationVector=m.Zero(),this._onCollisionPositionChange=(l,h,c=null)=>{c?(this.setPosition(h),this.onCollide&&this.onCollide(c)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),d=Math.sin(this.alpha),f=Math.cos(this.beta);let _=Math.sin(this.beta);_===0&&(_=1e-4);const p=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*_,this.radius*f,this.radius*d*_),p.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let g=this.upVector;this.allowUpsideDown&&this.beta<0&&(g=g.clone(),g=g.negate()),this._computeViewMatrix(this._position,p,g),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=m.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Om(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=Z.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,s=2){const r=arguments;t=X.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,typeof r[0]=="boolean"&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<rt&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<rt&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*rt&&(this.inertialRadiusOffset=0)}if(this.inertialPanningX!==0||this.inertialPanningY!==0){const e=new m(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),m.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){const t=this.upVector,i=m.CrossToRef(this._transformedDirection,t,this._transformedDirection);m.CrossToRef(t,i,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit)this._transformedDirection.addInPlace(this._target),m.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection);else{if(this.parent){const t=U.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.transposeToRef(t),m.TransformCoordinatesToRef(this._transformedDirection,t,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*rt&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*rt&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){this.lowerBetaLimit===null||this.lowerBetaLimit===void 0?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),this.upperBetaLimit===null||this.upperBetaLimit===void 0?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit!==null&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),this.upperRadiusLimit!==null&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&m.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);s===0&&(s=1e-4),this.radius===0&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&m.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const n=this.getScene().collisionCoordinator;this._collider||(this._collider=n.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,n.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let n=this.upVector;this.allowUpsideDown&&s<0&&(n=n.negate()),this._computeViewMatrix(this._position,r,n),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=z.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(e.min===void 0){const r=e||this.getScene().meshes;i=z.MinMax(r),s=m.Distance(i.min,i.max)}else{const r=e;i=r,s=r.distance}this._target=z.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new $t(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=m.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*n,c=s*.5*i,u=c*Math.sqrt(1+1/(l*l)),d=c*Math.sqrt(1+1/(o*o));return Math.max(u,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}E([I()],$t.prototype,"alpha",void 0);E([I()],$t.prototype,"beta",void 0);E([I()],$t.prototype,"radius",void 0);E([I()],$t.prototype,"overrideCloneAlphaBetaRadius",void 0);E([bs("target")],$t.prototype,"_target",void 0);E([Wu("targetHost")],$t.prototype,"_targetHost",void 0);E([I()],$t.prototype,"inertialAlphaOffset",void 0);E([I()],$t.prototype,"inertialBetaOffset",void 0);E([I()],$t.prototype,"inertialRadiusOffset",void 0);E([I()],$t.prototype,"lowerAlphaLimit",void 0);E([I()],$t.prototype,"upperAlphaLimit",void 0);E([I()],$t.prototype,"lowerBetaLimit",void 0);E([I()],$t.prototype,"upperBetaLimit",void 0);E([I()],$t.prototype,"lowerRadiusLimit",void 0);E([I()],$t.prototype,"upperRadiusLimit",void 0);E([I()],$t.prototype,"inertialPanningX",void 0);E([I()],$t.prototype,"inertialPanningY",void 0);E([I()],$t.prototype,"pinchToPanMaxDistance",void 0);E([I()],$t.prototype,"panningDistanceLimit",void 0);E([bs()],$t.prototype,"panningOriginTarget",void 0);E([I()],$t.prototype,"panningInertia",void 0);E([I()],$t.prototype,"zoomToMouseLocation",null);E([I()],$t.prototype,"zoomOnFactor",void 0);E([hm()],$t.prototype,"targetScreenOffset",void 0);E([I()],$t.prototype,"allowUpsideDown",void 0);E([I()],$t.prototype,"useInputToRestoreState",void 0);Ct.AddNodeConstructor("DeviceOrientationCamera",(a,e)=>()=>new Nm(a,m.Zero(),e));class Nm extends qs{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new Q,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new Q,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(s=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new Q),Q.FromEulerAnglesToRef(0,s.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Bs.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Q),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class kb extends wf{constructor(e){super(e)}addKeyboard(){return this.add(new lo),this}addMouse(){return this.add(new Bf),this}}class zf extends Ai{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new m(1,1,1),this.ellipsoidOffset=new m(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=m.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=m.Zero(),this._diffPosition=m.Zero(),this._newPosition=m.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,o=null)=>{(h=>{this._newPosition.copyFrom(h),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>H.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(n)},this.inputs=new kb(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=X.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new m(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=m.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=m.Zero(),this._transformedDirection=m.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=this.rotation.z,s=t-i,r=.001;Math.abs(s)>=r&&(this.rotation.z+=s/e,Math.abs(t-this.rotation.z)<=r&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}E([bs()],zf.prototype,"ellipsoid",void 0);E([bs()],zf.prototype,"ellipsoidOffset",void 0);E([I()],zf.prototype,"checkCollisions",void 0);E([I()],zf.prototype,"applyGravity",void 0);class Gb extends wf{constructor(e){super(e)}addKeyboard(){return this.add(new As),this}addMouseWheel(){return this.add(new Wo),this}addPointers(){return this.add(new ur),this}addVRDeviceOrientation(){return O.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ct.AddNodeConstructor("FollowCamera",(a,e)=>()=>new Wr(a,m.Zero(),e));Ct.AddNodeConstructor("ArcFollowCamera",(a,e)=>()=>new zb(a,0,0,1,null,e));class Wr extends Ai{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new Gb(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=U.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=X.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,l=n-this.position.x,h=r.y+this.heightOffset-this.position.y,c=o-this.position.z;let u=l*this.cameraAcceleration*2,d=h*this.cameraAcceleration,f=c*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new m(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(r)}attachControl(e,t){t=X.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){this.lowerRadiusLimit!==null&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),this.upperRadiusLimit!==null&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),this.upperHeightOffsetLimit!==null&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),this.upperRotationOffsetLimit!==null&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}E([I()],Wr.prototype,"radius",void 0);E([I()],Wr.prototype,"lowerRadiusLimit",void 0);E([I()],Wr.prototype,"upperRadiusLimit",void 0);E([I()],Wr.prototype,"rotationOffset",void 0);E([I()],Wr.prototype,"lowerRotationOffsetLimit",void 0);E([I()],Wr.prototype,"upperRotationOffsetLimit",void 0);E([I()],Wr.prototype,"heightOffset",void 0);E([I()],Wr.prototype,"lowerHeightOffsetLimit",void 0);E([I()],Wr.prototype,"upperHeightOffsetLimit",void 0);E([I()],Wr.prototype,"cameraAcceleration",void 0);E([I()],Wr.prototype,"maxCameraSpeed",void 0);E([Wu("lockedTargetId")],Wr.prototype,"lockedTarget",void 0);class zb extends Ai{constructor(e,t,i,s,r,n){super(e,m.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=m.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}var xr;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(xr||(xr={}));var fl;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(fl||(fl={}));class Wb extends us{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new G,this.onButtonUpObservable=new G,this.onPadDownObservable=new G,this.onPadUpObservable=new G,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=us.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,xr.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,xr.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,xr.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,xr.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,xr.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,xr.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,xr.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,xr.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,xr.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,xr.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,fl.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,fl.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,fl.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,fl.Right)}update(){super.update(),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}var qr;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(qr||(qr={}));var _l;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(_l||(_l={}));class Hb extends us{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new G,this.onButtonUpObservable=new G,this.onPadDownObservable=new G,this.onPadUpObservable=new G,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=us.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(e===1&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),e===0&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(e===1&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),e===0&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,qr.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,qr.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,qr.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,qr.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,qr.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,qr.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,qr.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,qr.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,qr.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,qr.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,_l.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,_l.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,_l.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,_l.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Xb{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new G,ls()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new G(t=>{for(const i in this._babylonGamepads){const s=this._babylonGamepads[i];s&&s._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,s)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let s;this._babylonGamepads[i.index]?(s=this._babylonGamepads[i.index],s.browserGamepad=i,s._isConnected=!0):s=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(s),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const s in this._babylonGamepads)if(this._babylonGamepads[s].index===i.index){const r=this._babylonGamepads[s];r._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(r),r.dispose&&r.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const t=this._scene?this._scene.getEngine().getHostWindow():window;t&&(t.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),t.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=us.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){this._oneGamepadConnected||(this._oneGamepadConnected=!0);let t;const i=e.id.search("054c")!==-1&&e.id.search("0ce6")===-1,s=e.id.search("Xbox One")!==-1;return s||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new Wb(e.id,e.index,e,s):i?t=new Hb(e.id,e.index,e):t=new Ub(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(!(!t||!t.isConnected))try{t.update()}catch{this._loggedErrors.indexOf(t.index)===-1&&(X.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&H.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length;t++){const i=e[t];if(i)if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{const s=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(s)}}}}Object.defineProperty(Ee.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new Xb(this);let a=this._getComponent(he.NAME_GAMEPAD);a||(a=new Yb(this),this._addComponent(a))}return this._gamepadManager},enumerable:!0,configurable:!0});kf.prototype.addGamepad=function(){return this.add(new Gf),this};Om.prototype.addGamepad=function(){return this.add(new Lf),this};class Yb{constructor(e){this.name=he.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(he.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){const e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){const e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}}Ct.AddNodeConstructor("FreeCamera",(a,e)=>()=>new bc(a,m.Zero(),e));class bc extends nS{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}ve._CreateDefaultParsedCamera=(a,e)=>new bc(a,m.Zero(),e);Ct.AddNodeConstructor("GamepadCamera",(a,e)=>()=>new Fm(a,m.Zero(),e));class Fm extends bc{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const $b="passCubePixelShader",Kb=`varying vec2 vUV;uniform samplerCube textureSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec2 uv=vUV*2.0-1.0;
#ifdef POSITIVEX
gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));
#endif
#ifdef NEGATIVEX
gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));
#endif
#ifdef POSITIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));
#endif
#ifdef NEGATIVEY
gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));
#endif
#ifdef POSITIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,1.001));
#endif
#ifdef NEGATIVEZ
gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));
#endif
}`;W.ShadersStore[$b]=Kb;class An extends De{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,l=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,l)}static _Parse(e,t,i,s){return _e.Parse(()=>new An(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}V("BABYLON.PassPostProcess",An);H._RescalePostProcessFactory=a=>new An("rescale",1,null,2,a,!1,0);const jb="anaglyphPixelShader",qb=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;W.ShadersStore[jb]=qb;class aS extends De{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}V("BABYLON.AnaglyphPostProcess",aS);function Wf(a){a._rigCameras[0]._rigPostProcess=new An(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new aS(a.name+"_anaglyph",1,a._rigCameras)}Ct.AddNodeConstructor("AnaglyphArcRotateCamera",(a,e,t)=>()=>new Qb(a,0,0,1,m.Zero(),t.interaxial_distance,e));class Qb extends $t{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Wf(this),this.interaxialDistance=n,this.setCameraRigMode(ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Ct.AddNodeConstructor("AnaglyphFreeCamera",(a,e,t)=>()=>new Zb(a,m.Zero(),t.interaxial_distance,e));class Zb extends qs{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Wf(this),this.interaxialDistance=i,this.setCameraRigMode(ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ct.AddNodeConstructor("AnaglyphGamepadCamera",(a,e,t)=>()=>new Jb(a,m.Zero(),t.interaxial_distance,e));class Jb extends Fm{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Wf(this),this.interaxialDistance=i,this.setCameraRigMode(ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ct.AddNodeConstructor("AnaglyphUniversalCamera",(a,e,t)=>()=>new eA(a,m.Zero(),t.interaxial_distance,e));class eA extends bc{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Wf(this),this.interaxialDistance=i,this.setCameraRigMode(ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const tA="stereoscopicInterlacePixelShader",iA=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;
#ifdef IS_STEREOSCOPIC_HORIZ
useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);
#else
#ifdef IS_STEREOSCOPIC_INTERLACED
float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);
#else
useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);
#endif
#endif
if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}
gl_FragColor=vec4((frag1+frag2)/TWO,1.0);}
`;W.ShadersStore[tA]=iA;class sA extends De{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Z(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Z(1/this.width,1/this.height)}),this.onApplyObservable.add(l=>{l.setTextureFromPostProcess("camASampler",this._passedProcess),l.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function Hf(a){const e=a.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||a.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=a.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;a.cameraRigMode===ve.RIG_MODE_STEREOSCOPIC_INTERLACED?(a._rigCameras[0]._rigPostProcess=new An(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new sA(a.name+"_stereoInterlace",a._rigCameras,!1,!0)):(a._rigCameras[t?1:0].viewport=new Vr(0,0,e?.5:1,e?1:.5),a._rigCameras[t?0:1].viewport=new Vr(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Ct.AddNodeConstructor("StereoscopicArcRotateCamera",(a,e,t)=>()=>new rA(a,0,0,1,m.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class rA extends $t{constructor(e,t,i,s,r,n,o,l){super(e,t,i,s,r,l),this._setRigMode=()=>Hf(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new nA(a,m.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class nA extends qs{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hf(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ct.AddNodeConstructor("StereoscopicGamepadCamera",(a,e,t)=>()=>new aA(a,m.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class aA extends Fm{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hf(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new oA(a,m.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class oA extends bc{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hf(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}Ct.AddNodeConstructor("VirtualJoysticksCamera",(a,e)=>()=>new lA(a,m.Zero(),e));class lA extends qs{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Ac{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return D.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return D.Translation(-t,0,0)}get leftPreViewMatrix(){return D.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return D.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Ac;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}const hA="vrDistortionCorrectionPixelShader",cA=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; 
float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)
gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;W.ShadersStore[hA]=cA;class Tx extends De{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,k.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new Z(2,2/this.aspectRatio),this._scaleFactor=new Z(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new Z(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(r=>{r.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),r.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),r.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),r.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}const uA="vrMultiviewToSingleviewPixelShader",dA=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;W.ShadersStore[uA]=dA;class lp extends oi{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}H.prototype.createMultiviewRenderTargetTexture=function(a,e,t,i){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:a,height:e});r._framebuffer=s.createFramebuffer();const n=new Tt(this,et.Unknown,!0);return n.width=a,n.height=e,n.isMultiview=!0,t||(t=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,t),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,a,e,2)),r._colorTextureArray=t,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,a,e,2)),r._depthStencilTextureArray=i,n.isReady=!0,r.setTextures(n),r._depthStencilTexture=n,r};H.prototype.bindMultiviewFramebuffer=function(a){const e=a,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"};H.prototype.bindSpaceWarpFramebuffer=function(a){const e=a,t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw new Error("Invalid Space Warp framebuffer")};ve.prototype._useMultiviewToSingleView=!1;ve.prototype._multiviewTexture=null;ve.prototype._resizeOrCreateMultiviewTexture=function(a,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=a||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new lp(this.getScene(),{width:a,height:e})):this._multiviewTexture=new lp(this.getScene(),{width:a,height:e})};function oS(a,e){const t=new be(a,void 0,!0,e);return t.addUniform("viewProjection",16),t.addUniform("viewProjectionR",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}const fA=Ee.prototype.createSceneUniformBuffer;Ee.prototype._transformMatrixR=D.Zero();Ee.prototype._multiviewSceneUbo=null;Ee.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=oS(this.getEngine(),"scene_multiview")};Ee.prototype.createSceneUniformBuffer=function(a){return this._multiviewSceneUbo?oS(this.getEngine(),a):fA.bind(this)(a)};Ee.prototype._updateMultiviewUbo=function(a,e){a&&e&&a.multiplyToRef(e,this._transformMatrixR),a&&e&&(a.multiplyToRef(e,U.Matrix[0]),Or.GetRightPlaneToRef(U.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))};Ee.prototype._renderMultiviewToSingleView=function(a){a._resizeOrCreateMultiviewTexture(a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.width>0?a._rigPostProcess.width:this.getEngine().getRenderWidth(!0),a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.height>0?a._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),a.outputRenderTarget=a._multiviewTexture,this._renderForCamera(a),a.outputRenderTarget=null;for(let e=0;e<a._rigCameras.length;e++){const t=this.getEngine();this._activeCamera=a._rigCameras[e],t.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};class _A extends De{getClassName(){return"VRMultiviewToSingleviewPostProcess"}constructor(e,t,i){super(e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],i,t,k.BILINEAR_SAMPLINGMODE);const s=t??this.getCamera();this.onSizeChangedObservable.add(()=>{}),this.onApplyObservable.add(r=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?r.setInt("imageIndex",0):r.setInt("imageIndex",1),r.setTexture("multiviewSampler",s._multiviewTexture)})}}function wm(a,e){const t=e.vrCameraMetrics||Ac.GetDefault();a._rigCameras[0]._cameraRigParams.vrMetrics=t,a._rigCameras[0].viewport=new Vr(0,0,.5,1),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new D,a._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,a._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,a._rigCameras[0].getProjectionMatrix=a._rigCameras[0]._getVRProjectionMatrix,a._rigCameras[1]._cameraRigParams.vrMetrics=t,a._rigCameras[1].viewport=new Vr(.5,0,.5,1),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new D,a._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,a._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,a._rigCameras[1].getProjectionMatrix=a._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(a.getScene().getEngine().getCaps().multiview?(a._useMultiviewToSingleView=!0,a._rigPostProcess=new _A("VRMultiviewToSingleview",a,t.postProcessScaleFactor)):(O.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(a._rigCameras[0]._rigPostProcess=new Tx("VR_Distort_Compensation_Left",a._rigCameras[0],!1,t),a._rigCameras[1]._rigPostProcess=new Tx("VR_Distort_Compensation_Right",a._rigCameras[1],!0,t))}Ct.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(a,e)=>()=>new pA(a,0,0,1,m.Zero(),e));class pA extends $t{constructor(e,t,i,s,r,n,o=!0,l=Ac.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=h=>wm(this,h),l.compensateDistortion=o,this.setCameraRigMode(ve.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationFreeCamera",(a,e)=>()=>new Lm(a,m.Zero(),e));class Lm extends Nm{constructor(e,t,i,s=!0,r=Ac.GetDefault()){super(e,t,i),this._setRigMode=n=>wm(this,n),r.compensateDistortion=s,this.setCameraRigMode(ve.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(a,e)=>()=>new mA(a,m.Zero(),e));class mA extends Lm{constructor(e,t,i,s=!0,r=Ac.GetDefault()){super(e,t,i,s,r),this._setRigMode=n=>wm(this,n),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class Jd{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const n=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==n.frameId&&(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class ue{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,H.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,H.MarkAllMaterialsAsDirty(1))}}ue._DiffuseTextureEnabled=!0;ue._DetailTextureEnabled=!0;ue._DecalMapEnabled=!0;ue._AmbientTextureEnabled=!0;ue._OpacityTextureEnabled=!0;ue._ReflectionTextureEnabled=!0;ue._EmissiveTextureEnabled=!0;ue._SpecularTextureEnabled=!0;ue._BumpTextureEnabled=!0;ue._LightmapTextureEnabled=!0;ue._RefractionTextureEnabled=!0;ue._ColorGradingTextureEnabled=!0;ue._FresnelEnabled=!0;ue._ClearCoatTextureEnabled=!0;ue._ClearCoatBumpTextureEnabled=!0;ue._ClearCoatTintTextureEnabled=!0;ue._SheenTextureEnabled=!0;ue._AnisotropicTextureEnabled=!0;ue._ThicknessTextureEnabled=!0;ue._RefractionIntensityTextureEnabled=!0;ue._TranslucencyIntensityTextureEnabled=!0;ue._IridescenceTextureEnabled=!0;const gA="decalFragmentDeclaration",xA=`#ifdef DECAL
uniform vec4 vDecalInfos;
#endif
`;W.IncludesShadersStore[gA]=xA;const TA="defaultFragmentDeclaration",EA=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;
#ifdef SPECULARTERM
uniform vec4 vSpecularColor;
#endif
uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY 
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef ALPHATEST
uniform float alphaCutOff;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFRACTION
uniform vec4 vRefractionInfos;
#ifndef REFRACTIONMAP_3D
uniform mat4 refractionMatrix;
#endif
#ifdef REFRACTIONFRESNEL
uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;
#endif
#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; 
#endif
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;
#endif
#ifdef DIFFUSEFRESNEL
uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;
#endif
#ifdef OPACITYFRESNEL
uniform vec4 opacityParts;
#endif
#ifdef EMISSIVEFRESNEL
uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)
uniform mat4 reflectionMatrix;
#endif
#ifndef REFLECTIONMAP_SKYBOX
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; 
#endif
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#define ADDITIONAL_FRAGMENT_DECLARATION
`;W.IncludesShadersStore[TA]=EA;const SA="sceneUboDeclaration",CA=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif 
mat4 view;mat4 projection;vec4 vEyePosition;};
`;W.IncludesShadersStore[SA]=CA;const vA="meshUboDeclaration",bA=`#ifdef WEBGL2
uniform mat4 world;uniform float visibility;
#else
layout(std140,column_major) uniform;uniform Mesh
{mat4 world;float visibility;};
#endif
#define WORLD_UBO
`;W.IncludesShadersStore[vA]=bA;const AA="defaultUboDeclaration",yA=`layout(std140,column_major) uniform;uniform Material
{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;W.IncludesShadersStore[AA]=yA;const RA="prePassDeclaration",IA=`#ifdef PREPASS
#extension GL_EXT_draw_buffers : require
layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;
#ifdef PREPASS_DEPTH
varying highp vec3 vViewPos;
#endif
#ifdef PREPASS_VELOCITY
varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;
#endif
#endif
`;W.IncludesShadersStore[RA]=IA;const PA="oitDeclaration",MA=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#extension GL_EXT_draw_buffers : require
layout(location=0) out vec2 depth; 
layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;
#define MAX_DEPTH 99999.0
highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;
#endif
`;W.IncludesShadersStore[PA]=MA;const DA="mainUVVaryingDeclaration",OA=`#ifdef MAINUV{X}
varying vec2 vMainUV{X};
#endif
`;W.IncludesShadersStore[DA]=OA;const NA="helperFunctions",FA=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; 
const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;
#define saturate(x) clamp(x,0.0,1.0)
#define absEps(x) abs(x)+Epsilon
#define maxEps(x) max(x,Epsilon)
#define saturateEps(x) clamp(x,Epsilon,1.0)
mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(
vec3(i0.x,i1.x,i2.x),
vec3(i0.y,i1.y,i2.y),
vec3(i0.z,i1.z,i2.z)
);return outMatrix;}
mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),
b11,(a22*a00-a02*a20),(-a12*a00+a02*a10),
b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}
#if USE_EXACT_SRGB_CONVERSIONS
vec3 toLinearSpaceExact(vec3 color)
{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));
#else
return
vec3(
color.r<=0.04045 ? nearZeroSection.r : remainingSection.r,
color.g<=0.04045 ? nearZeroSection.g : remainingSection.g,
color.b<=0.04045 ? nearZeroSection.b : remainingSection.b);
#endif
}
vec3 toGammaSpaceExact(vec3 color)
{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));
#else
return
vec3(
color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,
color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,
color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);
#endif
}
#endif
float toLinearSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;
#else
return pow(color,LinearEncodePowerApprox);
#endif
}
vec3 toLinearSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toLinearSpaceExact(color);
#else
return pow(color,vec3(LinearEncodePowerApprox));
#endif
}
vec4 toLinearSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toLinearSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);
#endif
}
float toGammaSpace(float color)
{
#if USE_EXACT_SRGB_CONVERSIONS
float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;
#else
return pow(color,GammaEncodePowerApprox);
#endif
}
vec3 toGammaSpace(vec3 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return toGammaSpaceExact(color);
#else
return pow(color,vec3(GammaEncodePowerApprox));
#endif
}
vec4 toGammaSpace(vec4 color)
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);
#endif
}
float square(float value)
{return value*value;}
vec3 square(vec3 value)
{return value*value;}
float pow5(float value) {float sq=value*value;return sq*sq*value;}
float getLuminance(vec3 color)
{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}
float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}
float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}
const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }
vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}
vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}
`;W.IncludesShadersStore[NA]=FA;const wA="lightFragmentDeclaration",LA=`#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
#else
uniform highp sampler2DArray shadowSampler{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowSampler{X};
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowSampler{X};
#else
uniform sampler2D shadowSampler{X};
#endif
uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};
#endif
#endif
`;W.IncludesShadersStore[wA]=LA;const BA="lightUboDeclaration",UA=`#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowSampler{X};
#else
uniform highp sampler2DArray shadowSampler{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowSampler{X}; 
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowSampler{X};
#else
uniform sampler2D shadowSampler{X};
#endif
uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`;W.IncludesShadersStore[BA]=UA;const VA="lightsFragmentFunctions",kA=`struct lightingInfo
{vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef NDOTL
float ndl;
#endif
};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)
{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}
else
{lightVectorW=normalize(-lightData.xyz);}
float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)
{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=mix(groundColor,diffuseColor,ndl);
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;
#endif
return result;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;W.IncludesShadersStore[VA]=kA;const GA="shadowsFragmentFunctions",zA=`#ifdef SHADOWS
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
#ifndef SHADOWFLOAT
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}
#endif
float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)
{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}
#define inline
float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadow=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadow=textureCube(shadowSampler,directionToLight).x;
#endif
return depth>shadow ? darkness : 1.0;}
#define inline
float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);
#ifndef SHADOWFLOAT
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;
#else
if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;
#endif
return min(1.0,visibility+darkness);}
#define inline
float computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}
#define inline
float computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define inline
float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(texture2D(shadowSampler,uvLayer));
#else
float shadow=texture2D(shadowSampler,uvLayer).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}
#endif
#define inline
float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}
#define inline
float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);
#ifndef SHADOWFLOAT
if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;
#else
if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0); 
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#ifdef IS_NDC_HALF_ZRANGE
#define ZINCLIP clipSpace.z
#else
#define ZINCLIP uvDepth.z
#endif
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define GREATEST_LESS_THAN_ONE 0.99999994
/* disable_uniformity_analysis */
#define inline
float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
const vec3 PoissonSamplers32[64]=vec3[64](
vec3(0.06407013,0.05409927,0.),
vec3(0.7366577,0.5789394,0.),
vec3(-0.6270542,-0.5320278,0.),
vec3(-0.4096107,0.8411095,0.),
vec3(0.6849564,-0.4990818,0.),
vec3(-0.874181,-0.04579735,0.),
vec3(0.9989998,0.0009880066,0.),
vec3(-0.004920578,-0.9151649,0.),
vec3(0.1805763,0.9747483,0.),
vec3(-0.2138451,0.2635818,0.),
vec3(0.109845,0.3884785,0.),
vec3(0.06876755,-0.3581074,0.),
vec3(0.374073,-0.7661266,0.),
vec3(0.3079132,-0.1216763,0.),
vec3(-0.3794335,-0.8271583,0.),
vec3(-0.203878,-0.07715034,0.),
vec3(0.5912697,0.1469799,0.),
vec3(-0.88069,0.3031784,0.),
vec3(0.5040108,0.8283722,0.),
vec3(-0.5844124,0.5494877,0.),
vec3(0.6017799,-0.1726654,0.),
vec3(-0.5554981,0.1559997,0.),
vec3(-0.3016369,-0.3900928,0.),
vec3(-0.5550632,-0.1723762,0.),
vec3(0.925029,0.2995041,0.),
vec3(-0.2473137,0.5538505,0.),
vec3(0.9183037,-0.2862392,0.),
vec3(0.2469421,0.6718712,0.),
vec3(0.3916397,-0.4328209,0.),
vec3(-0.03576927,-0.6220032,0.),
vec3(-0.04661255,0.7995201,0.),
vec3(0.4402924,0.3640312,0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.)
);const vec3 PoissonSamplers64[64]=vec3[64](
vec3(-0.613392,0.617481,0.),
vec3(0.170019,-0.040254,0.),
vec3(-0.299417,0.791925,0.),
vec3(0.645680,0.493210,0.),
vec3(-0.651784,0.717887,0.),
vec3(0.421003,0.027070,0.),
vec3(-0.817194,-0.271096,0.),
vec3(-0.705374,-0.668203,0.),
vec3(0.977050,-0.108615,0.),
vec3(0.063326,0.142369,0.),
vec3(0.203528,0.214331,0.),
vec3(-0.667531,0.326090,0.),
vec3(-0.098422,-0.295755,0.),
vec3(-0.885922,0.215369,0.),
vec3(0.566637,0.605213,0.),
vec3(0.039766,-0.396100,0.),
vec3(0.751946,0.453352,0.),
vec3(0.078707,-0.715323,0.),
vec3(-0.075838,-0.529344,0.),
vec3(0.724479,-0.580798,0.),
vec3(0.222999,-0.215125,0.),
vec3(-0.467574,-0.405438,0.),
vec3(-0.248268,-0.814753,0.),
vec3(0.354411,-0.887570,0.),
vec3(0.175817,0.382366,0.),
vec3(0.487472,-0.063082,0.),
vec3(-0.084078,0.898312,0.),
vec3(0.488876,-0.783441,0.),
vec3(0.470016,0.217933,0.),
vec3(-0.696890,-0.549791,0.),
vec3(-0.149693,0.605762,0.),
vec3(0.034211,0.979980,0.),
vec3(0.503098,-0.308878,0.),
vec3(-0.016205,-0.872921,0.),
vec3(0.385784,-0.393902,0.),
vec3(-0.146886,-0.859249,0.),
vec3(0.643361,0.164098,0.),
vec3(0.634388,-0.049471,0.),
vec3(-0.688894,0.007843,0.),
vec3(0.464034,-0.188818,0.),
vec3(-0.440840,0.137486,0.),
vec3(0.364483,0.511704,0.),
vec3(0.034028,0.325968,0.),
vec3(0.099094,-0.308023,0.),
vec3(0.693960,-0.366253,0.),
vec3(0.678884,-0.204688,0.),
vec3(0.001801,0.780328,0.),
vec3(0.145177,-0.898984,0.),
vec3(0.062655,-0.611866,0.),
vec3(0.315226,-0.604297,0.),
vec3(-0.780145,0.486251,0.),
vec3(-0.371868,0.882138,0.),
vec3(0.200476,0.494430,0.),
vec3(-0.494552,-0.711051,0.),
vec3(0.612476,0.705252,0.),
vec3(-0.578845,-0.768792,0.),
vec3(-0.772454,-0.090976,0.),
vec3(0.504440,0.372295,0.),
vec3(0.155736,0.065157,0.),
vec3(0.391522,0.849605,0.),
vec3(-0.620106,-0.328104,0.),
vec3(0.789239,-0.419965,0.),
vec3(-0.545396,0.538133,0.),
vec3(-0.178564,-0.596057,0.)
);
#define inline
float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}
else
{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
if (numBlocker<1.0) {return 1.0;}
else
{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}
#define inline
float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}
#define inline
float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#endif
#endif
`;W.IncludesShadersStore[GA]=zA;const WA="samplerFragmentDeclaration",HA=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
uniform sampler2D _SAMPLERNAME_Sampler;
#endif
`;W.IncludesShadersStore[WA]=HA;const XA="fresnelFunction",YA=`#ifdef FRESNEL
float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)
{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}
#endif
`;W.IncludesShadersStore[XA]=YA;const $A="reflectionFunction",KA=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }
vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }
vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}
vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)
{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}
vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}
vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*(view*worldPos));}
vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*vec4(positionW,1.));}
#ifdef REFLECTION
vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR
return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SPHERICAL
return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_PLANAR
return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_CUBIC
#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);
#else
return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_PROJECTION
return computeProjectionCoords(worldPos,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SKYBOX
return computeSkyBoxCoords(vPositionUVW,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_EXPLICIT
return vec3(0,0,0);
#endif
}
#endif
`;W.IncludesShadersStore[$A]=KA;const jA="imageProcessingDeclaration",qA=`#ifdef EXPOSURE
uniform float exposureLinear;
#endif
#ifdef CONTRAST
uniform float contrast;
#endif
#if defined(VIGNETTE) || defined(DITHER)
uniform vec2 vInverseScreenSize;
#endif
#ifdef VIGNETTE
uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;
#endif
#ifdef COLORCURVES
uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;
#endif
#ifdef COLORGRADING
#ifdef COLORGRADING3D
uniform highp sampler3D txColorTransform;
#else
uniform sampler2D txColorTransform;
#endif
uniform vec4 colorTransformSettings;
#endif
#ifdef DITHER
uniform float ditherIntensity;
#endif
`;W.IncludesShadersStore[jA]=qA;const QA="imageProcessingFunctions",ZA=`#if defined(COLORGRADING) && !defined(COLORGRADING3D)
/** 
* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.
* sampler3dSetting.x=textureOffset (0.5/textureSize).
* sampler3dSetting.y=textureSize.
*/
#define inline
vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
{float sliceSize=2.0*sampler3dSetting.x; 
#ifdef SAMPLER3DGREENDEPTH
float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
#else
float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
#endif
float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;
#ifdef SAMPLER3DGREENDEPTH
vec2 sliceUV=color.rb;
#else
vec2 sliceUV=color.rg;
#endif
sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
#ifdef SAMPLER3DBGRMAP
color.rgb=result.rgb;
#else
color.rgb=result.bgr;
#endif
return color;}
#endif
#ifdef TONEMAPPING_ACES
const mat3 ACESInputMat=mat3(
vec3(0.59719,0.07600,0.02840),
vec3(0.35458,0.90834,0.13383),
vec3(0.04823,0.01566,0.83777)
);const mat3 ACESOutputMat=mat3(
vec3( 1.60475,-0.10208,-0.00327),
vec3(-0.53108, 1.10813,-0.07276),
vec3(-0.07367,-0.00605, 1.07602)
);vec3 RRTAndODTFit(vec3 v)
{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
vec3 ACESFitted(vec3 color)
{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
vec4 applyImageProcessing(vec4 result) {
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
#ifdef EXPOSURE
result.rgb*=exposureLinear;
#endif
#ifdef VIGNETTE
vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;
#ifdef VIGNETTEBLENDMODEMULTIPLY
vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;
#endif
#ifdef VIGNETTEBLENDMODEOPAQUE
result.rgb=mix(vignetteColor,result.rgb,vignette);
#endif
#endif
#ifdef TONEMAPPING
#ifdef TONEMAPPING_ACES
result.rgb=ACESFitted(result.rgb);
#else
const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
#endif
#endif
result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);
#ifdef CONTRAST
vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}
#endif
#ifdef COLORGRADING
vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
#ifdef COLORGRADING3D
vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
#else
vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
#endif
result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
#endif
#ifdef COLORCURVES
float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
#endif
#ifdef DITHER
float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
return result;}`;W.IncludesShadersStore[QA]=ZA;const JA="bumpFragmentMainFunctions",ey=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL) 
varying mat3 vTBN;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform mat4 normalMatrix;
#if defined(WEBGL2) || defined(WEBGPU)
mat4 toNormalMatrix(mat4 wMatrix)
{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}
#else
mat4 toNormalMatrix(mat4 m)
{float
a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],
a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],
a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],
a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],
b00=a00*a11-a01*a10,
b01=a00*a12-a02*a10,
b02=a00*a13-a03*a10,
b03=a01*a12-a02*a11,
b04=a01*a13-a03*a11,
b05=a02*a13-a03*a12,
b06=a20*a31-a21*a30,
b07=a20*a32-a22*a30,
b08=a20*a33-a23*a30,
b09=a21*a32-a22*a31,
b10=a21*a33-a23*a31,
b11=a22*a33-a23*a32,
det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(
a11*b11-a12*b10+a13*b09,
a02*b10-a01*b11-a03*b09,
a31*b05-a32*b04+a33*b03,
a22*b04-a21*b05-a23*b03,
a12*b08-a10*b11-a13*b07,
a00*b11-a02*b08+a03*b07,
a32*b02-a30*b05-a33*b01,
a20*b05-a22*b02+a23*b01,
a10*b10-a11*b08+a13*b06,
a01*b08-a00*b10-a03*b06,
a30*b04-a31*b02+a33*b00,
a21*b02-a20*b04-a23*b00,
a11*b07-a10*b09-a12*b06,
a00*b09-a01*b07+a02*b06,
a31*b01-a30*b03-a32*b00,
a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
#endif
vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
{
#ifdef NORMALXYSCALE
normal=normalize(normal*vec3(scale,scale,1.0));
#endif
return normalize(cotangentFrame*normal);}
vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}
#endif
`;W.IncludesShadersStore[JA]=ey;const ty="bumpFragmentFunctions",iy=`#if defined(BUMP)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(BUMP) && defined(PARALLAX)
const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)
{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
vec2 parallaxOffset(vec3 viewDir,float heightScale)
{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`;W.IncludesShadersStore[ty]=iy;const sy="clipPlaneFragmentDeclaration",ry=`#ifdef CLIPPLANE
varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
varying float fClipDistance6;
#endif
`;W.IncludesShadersStore[sy]=ry;const ny="logDepthDeclaration",ay=`#ifdef LOGARITHMICDEPTH
uniform float logarithmicDepthConstant;varying float vFragmentDepth;
#endif
`;W.IncludesShadersStore[ny]=ay;const oy="fogFragmentDeclaration",ly=`#ifdef FOG
#define FOGMODE_NONE 0.
#define FOGMODE_EXP 1.
#define FOGMODE_EXP2 2.
#define FOGMODE_LINEAR 3.
#define E 2.71828
uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()
{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x)
{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}
else if (FOGMODE_EXP==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}
else if (FOGMODE_EXP2==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}
return clamp(fogCoeff,0.0,1.0);}
#endif
`;W.IncludesShadersStore[oy]=ly;const hy="clipPlaneFragment",cy=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fClipDistance6>0.0)
{discard;}
#endif
`;W.IncludesShadersStore[hy]=cy;const uy="bumpFragment",dy=`vec2 uvOffset=vec2(0.0,0.0);
#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
float normalScale=1.0;
#elif defined(BUMP)
float normalScale=vBumpInfos.y;
#else
float normalScale=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#elif defined(BUMP)
vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#else
vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
#endif
#elif defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#else
vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
#endif
#endif
#ifdef PARALLAX
mat3 invTBN=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);
#else
uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);
#endif
#endif
#ifdef DETAIL
vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
#endif
#ifdef BUMP
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);
#else
vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0 
detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1 
detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);
#endif
#elif defined(DETAIL)
detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
#endif
`;W.IncludesShadersStore[uy]=dy;const fy="decalFragment",_y=`#ifdef DECAL
#ifdef GAMMADECAL
decalColor.rgb=toLinearSpace(decalColor.rgb);
#endif
#ifdef DECAL_SMOOTHALPHA
decalColor.a*=decalColor.a;
#endif
surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);
#endif
`;W.IncludesShadersStore[fy]=_y;const py="depthPrePass",my=`#ifdef DEPTHPREPASS
gl_FragColor=vec4(0.,0.,0.,1.0);return;
#endif
`;W.IncludesShadersStore[py]=my;const gy="lightFragment",xy=`#ifdef LIGHT{X}
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
#ifdef PBR
#ifdef SPOTLIGHT{X}
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(POINTLIGHT{X})
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(HEMILIGHT{X})
preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#elif defined(DIRLIGHT{X})
preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);
#endif
preInfo.NdotV=NdotV;
#ifdef SPOTLIGHT{X}
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);
#endif
#elif defined(POINTLIGHT{X})
#ifdef LIGHT_FALLOFF_GLTF{X}
preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);
#elif defined(LIGHT_FALLOFF_PHYSICAL{X})
preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);
#elif defined(LIGHT_FALLOFF_STANDARD{X})
preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);
#else
preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);
#endif
#else
preInfo.attenuation=1.0;
#endif
#ifdef HEMILIGHT{X}
preInfo.roughness=roughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
#ifdef IRIDESCENCE
preInfo.iridescenceIntensity=iridescenceIntensity;
#endif
#ifdef HEMILIGHT{X}
info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);
#elif defined(SS_TRANSLUCENCY)
info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);
#else
info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);
#endif
#ifdef SPECULARTERM
#ifdef ANISOTROPIC
info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#else
info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#endif
#endif
#ifdef SHEEN
#ifdef SHEEN_LINKWITHALBEDO
preInfo.roughness=sheenOut.sheenIntensity;
#else
#ifdef HEMILIGHT{X}
preInfo.roughness=sheenOut.sheenRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
#endif
info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);
#endif
#ifdef CLEARCOAT
#ifdef HEMILIGHT{X}
preInfo.roughness=clearcoatOut.clearCoatRoughness;
#else
preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);
#endif
info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);
#ifdef CLEARCOAT_TINT
absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;
#ifdef SPECULARTERM
info.specular*=absorption;
#endif
#endif
info.diffuse*=info.clearCoat.w;
#ifdef SPECULARTERM
info.specular*=info.clearCoat.w;
#endif
#ifdef SHEEN
info.sheen*=info.clearCoat.w;
#endif
#endif
#else
#ifdef SPOTLIGHT{X}
info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
#elif defined(HEMILIGHT{X})
info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);
#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})
info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);
#endif
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});
#endif
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) 
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;
#else
diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;
#endif
if (diff{X}>=0.) {index{X}=i;break;}}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
if (index{X}>=0)
#endif
{
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];
#endif
#ifndef SHADOWCSMNOBLEND{X}
float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
{index{X}+=1;float nextShadow=0.;
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
shadow=mix(nextShadow,shadow,diffRatio);
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
#endif
}
#endif
}
#elif defined(SHADOWCLOSEESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPOISSON{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#else
#if defined(SHADOWCUBE{X})
shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#endif
#ifdef SHADOWONLY
#ifndef SHADOWINUSE
#define SHADOWINUSE
#endif
globalShadow+=shadow;shadowLightCount+=1.0;
#endif
#else
shadow=1.;
#endif
aggShadow+=shadow;numLights+=1.0;
#ifndef SHADOWONLY
#ifdef CUSTOMUSERLIGHTING
diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
#ifdef SPECULARTERM
specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
#endif
#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
diffuseBase+=lightmapColor.rgb*shadow;
#ifdef SPECULARTERM
#ifndef LIGHTMAPNOSPECULAR{X}
specularBase+=info.specular*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef CLEARCOAT
#ifndef LIGHTMAPNOSPECULAR{X}
clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef SHEEN
#ifndef LIGHTMAPNOSPECULAR{X}
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#else
#ifdef SHADOWCSMDEBUG{X}
diffuseBase+=info.diffuse*shadowDebug{X};
#else 
diffuseBase+=info.diffuse*shadow;
#endif
#ifdef SPECULARTERM
specularBase+=info.specular*shadow;
#endif
#ifdef CLEARCOAT
clearCoatBase+=info.clearCoat.rgb*shadow;
#endif
#ifdef SHEEN
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#endif
#endif
`;W.IncludesShadersStore[gy]=xy;const Ty="logDepthFragment",Ey=`#ifdef LOGARITHMICDEPTH
gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
#endif
`;W.IncludesShadersStore[Ty]=Ey;const Sy="fogFragment",Cy=`#ifdef FOG
float fog=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color.rgb=mix(vFogColor,color.rgb,fog);
#endif
`;W.IncludesShadersStore[Sy]=Cy;const vy="oitFragment",by=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY
float fragDepth=gl_FragCoord.z; 
#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;
#endif
ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0);
#ifdef USE_REVERSE_DEPTHBUFFER
float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;
#else
float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;
#endif
float alphaMultiplier=1.0-lastFrontColor.a;
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif
return;}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif
depth.rg=vec2(-fragDepth,fragDepth);return;}
#endif
`;W.IncludesShadersStore[vy]=by;const Ay="defaultPixelShader",yy=`#include<__decl__defaultFragment>
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
uniform samplerCube refractionCubeSampler;
#else
uniform sampler2D refraction2DSampler;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif
#include<fresnelFunction>
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
uniform samplerCube reflectionCubeSampler;
#else
uniform sampler2D reflection2DSampler;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
#ifdef DIFFUSE
baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<alphaCutOff)
discard;
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor.rgb*=vDiffuseInfos.y;
#endif
#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#include<depthPrePass>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
baseColor.rgb*=vColor.rgb;
#endif
#ifdef DETAIL
baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);
#endif
#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
vec3 baseAmbientColor=vec3(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
#ifdef SPECULARTERM
float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;
#ifdef SPECULAR
vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#else
float glossiness=0.;
#endif
vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
float shadow=1.;float aggShadow=0.;float numLights=0.;
#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
#include<lightFragment>[0..maxSimultaneousLights]
aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);
#ifdef REFRACTION
vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor.rgb=fromRGBD(refractionColor);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor.rgb=toGammaSpace(refractionColor.rgb);
#endif
refractionColor.rgb*=vRefractionInfos.x;
#endif
vec4 reflectionColor=vec4(0.,0.,0.,1.);
#ifdef REFLECTION
vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
float bias=vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);
#else
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);
#endif
#else
vec2 coords=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor.rgb=toGammaSpace(reflectionColor.rgb);
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#ifdef REFLECTIONFRESNEL
float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;
#else
alpha*=opacityMap.a*vOpacityInfos.y;
#endif
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#ifdef OPACITYFRESNEL
float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<alphaCutOff)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
vec3 emissiveColor=vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;
#endif
#ifdef DIFFUSEFRESNEL
float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;
#endif
#ifdef EMISSIVEASILLUMINATION
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#else
vec3 finalSpecular=vec3(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#ifdef EMISSIVEASILLUMINATION
vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
#else
vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color.rgb*=lightmapColor.rgb;
#else
color.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color.rgb=max(color.rgb,0.);
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
color.rgb=toLinearSpace(color.rgb);
#else
#ifdef IMAGEPROCESSING
color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);
#endif
#endif
color.a*=visibility;
#ifdef PREMULTIPLYALPHA
color.rgb*=color.a;
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; 
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); 
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); 
#endif
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULARTERM)
#if defined(SPECULAR)
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; 
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;
#endif
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo;
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=color;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`;W.ShadersStore[Ay]=yy;const Ry="decalVertexDeclaration",Iy=`#ifdef DECAL
uniform vec4 vDecalInfos;uniform mat4 decalMatrix;
#endif
`;W.IncludesShadersStore[Ry]=Iy;const Py="defaultVertexDeclaration",My=`uniform mat4 viewProjection;uniform mat4 view;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;uniform mat4 specularMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef REFLECTION
uniform mat4 reflectionMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;W.IncludesShadersStore[Py]=My;const Dy="uvAttributeDeclaration",Oy=`#ifdef UV{X}
attribute vec2 uv{X};
#endif
`;W.IncludesShadersStore[Dy]=Oy;const Ny="bonesDeclaration",Fy=`#if NUM_BONE_INFLUENCERS>0
attribute vec4 matricesIndices;attribute vec4 matricesWeights;
#if NUM_BONE_INFLUENCERS>4
attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
uniform highp sampler2D boneSampler;uniform float boneTextureWidth;
#else
uniform mat4 mBones[BonesPerMesh];
#endif
#ifdef BONES_VELOCITY_ENABLED
uniform mat4 mPreviousBones[BonesPerMesh];
#endif
#ifdef BONETEXTURE
#define inline
mat4 readMatrixFromRawSampler(sampler2D smp,float index)
{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);}
#endif
#endif
#endif
`;W.IncludesShadersStore[Ny]=Fy;const wy="bakedVertexAnimationDeclaration",Ly=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;
#ifdef INSTANCES
attribute vec4 bakedVertexAnimationSettingsInstanced;
#endif
#define inline
mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);}
#endif
`;W.IncludesShadersStore[wy]=Ly;const By="instancesDeclaration",Uy=`#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#ifdef INSTANCESCOLOR
attribute vec4 instanceColor;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;
#ifdef THIN_INSTANCES
uniform mat4 previousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
uniform mat4 previousWorld;
#endif
#endif
`;W.IncludesShadersStore[By]=Uy;const Vy="prePassVertexDeclaration",ky=`#ifdef PREPASS
#ifdef PREPASS_DEPTH
varying vec3 vViewPos;
#endif
#ifdef PREPASS_VELOCITY
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#endif
`;W.IncludesShadersStore[Vy]=ky;const Gy="samplerVertexDeclaration",zy=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
varying vec2 v_VARYINGNAME_UV;
#endif
`;W.IncludesShadersStore[Gy]=zy;const Wy="bumpVertexDeclaration",Hy=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL) 
varying mat3 vTBN;
#endif
#endif
`;W.IncludesShadersStore[Wy]=Hy;const Xy="clipPlaneVertexDeclaration",Yy=`#ifdef CLIPPLANE
uniform vec4 vClipPlane;varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;varying float fClipDistance6;
#endif
`;W.IncludesShadersStore[Xy]=Yy;const $y="fogVertexDeclaration",Ky=`#ifdef FOG
varying vec3 vFogDistance;
#endif
`;W.IncludesShadersStore[$y]=Ky;const jy="lightVxFragmentDeclaration",qy=`#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#endif
`;W.IncludesShadersStore[jy]=qy;const Qy="lightVxUboDeclaration",Zy=`#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`;W.IncludesShadersStore[Qy]=Zy;const Jy="morphTargetsVertexGlobalDeclaration",eR=`#ifdef MORPHTARGETS
uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
#ifdef MORPHTARGETS_TEXTURE 
uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
{ 
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;}
#endif
#endif
`;W.IncludesShadersStore[Jy]=eR;const tR="morphTargetsVertexDeclaration",iR=`#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
attribute vec3 position{X};
#ifdef MORPHTARGETS_NORMAL
attribute vec3 normal{X};
#endif
#ifdef MORPHTARGETS_TANGENT
attribute vec3 tangent{X};
#endif
#ifdef MORPHTARGETS_UV
attribute vec2 uv_{X};
#endif
#elif {X}==0
uniform int morphTargetCount;
#endif
#endif
`;W.IncludesShadersStore[tR]=iR;const sR="morphTargetsVertexGlobal",rR=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif
`;W.IncludesShadersStore[sR]=rR;const nR="morphTargetsVertex",aR=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (i>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0;
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];
#endif
}
#endif
#else
positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
#endif
#endif
#endif
`;W.IncludesShadersStore[nR]=aR;const oR="instancesVertex",lR=`#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
finalWorld=world*finalWorld;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
mat4 finalWorld=world;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
mat4 finalPreviousWorld=previousWorld;
#endif
#endif
`;W.IncludesShadersStore[oR]=lR;const hR="bonesVertex",cR=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
mat4 influence;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
#endif
#else
influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`;W.IncludesShadersStore[hR]=cR;const uR="bakedVertexAnimation",dR=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
#define BVASNAME bakedVertexAnimationSettingsInstanced
#else
#define BVASNAME bakedVertexAnimationSettings
#endif
float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;W.IncludesShadersStore[uR]=dR;const fR="prePassVertex",_R=`#ifdef PREPASS_DEPTH
vViewPos=(view*worldPos).rgb;
#endif
#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif 
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif 
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif 
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif 
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif 
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
`;W.IncludesShadersStore[fR]=_R;const pR="uvVariableDeclaration",mR=`#if !defined(UV{X}) && defined(MAINUV{X})
vec2 uv{X}=vec2(0.,0.);
#endif
#ifdef MAINUV{X}
vMainUV{X}=uv{X};
#endif
`;W.IncludesShadersStore[pR]=mR;const gR="samplerVertexImplementation",xR=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
if (v_INFONAME_==0.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}
#ifdef UV2
else if (v_INFONAME_==1.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));}
#endif
#ifdef UV3
else if (v_INFONAME_==2.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}
#endif
#ifdef UV4
else if (v_INFONAME_==3.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}
#endif
#ifdef UV5
else if (v_INFONAME_==4.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}
#endif
#ifdef UV6
else if (v_INFONAME_==5.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}
#endif
#endif
`;W.IncludesShadersStore[gR]=xR;const TR="bumpVertex",ER=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
#endif
#endif
`;W.IncludesShadersStore[TR]=ER;const SR="clipPlaneVertex",CR=`#ifdef CLIPPLANE
fClipDistance=dot(worldPos,vClipPlane);
#endif
#ifdef CLIPPLANE2
fClipDistance2=dot(worldPos,vClipPlane2);
#endif
#ifdef CLIPPLANE3
fClipDistance3=dot(worldPos,vClipPlane3);
#endif
#ifdef CLIPPLANE4
fClipDistance4=dot(worldPos,vClipPlane4);
#endif
#ifdef CLIPPLANE5
fClipDistance5=dot(worldPos,vClipPlane5);
#endif
#ifdef CLIPPLANE6
fClipDistance6=dot(worldPos,vClipPlane6);
#endif
`;W.IncludesShadersStore[SR]=CR;const vR="fogVertex",bR=`#ifdef FOG
vFogDistance=(view*worldPos).xyz;
#endif
`;W.IncludesShadersStore[vR]=bR;const AR="shadowsVertex",yR=`#ifdef SHADOWS
#if defined(SHADOWCSM{X})
vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
}
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vPositionFromLight{X}=lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif
`;W.IncludesShadersStore[AR]=yR;const RR="vertexColorMixing",IR=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
vColor=vec4(1.0);
#ifdef VERTEXCOLOR
#ifdef VERTEXALPHA
vColor*=color;
#else
vColor.rgb*=color.rgb;
#endif
#endif
#ifdef INSTANCESCOLOR
vColor*=instanceColor;
#endif
#endif
`;W.IncludesShadersStore[RR]=IR;const PR="pointCloudVertex",MR=`#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
`;W.IncludesShadersStore[PR]=MR;const DR="logDepthVertex",OR=`#ifdef LOGARITHMICDEPTH
vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
#endif
`;W.IncludesShadersStore[DR]=OR;const NR="defaultVertexShader",FR=`#include<__decl__defaultVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
vPositionW=vec3(worldPos);
#include<prePassVertex>
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#include<uvVariableDeclaration>[2..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<pointCloudVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;W.ShadersStore[NR]=FR;const wR=new RegExp("^([gimus]+)!");class Ba{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let s=0;s<this._plugins.length;++s)if(this._plugins[s].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;const t=e.getClassName();Ba._MaterialPluginClassToMainDefine[t]||(Ba._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++Ba._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(s,r)=>this._handlePluginEvent(s,r),this._plugins.push(e),this._plugins.sort((s,r)=>s.priority-r.priority),this._codeInjectionPoints={};const i={};i[Ba._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const i of this._activePluginsForExtraEvents)if(t=i.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){switch(e){case Es.GetActiveTextures:{const i=t;for(const s of this._activePlugins)s.getActiveTextures(i.activeTextures);break}case Es.GetAnimatables:{const i=t;for(const s of this._activePlugins)s.getAnimatables(i.animatables);break}case Es.HasTexture:{const i=t;let s=!1;for(const r of this._activePlugins)if(s=r.hasTexture(i.texture),s)break;i.hasTexture=s;break}case Es.Disposed:{const i=t;for(const s of this._plugins)s.dispose(i.forceDisposeTextures);break}case Es.GetDefineNames:{const i=t;i.defineNames=this._defineNamesFromPlugins;break}case Es.PrepareEffect:{const i=t;for(const s of this._activePlugins)i.fallbackRank=s.addFallbacks(i.defines,i.fallbacks,i.fallbackRank),s.getAttributes(i.attributes,this._scene,i.mesh);this._uniformList.length>0&&i.uniforms.push(...this._uniformList),this._samplerList.length>0&&i.samplers.push(...this._samplerList),this._uboList.length>0&&i.uniformBuffersNames.push(...this._uboList),i.customCode=this._injectCustomCode(i,i.customCode);break}case Es.PrepareUniformBuffer:{const i=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const s of this._plugins){const r=s.getUniforms();if(r){if(r.ubo)for(const n of r.ubo){if(n.size&&n.type){const o=n.arraySize??0;i.ubo.addUniform(n.name,n.size,o),this._uboDeclaration+=`${n.type} ${n.name}${o>0?`[${o}]`:""};
`}this._uniformList.push(n.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+`
`),r.fragment&&(this._fragmentDeclaration+=r.fragment+`
`)}s.getSamplers(this._samplerList),s.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{var o,l;t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!r)return s;let n=null;for(let h in r){let c="";for(const u of this._activePlugins){let d=(l=u.getCustomCode(i))==null?void 0:l[h];if(d){if(u.resolveIncludes){if(n===null){const f=Zt.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:W.GetShadersRepository(f),includesShadersStore:W.GetIncludesShadersStore(f),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment=i==="fragment",Fr._ProcessIncludes(d,n,f=>d=f)}c+=d+`
`}}if(c.length>0)if(h.charAt(0)==="!"){h=h.substring(1);let u="g";if(h.charAt(0)==="!")u="",h=h.substring(1);else{const p=wR.exec(h);p&&p.length>=2&&(u=p[1],h=h.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const d=s,f=new RegExp(h,u);let _=f.exec(d);for(;_!==null;){let p=c;for(let g=0;g<_.length;++g)p=p.replace("$"+g,_[g]);s=s.replace(_[0],p),_=f.exec(d)}}else{const u="#define "+h;s=s.replace(u,`
`+c+`
`+u)}}return s}}}Ba._MaterialPluginClassToMainDefine={};Ba._MaterialPluginCounter=0;Ae.OnEnginesDisposedObservable.add(()=>{BR()});const LR=[];let Ex=null;function BR(){LR.length=0,ee.OnEventObservable.remove(Ex),Ex=null}class Zs{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new Ba(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){_e.Clone(()=>e,this)}serialize(){return _e.Serialize(this)}parse(e,t,i){_e.Parse(()=>this,e,t,i)}}E([I()],Zs.prototype,"name",void 0);E([I()],Zs.prototype,"priority",void 0);E([I()],Zs.prototype,"resolveIncludes",void 0);E([I()],Zs.prototype,"registerForExtraEvents",void 0);class UR extends Vs{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class ho extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new UR,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ee.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&&ue.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&&ue.DetailTextureEnabled&&this._isEnabled?(qt(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&&ue.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Gt(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&ue.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}E([ht("detailTexture"),te("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"texture",void 0);E([I()],ho.prototype,"diffuseBlendLevel",void 0);E([I()],ho.prototype,"roughnessBlendLevel",void 0);E([I()],ho.prototype,"bumpLevel",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"normalBlendMethod",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ho.prototype,"isEnabled",void 0);const O_={effect:null,subMesh:null};class VR extends Vs{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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 de extends vc{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 q(0,0,0),this.diffuseColor=new q(1,1,1),this.specularColor=new q(1,1,1),this.emissiveColor=new q(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 Wi(16),this._worldViewProjectionMatrix=D.Zero(),this._globalAmbientColor=new q(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new ho(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Jd,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),de.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),de.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 de.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||de.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===ee.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==ee.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Es.GetDefineNames,this._eventInfo),t.materialDefines=new VR(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=qu(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),Pf(r,n);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(bm(r,n,this.canRenderToMRT&&!l),kE(r,n,l),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let c=1;c<=6;++c)n["MAINUV"+c]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&de.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())qt(this._diffuseTexture,n,"DIFFUSE");else return!1;else n.DIFFUSE=!1;if(this._ambientTexture&&de.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())qt(this._ambientTexture,n,"AMBIENT");else return!1;else n.AMBIENT=!1;if(this._opacityTexture&&de.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())qt(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else n.OPACITY=!1;if(this._reflectionTexture&&de.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===k.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case k.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case k.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case k.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case k.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case k.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case k.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case k.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case k.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case k.CUBIC_MODE:case k.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC");break}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&de.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())qt(this._emissiveTexture,n,"EMISSIVE");else return!1;else n.EMISSIVE=!1;if(this._lightmapTexture&&de.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())qt(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else n.LIGHTMAP=!1;if(this._specularTexture&&de.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())qt(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&de.BumpTextureEnabled){if(this._bumpTexture.isReady())qt(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&de.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,n.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(de.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),yf(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Rf(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),If(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(n.isDirty){const c=n._areLightsDisposed;n.markAsProcessed();const u=new zo;n.REFLECTION&&u.addFallback(0,"REFLECTION"),n.SPECULAR&&u.addFallback(0,"SPECULAR"),n.BUMP&&u.addFallback(0,"BUMP"),n.PARALLAX&&u.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&u.addFallback(1,"FOG"),n.POINTSIZE&&u.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),Cm(n,u,this._maxSimultaneousLights),n.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&u.addFallback(4,"FRESNEL"),n.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const d=[y.PositionKind];n.NORMAL&&d.push(y.NormalKind),n.TANGENT&&d.push(y.TangentKind);for(let b=1;b<=6;++b)n["UV"+b]&&d.push(`uv${b===1?"":b}`);n.VERTEXCOLOR&&d.push(y.ColorKind),Sm(d,e,n,u),Af(d,n),xm(d,e,n),Tm(d,e,n);let f="default";const _=["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"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],x={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=_,this._eventInfo.attributes=d,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=x,this._callbackPluginEventGeneric(Es.PrepareEffect,this._eventInfo),Jd.AddUniforms(_),lt&&(lt.PrepareUniforms(_,n),lt.PrepareSamplers(p,n)),Mf({uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),sn(_);const T={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,_,g,p,n,d,T));const S=n.toString(),C=t.effect;let v=r.getEngine().createEffect(f,{attributes:d,uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:S,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:x,processFinalCode:T.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,v)if(this._onEffectCreatedObservable&&(O_.effect=v,O_.subMesh=t,this._onEffectCreatedObservable.notifyObservers(O_)),this.allowShaderHotSwapping&&C&&!v.isReady()){if(v=C,n.markAsUnprocessed(),h=this.isFrozen,c)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(v,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!h,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var h;const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);Ku(t,n);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(de.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new q(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&de.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gt(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&de.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Gt(this._ambientTexture,l,"ambient")),this._opacityTexture&&de.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gt(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&de.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;l.updateVector3("vReflectionPosition",c.boundingBoxPosition),l.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&de.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gt(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&de.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gt(this._lightmapTexture,l,"lightmap")),this._specularTexture&&de.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Gt(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&de.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Gt(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&de.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;l.updateVector3("vRefractionPosition",u.boundingBoxPosition),l.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",de.EmissiveTextureEnabled?this.emissiveColor:q.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&de.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&de.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&de.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&de.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&de.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&de.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&de.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&de.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&de.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Gr(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&ju(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Ee.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Go(s,t,n),r.NUM_MORPH_INFLUENCERS&&Sa(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&((h=t.bakedVertexAnimationManager)==null||h.bind(n,r.INSTANCES)),this.useLogarithmicDepth&&ao(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),l.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,s,r,n,o,l,h,c,u;t&&((i=this._diffuseTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(r=this._opacityTexture)==null||r.dispose(),(n=this._reflectionTexture)==null||n.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(h=this._bumpTexture)==null||h.dispose(),(c=this._lightmapTexture)==null||c.dispose(),(u=this._refractionTexture)==null||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=_e.Clone(()=>new de(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=_e.Parse(()=>new de(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ee._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return ue.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){ue.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return ue.DetailTextureEnabled}static set DetailTextureEnabled(e){ue.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return ue.AmbientTextureEnabled}static set AmbientTextureEnabled(e){ue.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return ue.OpacityTextureEnabled}static set OpacityTextureEnabled(e){ue.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return ue.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){ue.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return ue.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){ue.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return ue.SpecularTextureEnabled}static set SpecularTextureEnabled(e){ue.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return ue.BumpTextureEnabled}static set BumpTextureEnabled(e){ue.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return ue.LightmapTextureEnabled}static set LightmapTextureEnabled(e){ue.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return ue.RefractionTextureEnabled}static set RefractionTextureEnabled(e){ue.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return ue.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){ue.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return ue.FresnelEnabled}static set FresnelEnabled(e){ue.FresnelEnabled=e}}E([ht("diffuseTexture")],de.prototype,"_diffuseTexture",void 0);E([te("_markAllSubMeshesAsTexturesAndMiscDirty")],de.prototype,"diffuseTexture",void 0);E([ht("ambientTexture")],de.prototype,"_ambientTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"ambientTexture",void 0);E([ht("opacityTexture")],de.prototype,"_opacityTexture",void 0);E([te("_markAllSubMeshesAsTexturesAndMiscDirty")],de.prototype,"opacityTexture",void 0);E([ht("reflectionTexture")],de.prototype,"_reflectionTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"reflectionTexture",void 0);E([ht("emissiveTexture")],de.prototype,"_emissiveTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"emissiveTexture",void 0);E([ht("specularTexture")],de.prototype,"_specularTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"specularTexture",void 0);E([ht("bumpTexture")],de.prototype,"_bumpTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"bumpTexture",void 0);E([ht("lightmapTexture")],de.prototype,"_lightmapTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"lightmapTexture",void 0);E([ht("refractionTexture")],de.prototype,"_refractionTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"refractionTexture",void 0);E([li("ambient")],de.prototype,"ambientColor",void 0);E([li("diffuse")],de.prototype,"diffuseColor",void 0);E([li("specular")],de.prototype,"specularColor",void 0);E([li("emissive")],de.prototype,"emissiveColor",void 0);E([I()],de.prototype,"specularPower",void 0);E([I("useAlphaFromDiffuseTexture")],de.prototype,"_useAlphaFromDiffuseTexture",void 0);E([te("_markAllSubMeshesAsTexturesAndMiscDirty")],de.prototype,"useAlphaFromDiffuseTexture",void 0);E([I("useEmissiveAsIllumination")],de.prototype,"_useEmissiveAsIllumination",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useEmissiveAsIllumination",void 0);E([I("linkEmissiveWithDiffuse")],de.prototype,"_linkEmissiveWithDiffuse",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"linkEmissiveWithDiffuse",void 0);E([I("useSpecularOverAlpha")],de.prototype,"_useSpecularOverAlpha",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useSpecularOverAlpha",void 0);E([I("useReflectionOverAlpha")],de.prototype,"_useReflectionOverAlpha",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useReflectionOverAlpha",void 0);E([I("disableLighting")],de.prototype,"_disableLighting",void 0);E([te("_markAllSubMeshesAsLightsDirty")],de.prototype,"disableLighting",void 0);E([I("useObjectSpaceNormalMap")],de.prototype,"_useObjectSpaceNormalMap",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useObjectSpaceNormalMap",void 0);E([I("useParallax")],de.prototype,"_useParallax",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useParallax",void 0);E([I("useParallaxOcclusion")],de.prototype,"_useParallaxOcclusion",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useParallaxOcclusion",void 0);E([I()],de.prototype,"parallaxScaleBias",void 0);E([I("roughness")],de.prototype,"_roughness",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"roughness",void 0);E([I()],de.prototype,"indexOfRefraction",void 0);E([I()],de.prototype,"invertRefractionY",void 0);E([I()],de.prototype,"alphaCutOff",void 0);E([I("useLightmapAsShadowmap")],de.prototype,"_useLightmapAsShadowmap",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useLightmapAsShadowmap",void 0);E([zu("diffuseFresnelParameters")],de.prototype,"_diffuseFresnelParameters",void 0);E([te("_markAllSubMeshesAsFresnelDirty")],de.prototype,"diffuseFresnelParameters",void 0);E([zu("opacityFresnelParameters")],de.prototype,"_opacityFresnelParameters",void 0);E([te("_markAllSubMeshesAsFresnelAndMiscDirty")],de.prototype,"opacityFresnelParameters",void 0);E([zu("reflectionFresnelParameters")],de.prototype,"_reflectionFresnelParameters",void 0);E([te("_markAllSubMeshesAsFresnelDirty")],de.prototype,"reflectionFresnelParameters",void 0);E([zu("refractionFresnelParameters")],de.prototype,"_refractionFresnelParameters",void 0);E([te("_markAllSubMeshesAsFresnelDirty")],de.prototype,"refractionFresnelParameters",void 0);E([zu("emissiveFresnelParameters")],de.prototype,"_emissiveFresnelParameters",void 0);E([te("_markAllSubMeshesAsFresnelDirty")],de.prototype,"emissiveFresnelParameters",void 0);E([I("useReflectionFresnelFromSpecular")],de.prototype,"_useReflectionFresnelFromSpecular",void 0);E([te("_markAllSubMeshesAsFresnelDirty")],de.prototype,"useReflectionFresnelFromSpecular",void 0);E([I("useGlossinessFromSpecularMapAlpha")],de.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"useGlossinessFromSpecularMapAlpha",void 0);E([I("maxSimultaneousLights")],de.prototype,"_maxSimultaneousLights",void 0);E([te("_markAllSubMeshesAsLightsDirty")],de.prototype,"maxSimultaneousLights",void 0);E([I("invertNormalMapX")],de.prototype,"_invertNormalMapX",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"invertNormalMapX",void 0);E([I("invertNormalMapY")],de.prototype,"_invertNormalMapY",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"invertNormalMapY",void 0);E([I("twoSidedLighting")],de.prototype,"_twoSidedLighting",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],de.prototype,"twoSidedLighting",void 0);E([I("applyDecalMapAfterDetailMap")],de.prototype,"_applyDecalMapAfterDetailMap",void 0);E([te("_markAllSubMeshesAsMiscDirty")],de.prototype,"applyDecalMapAfterDetailMap",void 0);V("BABYLON.StandardMaterial",de);Ee.DefaultMaterialFactory=a=>new de("default material",a);pe.prototype.createDynamicTexture=function(a,e,t,i){const s=new Tt(this,et.Dynamic);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?pe.GetExponentOfTwo(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?pe.GetExponentOfTwo(e,this._caps.maxTextureSize):e),s.width=a,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};pe.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,r=!1,n=!1){if(!a)return;const o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,a,!0,r);this._unpackFlipY(t===void 0?a.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(a.type),u=this._getInternalFormat(s||a.format),d=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(l,0,d,u,c,e),a.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(a.format=s),a._dynamicTextureSource=e,a._premulAlpha=i,a.invertY=t||!1,a.isReady=!0};class yu extends k{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=k.CLAMP_ADDRESSMODE,this.wrapV=k.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=l.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,s,r):this._texture=l.createDynamicTexture(t,t,s,r));const h=this.getSize();this._canvas.width!==h.width&&(this._canvas.width=h.width),this._canvas.height!==h.height&&(this._canvas.height=h.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,l=!0){const h=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,h.width,h.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(h.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=h.height/2+c/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new yu(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&O.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return yu._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}class Bm{get isFixedFoveationSupported(){return this.layerType=="XRWebGLLayer"&&typeof this.layer.fixedFoveation=="number"}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class Um{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Tt(this._engine,et.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Ec(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},l=n?new lp(this._scene,o):new oi("XR renderTargetTexture",o,this._scene),h=l.renderTarget;if(h._samples=l.samples,(i||!s)&&(h._framebuffer=i),s)if(n)h._colorTextureArray=s;else{const c=this._createInternalTexture(o,s);h.setTexture(c,0),l._texture=c}return r&&(n?h._depthStencilTextureArray=r:h._depthStencilTexture=this._createInternalTexture(o,r)),l.disableRescaling(),this._renderTargetTextures.push(l),l}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}}class Vm extends Bm{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new kR(t.scene,this)),this.layer=e}}class kR extends Um{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||s!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Xf{static GetDefaults(e){const t=new Xf;return t.canvasOptions={antialias:!0,depth:!0,stencil:e?e.isStencilEnable:!0,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class GR{constructor(e,t=Xf.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new G,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const i=document.createElement("canvas");i.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(i)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Vm(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{X.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>t()):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){!this._canvas||!this._engine||(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class zR extends Bm{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new WR(t,this)),this.layer=e}}class WR extends Um{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class HR{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Yf{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new G,this.onXRReferenceSpaceChanged=new G,this.onXRSessionEnded=new G,this.onXRSessionInit=new G,this.onXRReferenceSpaceInitialized=new G,this.onXRReady=new G,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new G(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),(e=this._engine)==null||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{O.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)==null?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)==null?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new HR(this):(e=e||Xf.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new GR(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(i=>(this.session=i,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(i),this.session.addEventListener("end",()=>{var s;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&((s=this._baseLayerRTTProvider)==null||s.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return Yf.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;!this.inXRSession||!this._engine||(this._engine.customAnimationFrameRequester={requestAnimationFrame:t=>this.session.requestAnimationFrame(t),renderFunction:(t,i)=>{var s;if(!(!this.inXRSession||!this._engine)&&(this.currentFrame=i,this.currentTimestamp=t,i)){this.inXRFrameLoop=!0;const r=((s=this._baseLayerRTTProvider)==null?void 0:s.getFramebufferDimensions())||null;this._engine.framebufferDimensionsObject!==r&&(this._engine.framebufferDimensionsObject=r),this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)==null?void 0:e.getFramebufferDimensions())||null,this.onXRFrameObservable.addOnce(()=>{this.onXRReady.notifyObservers(this)}),typeof window<"u"&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(t=>t,t=>(O.Error("XR.requestReferenceSpace failed for the following reason: "),O.Error(t),O.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const s=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(s)},i=>{throw O.Error(i),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(t=>this.session.requestReferenceSpace("viewer").then(i=>(this.viewerReferenceSpace=i,t))).then(t=>(this.referenceSpace=this.baseReferenceSpace=t,this.onXRReferenceSpaceInitialized.notifyObservers(t),this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)==null||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)==null?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new zR(e.baseLayer):new Vm(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(i=>{const s=typeof i>"u"?!0:i;return Promise.resolve(s)}).catch(i=>(O.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){var e;return(e=this.session)==null?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)==null?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)==null?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){var e;return((e=this.session)==null?void 0:e.enabledFeatures)??null}}var qi;(function(a){a[a.ENTERING_XR=0]="ENTERING_XR",a[a.EXITING_XR=1]="EXITING_XR",a[a.IN_XR=2]="IN_XR",a[a.NOT_IN_XR=3]="NOT_IN_XR"})(qi||(qi={}));var pl;(function(a){a[a.NOT_TRACKING=0]="NOT_TRACKING",a[a.TRACKING_LOST=1]="TRACKING_LOST",a[a.TRACKING=2]="TRACKING"})(pl||(pl={}));z._GroundMeshParser=(a,e)=>Zu.Parse(a,e);class Zu extends z{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=U.Matrix[5];i.invertToRef(s);const r=U.Vector3[8];if(m.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return m.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new m(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=U.Matrix[5];s.invertToRef(r);const n=U.Vector3[8];if(m.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return m.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return t<r.slope.x*e+r.slope.y?n=r.facet1:n=r.facet2,n}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(let i=0;i<t;i++)for(let s=0;s<e;s++){const r={slope:Z.Zero(),facet1:new we(0,0,0,0),facet2:new we(0,0,0,0)};this._heightQuads[i*e+s]=r}return this}_computeHeightQuads(){const e=this.getVerticesData(y.PositionKind);if(!e)return this;const t=U.Vector3[3],i=U.Vector3[2],s=U.Vector3[1],r=U.Vector3[0],n=U.Vector3[4],o=U.Vector3[5],l=U.Vector3[6],h=U.Vector3[7],c=U.Vector3[8];let u=0,d=0,f=0,_=0,p=0,g=0,x=0;const T=this._subdivisionsX,S=this._subdivisionsY;for(let C=0;C<S;C++)for(let v=0;v<T;v++){u=v*3,d=C*(T+1)*3,f=(C+1)*(T+1)*3,t.x=e[d+u],t.y=e[d+u+1],t.z=e[d+u+2],i.x=e[d+u+3],i.y=e[d+u+4],i.z=e[d+u+5],s.x=e[f+u],s.y=e[f+u+1],s.z=e[f+u+2],r.x=e[f+u+3],r.y=e[f+u+4],r.z=e[f+u+5],_=(r.z-t.z)/(r.x-t.x),p=t.z-_*t.x,i.subtractToRef(t,n),s.subtractToRef(t,o),r.subtractToRef(t,l),m.CrossToRef(l,o,h),m.CrossToRef(n,l,c),h.normalize(),c.normalize(),g=-(h.x*t.x+h.y*t.y+h.z*t.z),x=-(c.x*i.x+c.y*i.y+c.z*i.z);const b=this._heightQuads[C*T+v];b.slope.copyFromFloats(_,p),b.facet1.copyFromFloats(h.x,h.y,h.z,g),b.facet2.copyFromFloats(c.x,c.y,c.z,x)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const i=new Zu(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}function ia(a){const e=[],t=[],i=[],s=[];let r,n;const o=a.width||1,l=a.height||1,h=(a.subdivisionsX||a.subdivisions||1)|0,c=(a.subdivisionsY||a.subdivisions||1)|0;for(r=0;r<=c;r++)for(n=0;n<=h;n++){const d=new m(n*o/h-o/2,0,(c-r)*l/c-l/2),f=new m(0,1,0);t.push(d.x,d.y,d.z),i.push(f.x,f.y,f.z),s.push(n/h,mt.UseOpenGLOrientationForUV?r/c:1-r/c)}for(r=0;r<c;r++)for(n=0;n<h;n++)e.push(n+1+(r+1)*(h+1)),e.push(n+1+r*(h+1)),e.push(n+r*(h+1)),e.push(n+(r+1)*(h+1)),e.push(n+1+(r+1)*(h+1)),e.push(n+r*(h+1));const u=new le;return u.indices=e,u.positions=t,u.normals=i,u.uvs=s,u}function lS(a){const e=a.xmin!==void 0&&a.xmin!==null?a.xmin:-1,t=a.zmin!==void 0&&a.zmin!==null?a.zmin:-1,i=a.xmax!==void 0&&a.xmax!==null?a.xmax:1,s=a.zmax!==void 0&&a.zmax!==null?a.zmax:1,r=a.subdivisions||{w:1,h:1},n=a.precision||{w:1,h:1},o=[],l=[],h=[],c=[];let u,d,f,_;r.h=r.h<1?1:r.h,r.w=r.w<1?1:r.w,n.w=n.w<1?1:n.w,n.h=n.h<1?1:n.h;const p={w:(i-e)/r.w,h:(s-t)/r.h};function g(T,S,C,v){const b=l.length/3,A=n.w+1;for(u=0;u<n.h;u++)for(d=0;d<n.w;d++){const w=[b+d+u*A,b+(d+1)+u*A,b+(d+1)+(u+1)*A,b+d+(u+1)*A];o.push(w[1]),o.push(w[2]),o.push(w[3]),o.push(w[0]),o.push(w[1]),o.push(w[3])}const P=m.Zero(),L=new m(0,1,0);for(u=0;u<=n.h;u++)for(P.z=u*(v-S)/n.h+S,d=0;d<=n.w;d++)P.x=d*(C-T)/n.w+T,P.y=0,l.push(P.x,P.y,P.z),h.push(L.x,L.y,L.z),c.push(d/n.w,u/n.h)}for(f=0;f<r.h;f++)for(_=0;_<r.w;_++)g(e+_*p.w,t+f*p.h,e+(_+1)*p.w,t+(f+1)*p.h);const x=new le;return x.indices=o,x.positions=l,x.normals=h,x.uvs=c,x}function hS(a){const e=[],t=[],i=[],s=[];let r,n;const o=a.colorFilter||new q(.3,.59,.11),l=a.alphaFilter||0;let h=!1;if(a.minHeight>a.maxHeight){h=!0;const u=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=u}for(r=0;r<=a.subdivisions;r++)for(n=0;n<=a.subdivisions;n++){const u=new m(n*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-r)*a.height/a.subdivisions-a.height/2),d=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,f=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,_=(d+f*a.bufferWidth)*4;let p=a.buffer[_]/255,g=a.buffer[_+1]/255,x=a.buffer[_+2]/255;const T=a.buffer[_+3]/255;h&&(p=1-p,g=1-g,x=1-x);const S=p*o.r+g*o.g+x*o.b;T>=l?u.y=a.minHeight+(a.maxHeight-a.minHeight)*S:u.y=a.minHeight-rt,a.heightBuffer&&(a.heightBuffer[r*(a.subdivisions+1)+n]=u.y),t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/a.subdivisions,1-r/a.subdivisions)}for(r=0;r<a.subdivisions;r++)for(n=0;n<a.subdivisions;n++){const u=n+1+(r+1)*(a.subdivisions+1),d=n+1+r*(a.subdivisions+1),f=n+r*(a.subdivisions+1),_=n+(r+1)*(a.subdivisions+1),p=t[u*3+1]>=a.minHeight,g=t[d*3+1]>=a.minHeight,x=t[f*3+1]>=a.minHeight;p&&g&&x&&(e.push(u),e.push(d),e.push(f)),t[_*3+1]>=a.minHeight&&p&&x&&(e.push(_),e.push(u),e.push(f))}le.ComputeNormals(t,e,i);const c=new le;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function km(a,e={},t){const i=new Zu(a,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,ia(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function XR(a,e,t=null){const i=new z(a,t);return lS(e).applyToMesh(i,e.updatable),i}function YR(a,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new q(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||Ae.LastCreatedScene;const f=new Zu(a,i);f._subdivisionsX=n,f._subdivisionsY=n,f._width=s,f._height=r,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);let _;t.passHeightBufferInCallback&&(_=new Float32Array((n+1)*(n+1)));const p=(g,x,T)=>{hS({width:s,height:r,subdivisions:n,minHeight:o,maxHeight:l,colorFilter:h,buffer:g,bufferWidth:x,bufferHeight:T,alphaFilter:c,heightBuffer:_}).applyToMesh(f,u),d&&d(f,_),f._setReady(!0)};if(typeof e=="string"){const g=x=>{const T=x.width,S=x.height;if(i.isDisposed)return;const C=i==null?void 0:i.getEngine().resizeImageBitmap(x,T,S);p(C,T,S)};X.LoadImage(e,g,t.onError?t.onError:()=>{},i.offlineProvider)}else p(e.data,e.width,e.height);return f}le.CreateGround=ia;le.CreateTiledGround=lS;le.CreateGroundFromHeightMap=hS;z.CreateGround=(a,e,t,i,s,r)=>km(a,{width:e,height:t,subdivisions:i,updatable:r},s);z.CreateTiledGround=(a,e,t,i,s,r,n,o,l)=>XR(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:l},o);z.CreateGroundFromHeightMap=(a,e,t,i,s,r,n,o,l,h,c)=>YR(a,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},o);function Gm(a){const e=[],t=[],i=[],s=[],r=a.diameter||1,n=a.thickness||.5,o=(a.tessellation||16)|0,l=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,h=o+1;for(let u=0;u<=o;u++){const d=u/o,f=u*Math.PI*2/o-Math.PI/2,_=D.Translation(r/2,0,0).multiply(D.RotationY(f));for(let p=0;p<=o;p++){const g=1-p/o,x=p*Math.PI*2/o+Math.PI,T=Math.cos(x),S=Math.sin(x);let C=new m(T,S,0),v=C.scale(n/2);const b=new Z(d,g);v=m.TransformCoordinates(v,_),C=m.TransformNormal(C,_),t.push(v.x,v.y,v.z),i.push(C.x,C.y,C.z),s.push(b.x,mt.UseOpenGLOrientationForUV?1-b.y:b.y);const A=(u+1)%h,P=(p+1)%h;e.push(u*h+p),e.push(u*h+P),e.push(A*h+p),e.push(u*h+P),e.push(A*h+P),e.push(A*h+p)}}le._ComputeSides(l,t,e,i,s,a.frontUVs,a.backUVs);const c=new le;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Bl(a,e={},t){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Gm(e).applyToMesh(i,e.updatable),i}le.CreateTorus=Gm;z.CreateTorus=(a,e,t,i,s,r,n)=>Bl(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);class $f{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=$f._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Bl("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new de("targetMat",e);i.specularColor=q.Black(),i.emissiveColor=new q(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new tt(m.Zero(),new m(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}$f._IdCounter=0;class Sx extends $f{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new tt(m.Zero(),m.Forward())}}class Ul{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new G,this.onAfterEnteringVRObservable=new G,this.onExitingVRObservable=new G,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Ul.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new m(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new m(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new q(.2,.2,1),this._pickedGazeColor=new q(0,0,1),this.onNewMeshSelected=new G,this.onNewMeshPicked=new G,this.onBeforeCameraTeleport=new G,this.onAfterCameraTeleport=new G,this.onSelectedMeshUnselected=new G,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=s=>{s.type!==us.POSE_ENABLED&&(s.leftStick&&s.onleftstickchanged(r=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(r,this._cameraGazer),this._checkTeleportBackwards(r,this._cameraGazer))}),s.rightStick&&s.onrightstickchanged(r=>{this._teleportationInitialized&&this._checkRotate(r,this._cameraGazer)}),s.type===us.XBOX&&(s.onbuttondown(r=>{this._interactionsEnabled&&r===xr.A&&this._cameraGazer._selectionPointerDown()}),s.onbuttonup(r=>{this._interactionsEnabled&&r===xr.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=m.Zero(),this._workingQuaternion=Q.Identity(),this._workingMatrix=D.Identity(),O.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),!("getVRDisplays"in navigator)&&t.useXR===void 0&&(t.useXR=!0),t.createFallbackVRDeviceOrientationFreeCamera===void 0&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),t.createDeviceOrientationCamera===void 0&&(t.createDeviceOrientationCamera=!0),t.laserToggle===void 0&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new m(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Nm("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Ai&&this._scene.activeCamera.rotation)){const s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Q.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Yf.IsSessionSupportedAsync("immersive-vr").then(s=>{s?(O.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(r=>{this.xr=r,this.xrTestDone=!0,this._cameraGazer=new Sx(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(n=>{switch(n){case qi.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case qi.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case qi.IN_XR:this._hasEnteredVR=!0;break;case qi.NOT_IN_XR:this._hasEnteredVR=!1;break}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Lm("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new Sx(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let r=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";r+=".babylonVRicon.vrdisplaypresenting { display: none; }";const n=document.createElement("style");n.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(n),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=s=>{s.keyCode===27&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},Re.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new qv,this._circleEase.setEasingMode(Us.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(s=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===Re.POINTERDOWN?this._cameraGazer._selectionPointerDown():s.type===Re.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===qi.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){!this._useCustomVRButton&&!this._btnVRDisplayed&&this._btnVR&&(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){!this._btnVR||this._useCustomVRButton||(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){O.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Q.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){O.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===qi.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>this._isTeleportationFloor(e)||e.name.indexOf("gazeTracker")===-1&&e.name.indexOf("teleportationTarget")===-1&&e.name.indexOf("torusTeleportation")===-1?this.raySelectionPredicate(e):!1,this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!!(this._floorMeshName&&e.name===this._floorMeshName)}addFloorMesh(e){this._floorMeshesCollection&&(this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);t!==-1&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const i=e.floorMeshes||[];if(!i.length){const s=this._scene.getMeshByName(e.floorMeshName);s&&i.push(s)}if(this.xr){i.forEach(s=>{this.xr.teleportation.addFloorMesh(s)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const s=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(s),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(s);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),e.easingFunction!==void 0&&(this._teleportationEasing=e.easingFunction);const t=new lt;t.vignetteColor=new xe(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))}_checkRotate(e,t){t._teleportationRequestInitiated||(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const i=Q.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Q.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),m.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new tt(s,this._workingVector),n=this._scene.pickWithRay(r,this._raySelectionPredicate);n&&n.pickedPoint&&n.pickedMesh&&this._isTeleportationFloor(n.pickedMesh)&&n.distance<5&&this.teleportCamera(n.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=km("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new yu("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),s=e/2,r=e/2,n=200;i.beginPath(),i.arc(s,r,n,0,2*Math.PI,!1),i.fillStyle=this._teleportationFillColor,i.fill(),i.lineWidth=10,i.strokeStyle=this._teleportationBorderColor,i.stroke(),i.closePath(),t.update();const o=new de("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const l=Bl("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const h=new K("animationInnerCircle","position.y",30,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CYCLE),c=[];c.push({frame:0,value:0}),c.push({frame:30,value:.4}),c.push({frame:60,value:0}),h.setKeys(c);const u=new FE;u.setEasingMode(Us.EASINGMODE_EASEINOUT),h.setEasingFunction(u),l.animations=[],l.animations.push(h),this._scene.beginAnimation(l,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof qs))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=Q.FromRotationMatrix(D.RotationY(Math.PI/4*this._rotationAngle)),i=new K("animationRotation","rotationQuaternion",90,K.ANIMATIONTYPE_QUATERNION,K.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new K("animationPP","vignetteWeight",90,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new K("animationPP2","vignetteStretch",90,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),o.setKeys(l),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof qs))return;this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,s;if(this._teleportationMode==Ul.TELEPORTATIONMODE_CONSTANTSPEED){s=t;const d=m.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/d}else s=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const r=new K("animationCameraTeleportation","position",t,K.ANIMATIONTYPE_VECTOR3,K.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:s,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];const o=Math.round(s/2),l=new K("animationPP","vignetteWeight",t,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:o,value:8}),h.push({frame:s,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l);const c=new K("animationPP2","vignetteStretch",t,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:o,value:10}),u.push({frame:s,value:0}),c.setKeys(u),this._postProcessMove.animations.push(c),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,s,!1,i,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}Ul.TELEPORTATIONMODE_CONSTANTTIME=0;Ul.TELEPORTATIONMODE_CONSTANTSPEED=1;const $R=(a,e,t,i)=>!(a.x>t.x+i||t.x-i>e.x||a.y>t.y+i||t.y-i>e.y||a.z>t.z+i||t.z-i>e.z),al=function(){const a={root:0,found:!1};return function(e,t,i,s){a.root=0,a.found=!1;const r=t*t-4*e*i;if(r<0)return a;const n=Math.sqrt(r);let o=(-t-n)/(2*e),l=(-t+n)/(2*e);if(o>l){const h=l;l=o,o=h}return o>0&&o<s?(a.root=o,a.found=!0,a):(l>0&&l<s&&(a.root=l,a.found=!0),a)}}();class Kf{constructor(){this._collisionPoint=m.Zero(),this._planeIntersectionPoint=m.Zero(),this._tempVector=m.Zero(),this._tempVector2=m.Zero(),this._tempVector3=m.Zero(),this._tempVector4=m.Zero(),this._edge=m.Zero(),this._baseToVertex=m.Zero(),this._destinationPoint=m.Zero(),this._slidePlaneNormal=m.Zero(),this._displacementVector=m.Zero(),this._radius=m.One(),this._retry=0,this._basePointWorld=m.Zero(),this._velocityWorld=m.Zero(),this._normalizedVelocity=m.Zero(),this._collisionMask=-1}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}get slidePlaneNormal(){return this._slidePlaneNormal}_initialize(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();const s=Math.sqrt(this._velocitySquaredLength);s===0||s===1?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/s,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1}_checkPointInTriangle(e,t,i,s,r){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),m.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);let n=m.Dot(this._tempVector4,r);return n<0||(s.subtractToRef(e,this._tempVector3),m.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=m.Dot(this._tempVector4,r),n<0)?!1:(m.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=m.Dot(this._tempVector4,r),n>=0)}_canDoCollision(e,t,i,s){const r=m.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!$R(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let l,h=!1;t||(t=[]),t[e]||(t[e]=new Ks(0,0,0,0),t[e].copyFromPoints(i,s,r));const c=t[e];if(!n&&!c.isFrontFacingTo(this._normalizedVelocity,0))return;const u=c.signedDistanceTo(this._basePoint),d=m.Dot(c.normal,this._velocity);if(Kf.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/d;let p=(1-u)/d;if(l>p){const g=p;p=l,l=g}if(l>1||p<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,_=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,c.normal)&&(f=!0,_=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let p=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let g=2*m.Dot(this._velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,T=al(p,g,x,_);T.found&&(_=T.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),g=2*m.Dot(this._velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,T=al(p,g,x,_),T.found&&(_=T.root,f=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),g=2*m.Dot(this._velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,T=al(p,g,x,_),T.found&&(_=T.root,f=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let S=this._edge.lengthSquared(),C=m.Dot(this._edge,this._velocity),v=m.Dot(this._edge,this._baseToVertex);if(p=S*-this._velocitySquaredLength+C*C,g=2*(S*m.Dot(this._velocity,this._baseToVertex)-C*v),x=S*(1-this._baseToVertex.lengthSquared())+v*v,T=al(p,g,x,_),T.found){const b=(C*T.root-v)/S;b>=0&&b<=1&&(_=T.root,f=!0,this._edge.scaleInPlace(b),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),S=this._edge.lengthSquared(),C=m.Dot(this._edge,this._velocity),v=m.Dot(this._edge,this._baseToVertex),p=S*-this._velocitySquaredLength+C*C,g=2*(S*m.Dot(this._velocity,this._baseToVertex)-C*v),x=S*(1-this._baseToVertex.lengthSquared())+v*v,T=al(p,g,x,_),T.found){const b=(C*T.root-v)/S;b>=0&&b<=1&&(_=T.root,f=!0,this._edge.scaleInPlace(b),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),S=this._edge.lengthSquared(),C=m.Dot(this._edge,this._velocity),v=m.Dot(this._edge,this._baseToVertex),p=S*-this._velocitySquaredLength+C*C,g=2*(S*m.Dot(this._velocity,this._baseToVertex)-C*v),x=S*(1-this._baseToVertex.lengthSquared())+v*v,T=al(p,g,x,_),T.found){const b=(C*T.root-v)/S;b>=0&&b<=1&&(_=T.root,f=!0,this._edge.scaleInPlace(b),r.addToRef(this._edge,this._collisionPoint))}}if(f){const p=_*_*this._velocitySquaredLength;(!this.collisionFound||p<this._nearestDistanceSquared)&&(o.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=p,this._nearestDistance=Math.sqrt(p),this.collisionFound=!0),this.collidedMesh=o)}}_collide(e,t,i,s,r,n,o,l,h,c=!1){if(c)if(!i||i.length===0)for(let u=0;u<t.length-2;u+=1){const d=t[u],f=t[u+1],_=t[u+2];!d||!f||!_||((h?1:0)^u%2?this._testTriangle(u,e,d,f,_,o,l):this._testTriangle(u,e,f,d,_,o,l))}else for(let u=s;u<r-2;u+=1){const d=i[u],f=i[u+1],_=i[u+2];if(_===4294967295){u+=2;continue}const p=t[d],g=t[f],x=t[_];!p||!g||!x||((h?1:0)^u%2?this._testTriangle(u,e,p,g,x,o,l):this._testTriangle(u,e,g,p,x,o,l))}else if(!i||i.length===0)for(let u=0;u<t.length;u+=3){const d=t[u],f=t[u+1],_=t[u+2];h?this._testTriangle(u,e,d,f,_,o,l):this._testTriangle(u,e,_,f,d,o,l)}else for(let u=s;u<r;u+=3){const d=t[i[u]-n],f=t[i[u+1]-n],_=t[i[u+2]-n];h?this._testTriangle(u,e,d,f,_,o,l):this._testTriangle(u,e,_,f,d,o,l)}}_getResponse(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(Ks.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)}}Kf.DoubleSidedCheck=!1;class KR{constructor(){this._scaledPosition=m.Zero(),this._scaledVelocity=m.Zero(),this._finalPosition=m.Zero()}getNewPosition(e,t,i,s,r,n,o){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,s,this._finalPosition,r),this._finalPosition.multiplyInPlace(i._radius),n(o,this._finalPosition,i.collidedMesh)}createCollider(){return new Kf}init(e){this._scene=e}_collideWithWorld(e,t,i,s,r,n=null){const o=H.CollisionsEpsilon*10;if(i._retry>=s){r.copyFrom(e);return}const l=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const h=n&&n.surroundingMeshes||this._scene.meshes;for(let c=0;c<h.length;c++){const u=h[c];u.isEnabled()&&u.checkCollisions&&u.subMeshes&&u!==n&&l&u.collisionGroup&&u._checkCollision(i)}if(!i.collisionFound){e.addToRef(t,r);return}if((t.x!==0||t.y!==0||t.z!==0)&&i._getResponse(e,t),t.length()<=o){r.copyFrom(e);return}i._retry++,this._collideWithWorld(e,t,i,s,r,n)}}Ee.CollisionCoordinatorFactory=()=>new KR;class Vl{constructor(e,t,i,s=""){this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new G,this.onErrorObservable=new G,this.onBindObservable=new G,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Zt.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=Vl._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=W.GetShadersStore(this._shaderLanguage),this._shaderRepository=W.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=W.GetIncludesShadersStore(this._shaderLanguage);let r;const n=ls()?this._engine.getHostDocument():null;e.computeSource?r="source:"+e.computeSource:e.computeElement?(r=n?n.getElementById(e.computeElement):null,r||(r=e.computeElement)):r=e.compute||e;const o={defines:this.defines.split(`
`),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",l=>{Fr.Initialize(o),Fr.PreProcess(l,o,h=>{this._rawComputeSourceCode=l,t.processFinalCode&&(h=t.processFinalCode(h));const c=Fr.Finalize(h,"",o);this._useFinalCode(c.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+`
`+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const n=dm(e);s(n);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const n=window.atob(e.substr(7));s(n);return}if(this._shaderStore[e+t+"Shader"]){s(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){s(this._shaderStore[e+i+"Shader"]);return}let r;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?r=e:r=this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){var e;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:((e=this._pipelineContext)==null?void 0:e._getComputeShaderCode())??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t){const i=/COMPUTE SHADER ERROR: 0:(\d+?):/;let s=null;if(t&&e){const r=t.match(i);if(r&&r.length===2){const n=parseInt(r[1]),o=e.split(`
`,-1);o.length>=n&&(s=`Offending line [${n}] in compute code: ${o[n-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,O.Error("Unable to compile compute effect:"),O.Error(`Defines:
`+this.defines),Vl.LogShaderCodeOnCompilationError){let s=null,r=null;(i=this._pipelineContext)!=null&&i._getComputeShaderCode()&&([r,s]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),r&&(O.Error("Compute code:"),O.Error(r))),s&&O.Error(s)}O.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){W.GetShadersStore(Zt.WGSL)[`${e}ComputeShader`]=t}}Vl._UniqueIdSeed=0;Vl.LogShaderCodeOnCompilationError=!0;var Vt;(function(a){a[a.Texture=0]="Texture",a[a.StorageTexture=1]="StorageTexture",a[a.UniformBuffer=2]="UniformBuffer",a[a.StorageBuffer=3]="StorageBuffer",a[a.TextureWithoutSampler=4]="TextureWithoutSampler",a[a.Sampler=5]="Sampler",a[a.ExternalTexture=6]="ExternalTexture",a[a.DataBuffer=7]="DataBuffer"})(Vt||(Vt={}));pe.prototype.createComputeEffect=function(a,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};pe.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};pe.prototype.createComputeContext=function(){};pe.prototype.computeDispatch=function(a,e,t,i,s,r,n){throw new Error("computeDispatch: This engine does not support compute shaders!")};pe.prototype.areAllComputeEffectsReady=function(){return!0};pe.prototype.releaseComputeEffects=function(){};pe.prototype._prepareComputePipelineContext=function(a,e,t,i,s){};pe.prototype._rebuildComputeEffects=function(){};pe.prototype._executeWhenComputeStateIsCompiled=function(a,e){e()};pe.prototype._releaseComputeEffect=function(a){};pe.prototype._deleteComputePipelineContext=function(a){};class zm{constructor(){this._gpuTimeInFrameId=-1,this.counter=new wr}_addDuration(e,t){e<this._gpuTimeInFrameId||(this._gpuTimeInFrameId!==e?(this.counter._fetchResult(),this.counter.fetchNewFrame(),this.counter.addCount(t,!1),this._gpuTimeInFrameId=e):this.counter.addCount(t,!1))}}class za{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,s={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.fastMode=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=Yu.UniqueId,t.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new zm),!this._engine.getCaps().supportComputeShaders){O.Error("This engine does not support compute shaders!");return}if(!s.bindingsMapping){O.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options={bindingsMapping:{},defines:[],...s}}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const s=this._bindings[e];this._bindings[e]={type:i?Vt.Texture:Vt.TextureWithoutSampler,object:t,indexInGroupEntries:s==null?void 0:s.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!s||s.object!==t||s.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Vt.StorageTexture,object:t,indexInGroupEntries:i==null?void 0:i.indexInGroupEntries}}setExternalTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Vt.ExternalTexture,object:t,indexInGroupEntries:i==null?void 0:i.indexInGroupEntries}}setVideoTexture(e,t){return t.externalTexture?(this.setExternalTexture(e,t.externalTexture),!0):!1}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:za._BufferIsDataBuffer(t)?Vt.DataBuffer:Vt.UniformBuffer,object:t,indexInGroupEntries:i==null?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:za._BufferIsDataBuffer(t)?Vt.DataBuffer:Vt.StorageBuffer,object:t,indexInGroupEntries:i==null?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:Vt.Sampler,object:t,indexInGroupEntries:i==null?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(const r in this._bindings){const n=this._bindings[r],o=n.type,l=n.object;switch(o){case Vt.Texture:case Vt.TextureWithoutSampler:case Vt.StorageTexture:{if(!l.isReady())return!1;break}case Vt.ExternalTexture:{if(!l.isReady())return!1;break}}}const t=[],i=this._shaderPath;if(this._options.defines)for(let r=0;r<this._options.defines.length;r++)t.push(this._options.defines[r]);const s=t.join(`
`);return this._cachedDefines!==s&&(this._cachedDefines=s,e=this._engine.createComputeEffect(i,{defines:s,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()}dispatch(e,t,i){var s;if(!this.fastMode){if(!this.isReady())return!1;for(const r in this._bindings){const n=this._bindings[r];if(!this._options.bindingsMapping[r])throw new Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+r+"'");switch(n.type){case Vt.Texture:{const o=this._samplers[r],l=n.object;(!o||!l._texture||!o.compareSampler(l._texture))&&(this._samplers[r]=new CE().setParameters(l.wrapU,l.wrapV,l.wrapR,l.anisotropicFilteringLevel,l._texture.samplingMode,(s=l._texture)==null?void 0:s._comparisonFunction),this._contextIsDirty=!0);break}case Vt.ExternalTexture:{this._contextIsDirty=!0;break}case Vt.UniformBuffer:{const o=n.object;o.getBuffer()!==n.buffer&&(n.buffer=o.getBuffer(),this._contextIsDirty=!0);break}}}this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear())}return this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping,this.gpuTimeInFrame),!0}dispatchWhenReady(e,t,i,s=10){return new Promise(r=>{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()})}serialize(){const e=_e.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case Vt.Texture:case Vt.TextureWithoutSampler:case Vt.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case Vt.UniformBuffer:break}}return e}static Parse(e,t,i){const s=_e.Parse(()=>new za(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=k.Parse(e.textures[r],t,i);n.type===Vt.Texture?s.setTexture(r,o):n.type===Vt.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return e.underlyingResource!==void 0}}E([I()],za.prototype,"name",void 0);E([I()],za.prototype,"fastMode",void 0);V("BABYLON.ComputeShader",za);class ef{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e);return}this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()}removeEntry(e){if(this.blocks){for(let i=0;i<this.blocks.length;i++)this.blocks[i].removeEntry(e);return}const t=this.entries.indexOf(e);t>-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t<e.length;t++){const i=e[t];this.addEntry(i)}}select(e,t,i){if(mn.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(let s=0;s<this.blocks.length;s++)this.blocks[s].select(e,t,i);return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}}intersects(e,t,i,s){if(mn.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(let r=0;r<this.blocks.length;r++)this.blocks[r].intersects(e,t,i,s);return}s?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}}intersectsRay(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(let i=0;i<this.blocks.length;i++)this.blocks[i].intersectsRay(e,t);return}t.concatWithNoDuplicate(this.entries)}}createInnerBlocks(){ef._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)}static _CreateBlocks(e,t,i,s,r,n,o,l){o.blocks=new Array;const h=new m((t.x-e.x)/2,(t.y-e.y)/2,(t.z-e.z)/2);for(let c=0;c<2;c++)for(let u=0;u<2;u++)for(let d=0;d<2;d++){const f=e.add(h.multiplyByFloats(c,u,d)),_=e.add(h.multiplyByFloats(c+1,u+1,d+1)),p=new ef(f,_,s,r+1,n,l);p.addEntries(i),o.blocks.push(p)}}}class kl{constructor(e,t,i=2){this.maxDepth=i,this.dynamicContent=[],this._maxBlockCapacity=t||64,this._selectionContent=new Ia(1024),this._creationFunc=e}update(e,t,i){ef._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)}addMesh(e){for(let t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e)}removeMesh(e){for(let t=0;t<this.blocks.length;t++)this.blocks[t].removeEntry(e)}select(e,t){this._selectionContent.reset();for(let i=0;i<this.blocks.length;i++)this.blocks[i].select(e,this._selectionContent,t);return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersects(e,t,i){this._selectionContent.reset();for(let s=0;s<this.blocks.length;s++)this.blocks[s].intersects(e,t,this._selectionContent,i);return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersectsRay(e){this._selectionContent.reset();for(let t=0;t<this.blocks.length;t++)this.blocks[t].intersectsRay(e,this._selectionContent);return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}}kl.CreationFuncForMeshes=(a,e)=>{const t=a.getBoundingInfo();!a.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};kl.CreationFuncForSubMeshes=(a,e)=>{a.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};Ee.prototype.createOrUpdateSelectionOctree=function(a=64,e=2){let t=this._getComponent(he.NAME_OCTREE);t||(t=new cS(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new kl(kl.CreationFuncForMeshes,a,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(Ee.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});ut.prototype.createOrUpdateSubmeshesOctree=function(a=64,e=2){const t=this.getScene();let i=t._getComponent(he.NAME_OCTREE);i||(i=new cS(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new kl(kl.CreationFuncForSubMeshes,a,e)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class cS{constructor(e){this.name=he.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new tt(m.Zero(),new m(1,1,1)),e=e||Ae.LastCreatedScene,e&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=t=>this.getActiveSubMeshCandidates(t),this.scene.getCollidingSubMeshCandidates=(t,i)=>this.getCollidingSubMeshCandidates(t,i),this.scene.getIntersectingSubMeshCandidates=(t,i)=>this.getIntersectingSubMeshCandidates(t,i))}register(){this.scene.onMeshRemovedObservable.add(e=>{const t=this.scene.selectionOctree;if(t!=null){const i=t.dynamicContent.indexOf(e);i!==-1&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{const t=this.scene.selectionOctree;t!=null&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return((e=this.scene._selectionOctree)==null?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(tt.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function Wm(a){const e=a.height||2;let t=a.diameterTop===0?0:a.diameterTop||a.diameter||1,i=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;t=t||1e-5,i=i||1e-5;const s=(a.tessellation||24)|0,r=(a.subdivisions||1)|0,n=!!a.hasRings,o=!!a.enclose,l=a.cap===0?0:a.cap||z.CAP_ALL,h=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,c=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,u=a.faceUV||new Array(3),d=a.faceColors,f=h!==1&&o?2:0,_=n?r:1,p=2+(1+f)*_;let g;for(g=0;g<p;g++)d&&d[g]===void 0&&(d[g]=new xe(1,1,1,1));for(g=0;g<p;g++)u&&u[g]===void 0&&(u[g]=new we(0,0,1,1));const x=[],T=[],S=[],C=[],v=[],b=Math.PI*2*h/s;let A,P,L;const w=(i-t)/2/e,$=m.Zero(),J=m.Zero(),ne=m.Zero(),oe=m.Zero(),re=m.Zero(),ce=Bs.Y;let Se,Ce,ae,ie=1,F=1,j=0,se=0;for(Se=0;Se<=r;Se++)for(P=Se/r,L=(P*(t-i)+i)/2,ie=n&&Se!==0&&Se!==r?2:1,ae=0;ae<ie;ae++){for(n&&(F+=ae),o&&(F+=2*ae),Ce=0;Ce<=s;Ce++)A=Ce*b,$.x=Math.cos(-A)*L,$.y=-e/2+P*e,$.z=Math.sin(-A)*L,t===0&&Se===r?(J.x=S[S.length-(s+1)*3],J.y=S[S.length-(s+1)*3+1],J.z=S[S.length-(s+1)*3+2]):(J.x=$.x,J.z=$.z,J.y=Math.sqrt(J.x*J.x+J.z*J.z)*w,J.normalize()),Ce===0&&(ne.copyFrom($),oe.copyFrom(J)),T.push($.x,$.y,$.z),S.push(J.x,J.y,J.z),n?se=j!==F?u[F].y:u[F].w:se=u[F].y+(u[F].w-u[F].y)*P,C.push(u[F].x+(u[F].z-u[F].x)*Ce/s,mt.UseOpenGLOrientationForUV?1-se:se),d&&v.push(d[F].r,d[F].g,d[F].b,d[F].a);h!==1&&o&&(T.push($.x,$.y,$.z),T.push(0,$.y,0),T.push(0,$.y,0),T.push(ne.x,ne.y,ne.z),m.CrossToRef(ce,J,re),re.normalize(),S.push(re.x,re.y,re.z,re.x,re.y,re.z),m.CrossToRef(oe,ce,re),re.normalize(),S.push(re.x,re.y,re.z,re.x,re.y,re.z),n?se=j!==F?u[F+1].y:u[F+1].w:se=u[F+1].y+(u[F+1].w-u[F+1].y)*P,C.push(u[F+1].x,mt.UseOpenGLOrientationForUV?1-se:se),C.push(u[F+1].z,mt.UseOpenGLOrientationForUV?1-se:se),n?se=j!==F?u[F+2].y:u[F+2].w:se=u[F+2].y+(u[F+2].w-u[F+2].y)*P,C.push(u[F+2].x,mt.UseOpenGLOrientationForUV?1-se:se),C.push(u[F+2].z,mt.UseOpenGLOrientationForUV?1-se:se),d&&(v.push(d[F+1].r,d[F+1].g,d[F+1].b,d[F+1].a),v.push(d[F+1].r,d[F+1].g,d[F+1].b,d[F+1].a),v.push(d[F+2].r,d[F+2].g,d[F+2].b,d[F+2].a),v.push(d[F+2].r,d[F+2].g,d[F+2].b,d[F+2].a))),j!==F&&(j=F)}const Ie=h!==1&&o?s+4:s;for(Se=0,F=0;F<r;F++){let fe=0,me=0,Xe=0,Fe=0;for(Ce=0;Ce<s;Ce++)fe=Se*(Ie+1)+Ce,me=(Se+1)*(Ie+1)+Ce,Xe=Se*(Ie+1)+(Ce+1),Fe=(Se+1)*(Ie+1)+(Ce+1),x.push(fe,me,Xe),x.push(Fe,Xe,me);h!==1&&o&&(x.push(fe+2,me+2,Xe+2),x.push(Fe+2,Xe+2,me+2),x.push(fe+4,me+4,Xe+4),x.push(Fe+4,Xe+4,me+4)),Se=n?Se+2:Se+1}const Ye=fe=>{const me=fe?t/2:i/2;if(me===0)return;let Xe,Fe,ke;const Ue=fe?u[p-1]:u[0];let Rt=null;d&&(Rt=fe?d[p-1]:d[0]);const hi=T.length/3,_i=fe?e/2:-e/2,pi=new m(0,_i,0);T.push(pi.x,pi.y,pi.z),S.push(0,fe?1:-1,0);const er=Ue.y+(Ue.w-Ue.y)*.5;C.push(Ue.x+(Ue.z-Ue.x)*.5,mt.UseOpenGLOrientationForUV?1-er:er),Rt&&v.push(Rt.r,Rt.g,Rt.b,Rt.a);const Os=new Z(.5,.5);for(ke=0;ke<=s;ke++){Xe=Math.PI*2*ke*h/s;const Ca=Math.cos(-Xe),va=Math.sin(-Xe);Fe=new m(Ca*me,_i,va*me);const po=new Z(Ca*Os.x+.5,va*Os.y+.5);T.push(Fe.x,Fe.y,Fe.z),S.push(0,fe?1:-1,0);const yn=Ue.y+(Ue.w-Ue.y)*po.y;C.push(Ue.x+(Ue.z-Ue.x)*po.x,mt.UseOpenGLOrientationForUV?1-yn:yn),Rt&&v.push(Rt.r,Rt.g,Rt.b,Rt.a)}for(ke=0;ke<s;ke++)fe?(x.push(hi),x.push(hi+(ke+2)),x.push(hi+(ke+1))):(x.push(hi),x.push(hi+(ke+1)),x.push(hi+(ke+2)))};(l===z.CAP_START||l===z.CAP_ALL)&&Ye(!1),(l===z.CAP_END||l===z.CAP_ALL)&&Ye(!0),le._ComputeSides(c,T,x,S,C,a.frontUVs,a.backUVs);const $e=new le;return $e.indices=x,$e.positions=T,$e.normals=S,$e.uvs=C,d&&($e.colors=v),$e}function Hm(a,e={},t){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Wm(e).applyToMesh(i,e.updatable),i}le.CreateCylinder=Wm;z.CreateCylinder=(a,e,t,i,s,r,n,o,l)=>((n===void 0||!(n instanceof Ee))&&(n!==void 0&&(l=o||z.DEFAULTSIDE,o=n),n=r,r=1),Hm(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:l,updatable:o},n));Ct.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new Ho(a,m.Zero(),e));class Ho extends st{constructor(e,t,i){super(e,i),this.groundColor=new q(0,0,0),this.direction=t||m.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=m.Normalize(e.subtract(m.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=m.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=m.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=D.Identity()),this._worldMatrix}getTypeID(){return st.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}E([li()],Ho.prototype,"groundColor",void 0);E([bs()],Ho.prototype,"direction",void 0);class Li{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?t=this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:t=this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Ho("shared gizmo light",new m(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=q.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return Li._DefaultUtilityLayer==null?Li._CreateDefaultUtilityLayerFromScene(Ae.LastCreatedScene):Li._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Li._DefaultUtilityLayer=new Li(e),Li._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Li._DefaultUtilityLayer=null}),Li._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return Li._DefaultKeepDepthUtilityLayer==null&&(Li._DefaultKeepDepthUtilityLayer=new Li(Ae.LastCreatedScene),Li._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Li._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Li._DefaultKeepDepthUtilityLayer=null})),Li._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new G,this.utilityLayerScene=new Ee(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(i=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&i.type!==Re.POINTERMOVE&&i.type!==Re.POINTERUP&&i.type!==Re.POINTERDOWN&&i.type!==Re.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const s=i.event;if(e.isPointerCaptured(s.pointerId)){this._pointerCaptures[s.pointerId]=!1;return}const r=o=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?l=i.nearInteractionPickingInfo:l=new es;else if(o!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let h=null;this._renderCamera&&(h=o._activeCamera,o._activeCamera=this._renderCamera,i.ray=null),l=i.ray?o.pickWithRay(i.ray):o.pick(e.pointerX,e.pointerY),h&&(o._activeCamera=h)}return l},n=r(this.utilityLayerScene);if(!i.ray&&n&&(i.ray=n.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=Re.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Zr(i.type,i.event,n),i.type),i.type===Re.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)n&&n.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Zr(i.type,i.event,n),i.type),i.skipOnPointerObservable=!0);else{const o=r(e),l=i.event;o&&n&&(n.distance===0&&o.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):i.type===Re.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===Re.POINTERMOVE||i.type===Re.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,o,l)):!this._pointerCaptures[l.pointerId]&&(n.distance<o.distance||o.distance===0)?(this._notifyObservers(i,n,l),i.skipOnPointerObservable||(i.skipOnPointerObservable=n.distance>0)):!this._pointerCaptures[l.pointerId]&&n.distance>=o.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):((i.type===Re.POINTERMOVE||i.type===Re.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,n,l))),i.type===Re.POINTERUP&&this._pointerCaptures[l.pointerId]&&(this._pointerCaptures[l.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(i=>{this.shouldRender&&i==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new Zr(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}Li._DefaultUtilityLayer=null;Li._DefaultKeepDepthUtilityLayer=null;var Cx;(function(a){a[a.Origin=0]="Origin",a[a.Pivot=1]="Pivot"})(Cx||(Cx={}));var vx;(function(a){a[a.World=0]="World",a[a.Local=1]="Local"})(vx||(vx={}));Object.defineProperty(Ee.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new Gl(this)),this._debugLayer},enumerable:!0,configurable:!0});var bx;(function(a){a[a.Properties=0]="Properties",a[a.Debug=1]="Debug",a[a.Statistics=2]="Statistics",a[a.Tools=3]="Tools",a[a.Settings=4]="Settings"})(bx||(bx={}));class Gl{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new G),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new G),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||Ae.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const i of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(i);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const i of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(i);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...Gl.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&(Object.prototype.toString.call(t)=="[object String]"?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){if(typeof INSPECTOR<"u")return INSPECTOR;if(typeof BABYLON<"u"&&typeof BABYLON.Inspector<"u")return BABYLON}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(typeof this.BJSINSPECTOR>"u"){const i=e&&e.inspectorURL?e.inspectorURL:Gl.InspectorURL;X.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}Gl.InspectorURL=`${X._DefaultCdnUrl}/v${H.Version}/inspector/babylon.inspector.bundle.js`;Gl.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function Xm(a){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=a.width||a.size||1,o=a.height||a.size||1,l=a.depth||a.size||1,h=a.wrap||!1;let c=a.topBaseAt===void 0?1:a.topBaseAt,u=a.bottomBaseAt===void 0?0:a.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let _=d[c],p=f[u],g=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(h){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],g=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let A=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],P=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const L=[17,18,19,16],w=[22,23,20,21];for(;_>0;)A.unshift(A.pop()),L.unshift(L.pop()),_--;for(;p>0;)P.unshift(P.pop()),w.unshift(w.pop()),p--;A=A.flat(),P=P.flat(),g=g.concat(A).concat(P),t.push(L[0],L[2],L[3],L[0],L[1],L[2]),t.push(w[0],w[2],w[3],w[0],w[1],w[2])}const x=[n/2,o/2,l/2];r=g.reduce((A,P,L)=>A.concat(P*x[L%3]),[]);const T=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,S=a.faceUV||new Array(6),C=a.faceColors,v=[];for(let A=0;A<6;A++)S[A]===void 0&&(S[A]=new we(0,0,1,1)),C&&C[A]===void 0&&(C[A]=new xe(1,1,1,1));for(let A=0;A<6;A++)if(s.push(S[A].z,mt.UseOpenGLOrientationForUV?1-S[A].w:S[A].w),s.push(S[A].x,mt.UseOpenGLOrientationForUV?1-S[A].w:S[A].w),s.push(S[A].x,mt.UseOpenGLOrientationForUV?1-S[A].y:S[A].y),s.push(S[A].z,mt.UseOpenGLOrientationForUV?1-S[A].y:S[A].y),C)for(let P=0;P<4;P++)v.push(C[A].r,C[A].g,C[A].b,C[A].a);le._ComputeSides(T,r,t,i,s,a.frontUVs,a.backUVs);const b=new le;if(b.indices=t,b.positions=r,b.normals=i,b.uvs=s,C){const A=T===le.DOUBLESIDE?v.concat(v):v;b.colors=A}return b}function jR(a){const e=a.width||a.size||1,t=a.height||a.size||1,i=a.depth||a.size||1,s=(a.widthSegments||a.segments||1)|0,r=(a.heightSegments||a.segments||1)|0,n=(a.depthSegments||a.segments||1)|0,o=new D,l=new D,h=new D,c=ia({width:e,height:i,subdivisionsX:s,subdivisionsY:n});D.TranslationToRef(0,-t/2,0,l),D.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),c.transform(h);const u=ia({width:e,height:i,subdivisionsX:s,subdivisionsY:n});D.TranslationToRef(0,t/2,0,h),u.transform(h);const d=ia({width:t,height:i,subdivisionsX:r,subdivisionsY:n});D.TranslationToRef(-e/2,0,0,l),D.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);const f=ia({width:t,height:i,subdivisionsX:r,subdivisionsY:n});D.TranslationToRef(e/2,0,0,l),D.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h);const _=ia({width:e,height:t,subdivisionsX:s,subdivisionsY:r});D.TranslationToRef(0,0,-i/2,l),D.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);const p=ia({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return D.TranslationToRef(0,0,i/2,l),D.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h),c.merge([u,f,d,_,p],!0),c}function Ym(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Xm(e).applyToMesh(i,e.updatable),i}le.CreateBox=Xm;z.CreateBox=(a,e,t=null,i,s)=>Ym(a,{size:e,sideOrientation:s,updatable:i},t);function $m(a){const e=(a.segments||32)|0,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,r=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,n=a.slice&&a.slice<=0?1:a.slice||1,o=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,l=!!a.dedupTopBottomIndices,h=new m(t/2,i/2,s/2),c=2+e,u=2*c,d=[],f=[],_=[],p=[];for(let x=0;x<=c;x++){const T=x/c,S=T*Math.PI*n;for(let C=0;C<=u;C++){const v=C/u,b=v*Math.PI*2*r,A=D.RotationZ(-S),P=D.RotationY(b),L=m.TransformCoordinates(m.Up(),A),w=m.TransformCoordinates(L,P),$=w.multiply(h),J=w.divide(h).normalize();f.push($.x,$.y,$.z),_.push(J.x,J.y,J.z),p.push(v,mt.UseOpenGLOrientationForUV?1-T:T)}if(x>0){const C=f.length/3;for(let v=C-2*(u+1);v+u+2<C;v++)l?(x>1&&(d.push(v),d.push(v+1),d.push(v+u+1)),(x<c||n<1)&&(d.push(v+u+1),d.push(v+1),d.push(v+u+2))):(d.push(v),d.push(v+1),d.push(v+u+1),d.push(v+u+1),d.push(v+1),d.push(v+u+2))}}le._ComputeSides(o,f,d,_,p,a.frontUVs,a.backUVs);const g=new le;return g.indices=d,g.positions=f,g.normals=_,g.uvs=p,g}function pa(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,$m(e).applyToMesh(i,e.updatable),i}le.CreateSphere=$m;z.CreateSphere=(a,e,t,i,s,r)=>pa(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function Km(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1)|0,t=Math.max(a.tessellation?a.tessellation:16,3)|0,i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),r=Math.max(a.capSubdivisions?a.capSubdivisions:6,1)|0,n=t,o=e,l=Math.max(a.radiusTop?a.radiusTop:s,0),h=Math.max(a.radiusBottom?a.radiusBottom:s,0),c=i-(l+h),u=0,d=2*Math.PI,f=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:r,1),_=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:r,1),p=Math.acos((h-l)/i);let g=[];const x=[],T=[],S=[];let C=0;const v=[],b=c*.5,A=Math.PI*.5;let P,L;const w=m.Zero(),$=m.Zero(),J=Math.cos(p),ne=Math.sin(p),oe=new Z(l*ne,b+l*J).subtract(new Z(h*ne,-b+h*J)).length(),re=l*p+oe+h*(A-p);let ce=0;for(L=0;L<=f;L++){const ie=[],F=A-p*(L/f);ce+=l*p/f;const j=Math.cos(F),se=Math.sin(F),Ie=j*l;for(P=0;P<=n;P++){const Ye=P/n,$e=Ye*d+u,fe=Math.sin($e),me=Math.cos($e);$.x=Ie*fe,$.y=b+se*l,$.z=Ie*me,x.push($.x,$.y,$.z),w.set(j*fe,se,j*me),T.push(w.x,w.y,w.z),S.push(Ye,mt.UseOpenGLOrientationForUV?ce/re:1-ce/re),ie.push(C),C++}v.push(ie)}const Se=i-l-h+J*l-J*h,Ce=ne*(h-l)/Se;for(L=1;L<=o;L++){const ie=[];ce+=oe/o;const F=ne*(L*(h-l)/o+l);for(P=0;P<=n;P++){const j=P/n,se=j*d+u,Ie=Math.sin(se),Ye=Math.cos(se);$.x=F*Ie,$.y=b+J*l-L*Se/o,$.z=F*Ye,x.push($.x,$.y,$.z),w.set(Ie,Ce,Ye).normalize(),T.push(w.x,w.y,w.z),S.push(j,mt.UseOpenGLOrientationForUV?ce/re:1-ce/re),ie.push(C),C++}v.push(ie)}for(L=1;L<=_;L++){const ie=[],F=A-p-(Math.PI-p)*(L/_);ce+=h*p/_;const j=Math.cos(F),se=Math.sin(F),Ie=j*h;for(P=0;P<=n;P++){const Ye=P/n,$e=Ye*d+u,fe=Math.sin($e),me=Math.cos($e);$.x=Ie*fe,$.y=-b+se*h,$.z=Ie*me,x.push($.x,$.y,$.z),w.set(j*fe,se,j*me),T.push(w.x,w.y,w.z),S.push(Ye,mt.UseOpenGLOrientationForUV?ce/re:1-ce/re),ie.push(C),C++}v.push(ie)}for(P=0;P<n;P++)for(L=0;L<f+o+_;L++){const ie=v[L][P],F=v[L+1][P],j=v[L+1][P+1],se=v[L][P+1];g.push(ie),g.push(F),g.push(se),g.push(F),g.push(j),g.push(se)}if(g=g.reverse(),a.orientation&&!a.orientation.equals(m.Up())){const ie=new D;a.orientation.clone().scale(Math.PI*.5).cross(m.Up()).toQuaternion().toRotationMatrix(ie);const F=m.Zero();for(let j=0;j<x.length;j+=3)F.set(x[j],x[j+1],x[j+2]),m.TransformCoordinatesToRef(F.clone(),ie,F),x[j]=F.x,x[j+1]=F.y,x[j+2]=F.z}const ae=new le;return ae.positions=x,ae.normals=T,ae.uvs=S,ae.indices=g,ae}function qR(a,e={orientation:m.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},t=null){const i=new z(a,t);return Km(e).applyToMesh(i,e.updatable),i}z.CreateCapsule=(a,e,t)=>qR(a,e,t);le.CreateCapsule=Km;function uS(a){let e=a.pathArray;const t=a.closeArray||!1,i=a.closePath||!1,s=a.invertUV||!1,r=Math.floor(e[0].length/2);let n=a.offset||r;n=n>r?r:Math.floor(n);const o=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,l=a.uvs,h=a.colors,c=[],u=[],d=[],f=[],_=[],p=[],g=[],x=[];let T;const S=[],C=[];let v,b,A;if(e.length<2){const ke=[],Ue=[];for(b=0;b<e[0].length-n;b++)ke.push(e[0][b]),Ue.push(e[0][b+n]);e=[ke,Ue]}let P=0;const L=i?1:0;let w,$;T=e[0].length;let J,ne;for(v=0;v<e.length;v++){for(g[v]=0,_[v]=[0],w=e[v],$=w.length,T=T<$?T:$,A=0;A<$;)c.push(w[A].x,w[A].y,w[A].z),A>0&&(J=w[A].subtract(w[A-1]).length(),ne=J+g[v],_[v].push(ne),g[v]=ne),A++;i&&(A--,c.push(w[0].x,w[0].y,w[0].z),J=w[A].subtract(w[0]).length(),ne=J+g[v],_[v].push(ne),g[v]=ne),S[v]=$+L,C[v]=P,P+=$+L}let oe,re,ce=null,Se=null;for(b=0;b<T+L;b++){for(x[b]=0,p[b]=[0],v=0;v<e.length-1;v++)oe=e[v],re=e[v+1],b===T?(ce=oe[0],Se=re[0]):(ce=oe[b],Se=re[b]),J=Se.subtract(ce).length(),ne=J+x[b],p[b].push(ne),x[b]=ne;t&&Se&&ce&&(oe=e[v],re=e[0],b===T&&(Se=re[0]),J=Se.subtract(ce).length(),ne=J+x[b],x[b]=ne)}let Ce,ae;if(l)for(v=0;v<l.length;v++)f.push(l[v].x,mt.UseOpenGLOrientationForUV?1-l[v].y:l[v].y);else for(v=0;v<e.length;v++)for(b=0;b<T+L;b++)Ce=g[v]!=0?_[v][b]/g[v]:0,ae=x[b]!=0?p[b][v]/x[b]:0,s?f.push(ae,Ce):f.push(Ce,mt.UseOpenGLOrientationForUV?1-ae:ae);v=0;let ie=0,F=S[v]-1,j=S[v+1]-1,se=F<j?F:j,Ie=C[1]-C[0];const Ye=t?S.length:S.length-1;for(;ie<=se&&v<Ye;)u.push(ie,ie+Ie,ie+1),u.push(ie+Ie+1,ie+1,ie+Ie),ie+=1,ie===se&&(v++,v===S.length-1?(Ie=C[0]-C[v],F=S[v]-1,j=S[0]-1):(Ie=C[v+1]-C[v],F=S[v]-1,j=S[v+1]-1),ie=C[v],se=F<j?F+ie:j+ie);if(le.ComputeNormals(c,u,d),i){let ke=0,Ue=0;for(v=0;v<e.length;v++)ke=C[v]*3,v+1<e.length?Ue=(C[v+1]-1)*3:Ue=d.length-3,d[ke]=(d[ke]+d[Ue])*.5,d[ke+1]=(d[ke+1]+d[Ue+1])*.5,d[ke+2]=(d[ke+2]+d[Ue+2])*.5,d[Ue]=d[ke],d[Ue+1]=d[ke+1],d[Ue+2]=d[ke+2]}le._ComputeSides(o,c,u,d,f,a.frontUVs,a.backUVs);let $e=null;if(h){$e=new Float32Array(h.length*4);for(let ke=0;ke<h.length;ke++)$e[ke*4]=h[ke].r,$e[ke*4+1]=h[ke].g,$e[ke*4+2]=h[ke].b,$e[ke*4+3]=h[ke].a}const fe=new le,me=new Float32Array(c),Xe=new Float32Array(d),Fe=new Float32Array(f);return fe.indices=u,fe.positions=me,fe.normals=Xe,fe.uvs=Fe,$e&&fe.set($e,y.ColorKind),i&&(fe._idx=C),fe}function zl(a,e,t=null){const i=e.pathArray,s=e.closeArray,r=e.closePath,n=z._GetDefaultSideOrientation(e.sideOrientation),o=e.instance,l=e.updatable;if(o){const h=U.Vector3[0].setAll(Number.MAX_VALUE),c=U.Vector3[1].setAll(-Number.MAX_VALUE),u=f=>{let _=i[0].length;const p=o;let g=0;const x=p._originalBuilderSideOrientation===z.DOUBLESIDE?2:1;for(let T=1;T<=x;++T)for(let S=0;S<i.length;++S){const C=i[S],v=C.length;_=_<v?_:v;for(let b=0;b<_;++b){const A=C[b];f[g]=A.x,f[g+1]=A.y,f[g+2]=A.z,h.minimizeInPlaceFromFloats(A.x,A.y,A.z),c.maximizeInPlaceFromFloats(A.x,A.y,A.z),g+=3}if(p._creationDataStorage&&p._creationDataStorage.closePath){const b=C[0];f[g]=b.x,f[g+1]=b.y,f[g+2]=b.z,g+=3}}},d=o.getVerticesData(y.PositionKind);if(u(d),o.hasBoundingInfo?o.getBoundingInfo().reConstruct(h,c,o._worldMatrix):o.buildBoundingInfo(h,c,o._worldMatrix),o.updateVerticesData(y.PositionKind,d,!1,!1),e.colors){const f=o.getVerticesData(y.ColorKind);for(let _=0,p=0;_<e.colors.length;_++,p+=4){const g=e.colors[_];f[p]=g.r,f[p+1]=g.g,f[p+2]=g.b,f[p+3]=g.a}o.updateVerticesData(y.ColorKind,f,!1,!1)}if(e.uvs){const f=o.getVerticesData(y.UVKind);for(let _=0;_<e.uvs.length;_++)f[_*2]=e.uvs[_].x,f[_*2+1]=mt.UseOpenGLOrientationForUV?1-e.uvs[_].y:e.uvs[_].y;o.updateVerticesData(y.UVKind,f,!1,!1)}if(!o.areNormalsFrozen||o.isFacetDataEnabled){const f=o.getIndices(),_=o.getVerticesData(y.NormalKind),p=o.isFacetDataEnabled?o.getFacetDataParameters():null;if(le.ComputeNormals(d,f,_,p),o._creationDataStorage&&o._creationDataStorage.closePath){let g=0,x=0;for(let T=0;T<i.length;T++)g=o._creationDataStorage.idx[T]*3,T+1<i.length?x=(o._creationDataStorage.idx[T+1]-1)*3:x=_.length-3,_[g]=(_[g]+_[x])*.5,_[g+1]=(_[g+1]+_[x+1])*.5,_[g+2]=(_[g+2]+_[x+2])*.5,_[x]=_[g],_[x+1]=_[g+1],_[x+2]=_[g+2]}o.areNormalsFrozen||o.updateVerticesData(y.NormalKind,_,!1,!1)}return o}else{const h=new z(a,t);h._originalBuilderSideOrientation=n,h._creationDataStorage=new zE;const c=uS(e);return r&&(h._creationDataStorage.idx=c._idx),h._creationDataStorage.closePath=r,h._creationDataStorage.closeArray=s,c.applyToMesh(h,l),h}}le.CreateRibbon=uS;z.CreateRibbon=(a,e,t=!1,i,s,r,n=!1,o,l)=>zl(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:o,instance:l},r);function jm(a){const e=[],t=[],i=[],s=[],r=a.radius||.5,n=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,l=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*o,c=o===1?h/n:h/(n-1);let u=0;for(let _=0;_<n;_++){const p=Math.cos(u),g=Math.sin(u),x=(p+1)/2,T=(1-g)/2;e.push(r*p,r*g,0),s.push(x,mt.UseOpenGLOrientationForUV?1-T:T),u+=c}o===1&&(e.push(e[3],e[4],e[5]),s.push(s[2],mt.UseOpenGLOrientationForUV?1-s[3]:s[3]));const d=e.length/3;for(let _=1;_<d-1;_++)t.push(_+1,0,_);le.ComputeNormals(e,t,i),le._ComputeSides(l,e,t,i,s,a.frontUVs,a.backUVs);const f=new le;return f.indices=t,f.positions=e,f.normals=i,f.uvs=s,f}function dS(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,jm(e).applyToMesh(i,e.updatable),i}le.CreateDisc=jm;z.CreateDisc=(a,e,t,i=null,s,r)=>dS(a,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);function Wd(a){const e=a.pattern||z.NO_FLIP,t=a.tileWidth||a.tileSize||1,i=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,r=a.alignVertical||0,n=a.width||a.size||1,o=Math.floor(n/t);let l=n-o*t;const h=a.height||a.size||1,c=Math.floor(h/i);let u=h-c*i;const d=t*o/2,f=i*c/2;let _=0,p=0,g=0,x=0,T=0,S=0;if(l>0||u>0){switch(g=-d,x=-f,T=d,S=f,s){case z.CENTER:l/=2,g-=l,T+=l;break;case z.LEFT:T+=l,_=-l/2;break;case z.RIGHT:g-=l,_=l/2;break}switch(r){case z.CENTER:u/=2,x-=u,S+=u;break;case z.BOTTOM:S+=u,p=-u/2;break;case z.TOP:x-=u,p=u/2;break}}const C=[],v=[],b=[];b[0]=[0,0,1,0,1,1,0,1],b[1]=[0,0,1,0,1,1,0,1],(e===z.ROTATE_TILE||e===z.ROTATE_ROW)&&(b[1]=[1,1,0,1,0,0,1,0]),(e===z.FLIP_TILE||e===z.FLIP_ROW)&&(b[1]=[1,0,0,0,0,1,1,1]),(e===z.FLIP_N_ROTATE_TILE||e===z.FLIP_N_ROTATE_ROW)&&(b[1]=[0,1,1,1,1,0,0,0]);let A=[];const P=[],L=[];let w=0;for(let oe=0;oe<c;oe++)for(let re=0;re<o;re++)C.push(-d+re*t+_,-f+oe*i+p,0),C.push(-d+(re+1)*t+_,-f+oe*i+p,0),C.push(-d+(re+1)*t+_,-f+(oe+1)*i+p,0),C.push(-d+re*t+_,-f+(oe+1)*i+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),e===z.FLIP_TILE||e===z.ROTATE_TILE||e===z.FLIP_N_ROTATE_TILE?A=A.concat(b[(re%2+oe%2)%2]):e===z.FLIP_ROW||e===z.ROTATE_ROW||e===z.FLIP_N_ROTATE_ROW?A=A.concat(b[oe%2]):A=A.concat(b[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),w+=4;if(l>0||u>0){const oe=u>0&&(r===z.CENTER||r===z.TOP),re=u>0&&(r===z.CENTER||r===z.BOTTOM),ce=l>0&&(s===z.CENTER||s===z.RIGHT),Se=l>0&&(s===z.CENTER||s===z.LEFT);let Ce=[],ae,ie,F,j;if(oe&&ce&&(C.push(g+_,x+p,0),C.push(-d+_,x+p,0),C.push(-d+_,x+u+p,0),C.push(g+_,x+u+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,ae=1-l/t,ie=1-u/i,F=1,j=1,Ce=[ae,ie,F,ie,F,j,ae,j],e===z.ROTATE_ROW&&(Ce=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),e===z.FLIP_ROW&&(Ce=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),e===z.FLIP_N_ROTATE_ROW&&(Ce=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]),A=A.concat(Ce),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe&&Se&&(C.push(d+_,x+p,0),C.push(T+_,x+p,0),C.push(T+_,x+u+p,0),C.push(d+_,x+u+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,ae=0,ie=1-u/i,F=l/t,j=1,Ce=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_ROW||e===z.ROTATE_TILE&&o%2===0)&&(Ce=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_ROW||e===z.FLIP_TILE&&o%2===0)&&(Ce=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_ROW||e===z.FLIP_N_ROTATE_TILE&&o%2===0)&&(Ce=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]),A=A.concat(Ce),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),re&&ce&&(C.push(g+_,f+p,0),C.push(-d+_,f+p,0),C.push(-d+_,S+p,0),C.push(g+_,S+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,ae=1-l/t,ie=0,F=1,j=u/i,Ce=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_ROW&&c%2===1||e===z.ROTATE_TILE&&c%1===0)&&(Ce=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_ROW&&c%2===1||e===z.FLIP_TILE&&c%2===0)&&(Ce=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_ROW&&c%2===1||e===z.FLIP_N_ROTATE_TILE&&c%2===0)&&(Ce=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]),A=A.concat(Ce),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),re&&Se&&(C.push(d+_,f+p,0),C.push(T+_,f+p,0),C.push(T+_,S+p,0),C.push(d+_,S+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,ae=0,ie=0,F=l/t,j=u/i,Ce=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_ROW&&c%2===1||e===z.ROTATE_TILE&&(c+o)%2===1)&&(Ce=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_ROW&&c%2===1||e===z.FLIP_TILE&&(c+o)%2===1)&&(Ce=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_ROW&&c%2===1||e===z.FLIP_N_ROTATE_TILE&&(c+o)%2===1)&&(Ce=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]),A=A.concat(Ce),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe){const se=[];ae=0,ie=1-u/i,F=1,j=1,se[0]=[ae,ie,F,ie,F,j,ae,j],se[1]=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_TILE||e===z.ROTATE_ROW)&&(se[1]=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_TILE||e===z.FLIP_ROW)&&(se[1]=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_TILE||e===z.FLIP_N_ROTATE_ROW)&&(se[1]=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]);for(let Ie=0;Ie<o;Ie++)C.push(-d+Ie*t+_,x+p,0),C.push(-d+(Ie+1)*t+_,x+p,0),C.push(-d+(Ie+1)*t+_,x+u+p,0),C.push(-d+Ie*t+_,x+u+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,e===z.FLIP_TILE||e===z.ROTATE_TILE||e===z.FLIP_N_ROTATE_TILE?A=A.concat(se[(Ie+1)%2]):e===z.FLIP_ROW||e===z.ROTATE_ROW||e===z.FLIP_N_ROTATE_ROW?A=A.concat(se[1]):A=A.concat(se[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(re){const se=[];ae=0,ie=0,F=1,j=u/i,se[0]=[ae,ie,F,ie,F,j,ae,j],se[1]=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_TILE||e===z.ROTATE_ROW)&&(se[1]=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_TILE||e===z.FLIP_ROW)&&(se[1]=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_TILE||e===z.FLIP_N_ROTATE_ROW)&&(se[1]=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]);for(let Ie=0;Ie<o;Ie++)C.push(-d+Ie*t+_,S-u+p,0),C.push(-d+(Ie+1)*t+_,S-u+p,0),C.push(-d+(Ie+1)*t+_,S+p,0),C.push(-d+Ie*t+_,S+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,e===z.FLIP_TILE||e===z.ROTATE_TILE||e===z.FLIP_N_ROTATE_TILE?A=A.concat(se[(Ie+c)%2]):e===z.FLIP_ROW||e===z.ROTATE_ROW||e===z.FLIP_N_ROTATE_ROW?A=A.concat(se[c%2]):A=A.concat(se[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(ce){const se=[];ae=1-l/t,ie=0,F=1,j=1,se[0]=[ae,ie,F,ie,F,j,ae,j],se[1]=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_TILE||e===z.ROTATE_ROW)&&(se[1]=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_TILE||e===z.FLIP_ROW)&&(se[1]=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_TILE||e===z.FLIP_N_ROTATE_ROW)&&(se[1]=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]);for(let Ie=0;Ie<c;Ie++)C.push(g+_,-f+Ie*i+p,0),C.push(g+l+_,-f+Ie*i+p,0),C.push(g+l+_,-f+(Ie+1)*i+p,0),C.push(g+_,-f+(Ie+1)*i+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,e===z.FLIP_TILE||e===z.ROTATE_TILE||e===z.FLIP_N_ROTATE_TILE?A=A.concat(se[(Ie+1)%2]):e===z.FLIP_ROW||e===z.ROTATE_ROW||e===z.FLIP_N_ROTATE_ROW?A=A.concat(se[Ie%2]):A=A.concat(se[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(Se){const se=[];ae=0,ie=0,F=l/i,j=1,se[0]=[ae,ie,F,ie,F,j,ae,j],se[1]=[ae,ie,F,ie,F,j,ae,j],(e===z.ROTATE_TILE||e===z.ROTATE_ROW)&&(se[1]=[1-ae,1-ie,1-F,1-ie,1-F,1-j,1-ae,1-j]),(e===z.FLIP_TILE||e===z.FLIP_ROW)&&(se[1]=[1-ae,ie,1-F,ie,1-F,j,1-ae,j]),(e===z.FLIP_N_ROTATE_TILE||e===z.FLIP_N_ROTATE_ROW)&&(se[1]=[ae,1-ie,F,1-ie,F,1-j,ae,1-j]);for(let Ie=0;Ie<c;Ie++)C.push(T-l+_,-f+Ie*i+p,0),C.push(T+_,-f+Ie*i+p,0),C.push(T+_,-f+(Ie+1)*i+p,0),C.push(T-l+_,-f+(Ie+1)*i+p,0),L.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,e===z.FLIP_TILE||e===z.ROTATE_TILE||e===z.FLIP_N_ROTATE_TILE?A=A.concat(se[(Ie+o)%2]):e===z.FLIP_ROW||e===z.ROTATE_ROW||e===z.FLIP_N_ROTATE_ROW?A=A.concat(se[Ie%2]):A=A.concat(se[0]),P.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),v.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}const $=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE;le._ComputeSides($,C,L,v,A,a.frontUVs,a.backUVs);const J=new le;J.indices=L,J.positions=C,J.normals=v,J.uvs=A;const ne=$===le.DOUBLESIDE?P.concat(P):P;return J.colors=ne,J}le.CreateTiledPlane=Wd;function QR(a){const t=a.faceUV||new Array(6),i=a.faceColors,s=a.pattern||z.NO_FLIP,r=a.width||a.size||1,n=a.height||a.size||1,o=a.depth||a.size||1,l=a.tileWidth||a.tileSize||1,h=a.tileHeight||a.tileSize||1,c=a.alignHorizontal||0,u=a.alignVertical||0,d=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE;for(let F=0;F<6;F++)t[F]===void 0&&(t[F]=new we(0,0,1,1)),i&&i[F]===void 0&&(i[F]=new xe(1,1,1,1));const f=r/2,_=n/2,p=o/2,g=[];for(let F=0;F<2;F++)g[F]=Wd({pattern:s,tileWidth:l,tileHeight:h,width:r,height:n,alignVertical:u,alignHorizontal:c,sideOrientation:d});for(let F=2;F<4;F++)g[F]=Wd({pattern:s,tileWidth:l,tileHeight:h,width:o,height:n,alignVertical:u,alignHorizontal:c,sideOrientation:d});let x=u;u===z.BOTTOM?x=z.TOP:u===z.TOP&&(x=z.BOTTOM);for(let F=4;F<6;F++)g[F]=Wd({pattern:s,tileWidth:l,tileHeight:h,width:r,height:o,alignVertical:x,alignHorizontal:c,sideOrientation:d});let T=[],S=[],C=[],v=[];const b=[],A=[],P=[],L=[];let w=0,$=0;for(let F=0;F<6;F++){const j=g[F].positions.length;A[F]=[],P[F]=[];for(let se=0;se<j/3;se++)A[F].push(new m(g[F].positions[3*se],g[F].positions[3*se+1],g[F].positions[3*se+2])),P[F].push(new m(g[F].normals[3*se],g[F].normals[3*se+1],g[F].normals[3*se+2]));w=g[F].uvs.length,L[F]=[];for(let se=0;se<w;se+=2)L[F][se]=t[F].x+(t[F].z-t[F].x)*g[F].uvs[se],L[F][se+1]=t[F].y+(t[F].w-t[F].y)*g[F].uvs[se+1],mt.UseOpenGLOrientationForUV&&(L[F][se+1]=1-L[F][se+1]);if(C=C.concat(L[F]),v=v.concat(g[F].indices.map(se=>se+$)),$+=A[F].length,i)for(let se=0;se<4;se++)b.push(i[F].r,i[F].g,i[F].b,i[F].a)}const J=new m(0,0,p),ne=D.RotationY(Math.PI);T=A[0].map(F=>m.TransformNormal(F,ne).add(J)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]),S=P[0].map(F=>m.TransformNormal(F,ne)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]),T=T.concat(A[1].map(F=>F.subtract(J)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),S=S.concat(P[1].map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]));const oe=new m(f,0,0),re=D.RotationY(-Math.PI/2);T=T.concat(A[2].map(F=>m.TransformNormal(F,re).add(oe)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),S=S.concat(P[2].map(F=>m.TransformNormal(F,re)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]));const ce=D.RotationY(Math.PI/2);T=T.concat(A[3].map(F=>m.TransformNormal(F,ce).subtract(oe)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),S=S.concat(P[3].map(F=>m.TransformNormal(F,ce)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]));const Se=new m(0,_,0),Ce=D.RotationX(Math.PI/2);T=T.concat(A[4].map(F=>m.TransformNormal(F,Ce).add(Se)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),S=S.concat(P[4].map(F=>m.TransformNormal(F,Ce)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[]));const ae=D.RotationX(-Math.PI/2);T=T.concat(A[5].map(F=>m.TransformNormal(F,ae).subtract(Se)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),S=S.concat(P[5].map(F=>m.TransformNormal(F,ae)).map(F=>[F.x,F.y,F.z]).reduce((F,j)=>F.concat(j),[])),le._ComputeSides(d,T,v,S,C);const ie=new le;if(ie.indices=v,ie.positions=T,ie.normals=S,ie.uvs=C,i){const F=d===le.DOUBLESIDE?b.concat(b):b;ie.colors=F}return ie}le.CreateTiledBox=QR;function fS(a){const e=[],t=[],i=[],s=[],r=a.radius||2,n=a.tube||.5,o=a.radialSegments||32,l=a.tubularSegments||32,h=a.p||2,c=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,d=g=>{const x=Math.cos(g),T=Math.sin(g),S=c/h*g,C=Math.cos(S),v=r*(2+C)*.5*x,b=r*(2+C)*T*.5,A=r*Math.sin(S)*.5;return new m(v,b,A)};let f,_;for(f=0;f<=o;f++){const x=f%o/o*2*h*Math.PI,T=d(x),S=d(x+.01),C=S.subtract(T);let v=S.add(T);const b=m.Cross(C,v);for(v=m.Cross(b,C),b.normalize(),v.normalize(),_=0;_<l;_++){const P=_%l/l*2*Math.PI,L=-n*Math.cos(P),w=n*Math.sin(P);t.push(T.x+L*v.x+w*b.x),t.push(T.y+L*v.y+w*b.y),t.push(T.z+L*v.z+w*b.z),s.push(f/o),s.push(mt.UseOpenGLOrientationForUV?1-_/l:_/l)}}for(f=0;f<o;f++)for(_=0;_<l;_++){const g=(_+1)%l,x=f*l+_,T=(f+1)*l+_,S=(f+1)*l+g,C=f*l+g;e.push(C),e.push(T),e.push(x),e.push(C),e.push(S),e.push(T)}le.ComputeNormals(t,e,i),le._ComputeSides(u,t,e,i,s,a.frontUVs,a.backUVs);const p=new le;return p.indices=e,p.positions=t,p.normals=i,p.uvs=s,p}function ZR(a,e={},t){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,fS(e).applyToMesh(i,e.updatable),i}le.CreateTorusKnot=fS;z.CreateTorusKnot=(a,e,t,i,s,r,n,o,l,h)=>ZR(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:h,updatable:l},o);const N_={effect:null,subMesh:null};class Qs extends vc{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 D,this._cachedWorldViewProjectionMatrix=new D,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={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){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const v=s?i._drawWrapper:this._drawWrapper;if(v.effect&&v._wasPreviouslyReady&&v._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],l=[],h=new zo;let c=this._shaderPath,u=this._options.uniforms,d=this._options.uniformBuffers,f=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let v=0;v<this._options.defines.length;v++){const b=this._options.defines[v].indexOf("#define")===0?this._options.defines[v]:`#define ${this._options.defines[v]}`;o.push(b)}for(let v=0;v<this._options.attributes.length;v++)l.push(this._options.attributes[v]);if(e&&e.isVerticesDataPresent(y.ColorKind)&&(l.indexOf(y.ColorKind)===-1&&l.push(y.ColorKind),o.push("#define VERTEXCOLOR")),t&&(o.push("#define INSTANCES"),oo(l,this._materialHelperNeedsPreviousMatrices),e!=null&&e.hasThinInstances&&(o.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(y.ColorInstanceKind)&&(l.push(y.ColorInstanceKind),o.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){l.push(y.MatricesIndicesKind),l.push(y.MatricesWeightsKind),e.numBoneInfluencers>4&&(l.push(y.MatricesIndicesExtraKind),l.push(y.MatricesWeightsExtraKind));const v=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h.addCPUSkinningFallback(0,e),v.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(v.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const v=p.supportsUVs&&o.indexOf("#define UV1")!==-1,b=p.supportsTangents&&o.indexOf("#define TANGENT")!==-1,A=p.supportsNormals&&o.indexOf("#define NORMAL")!==-1;_=p.numMaxInfluencers||p.numInfluencers,v&&o.push("#define MORPHTARGETS_UV"),b&&o.push("#define MORPHTARGETS_TANGENT"),A&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let P=0;P<_;P++)l.push(y.PositionKind+P),A&&l.push(y.NormalKind+P),b&&l.push(y.TangentKind+P),v&&l.push(y.UVKind+"_"+P);_>0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const v=e.bakedVertexAnimationManager;v&&v.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Tm(l,e,o)}for(const v in this._textures)if(!this._textures[v].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(sn(u),no(this,r,o)),r.fogEnabled&&(e!=null&&e.applyFog)&&r.fogMode!==Ee.FOGMODE_NONE&&(o.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(u=u.slice(),d=d.slice(),f=f.slice(),c=this.customShaderNameResolve(c,u,d,f,o,l));const g=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,x=(g==null?void 0:g.effect)??null,T=(g==null?void 0:g.defines)??null,S=o.join(`
`);let C=x;return T!==S&&(C=n.createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:f,defines:S,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(C,S,this._materialContext):g&&g.setEffect(C,S),this._onEffectCreatedObservable&&(N_.effect=C,N_.subMesh=i??(e==null?void 0:e.subMeshes[0])??null,this._onEffectCreatedObservable.notifyObservers(N_))),g._wasPreviouslyUsingInstances=!!t,C!=null&&C.isReady()?(x!==C&&r.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0):!1}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)),this._options.uniforms.indexOf("view")!==-1&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)==null?void 0:s.effect,i)}bind(e,t,i,s){var u;const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let h=!1;if(n&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;d<l.length;++d)switch(l[d]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e));break;case"Scene":bf(n,o.getSceneUniformBuffer()),o.finalizeSceneUbo(),h=!0;break}const c=t&&r?this._mustRebind(o,n,s,t.visibility):o.getCachedMaterial()!==this;if(n&&c){!h&&this._options.uniforms.indexOf("view")!==-1&&n.setMatrix("view",o.getViewMatrix()),!h&&this._options.uniforms.indexOf("projection")!==-1&&n.setMatrix("projection",o.getProjectionMatrix()),!h&&this._options.uniforms.indexOf("viewProjection")!==-1&&(n.setMatrix("viewProjection",o.getTransformMatrix()),this._multiview&&n.setMatrix("viewProjectionR",o._transformMatrixR)),o.activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&n.setVector3("cameraPosition",o.activeCamera.globalPosition),Ku(t,n),Gr(n,this,o),this._useLogarithmicDepth&&ao(r?s.materialDefines:n.defines,n,o),t&&Go(o,t,n);let d;for(d in this._textures)n.setTexture(d,this._textures[d]);for(d in this._textureArrays)n.setTextureArray(d,this._textureArrays[d]);for(d in this._externalTextures)n.setExternalTexture(d,this._externalTextures[d]);for(d in this._ints)n.setInt(d,this._ints[d]);for(d in this._uints)n.setUInt(d,this._uints[d]);for(d in this._floats)n.setFloat(d,this._floats[d]);for(d in this._floatsArrays)n.setArray(d,this._floatsArrays[d]);for(d in this._colors3)n.setColor3(d,this._colors3[d]);for(d in this._colors3Arrays)n.setArray3(d,this._colors3Arrays[d]);for(d in this._colors4){const f=this._colors4[d];n.setFloat4(d,f.r,f.g,f.b,f.a)}for(d in this._colors4Arrays)n.setArray4(d,this._colors4Arrays[d]);for(d in this._vectors2)n.setVector2(d,this._vectors2[d]);for(d in this._vectors3)n.setVector3(d,this._vectors3[d]);for(d in this._vectors4)n.setVector4(d,this._vectors4[d]);for(d in this._quaternions)n.setQuaternion(d,this._quaternions[d]);for(d in this._matrices)n.setMatrix(d,this._matrices[d]);for(d in this._matrixArrays)n.setMatrices(d,this._matrixArrays[d]);for(d in this._matrices3x3)n.setMatrix3x3(d,this._matrices3x3[d]);for(d in this._matrices2x2)n.setMatrix2x2(d,this._matrices2x2[d]);for(d in this._vectors2Arrays)n.setArray2(d,this._vectors2Arrays[d]);for(d in this._vectors3Arrays)n.setArray3(d,this._vectors3Arrays[d]);for(d in this._vectors4Arrays)n.setArray4(d,this._vectors4Arrays[d]);for(d in this._quaternionsArrays)n.setArray4(d,this._quaternionsArrays[d]);for(d in this._uniformBuffers){const f=this._uniformBuffers[d].getBuffer();f&&n.bindUniformBuffer(f,d)}for(d in this._textureSamplers)n.setTextureSampler(d,this._textureSamplers[d]);for(d in this._storageBuffers)n.setStorageBuffer(d,this._storageBuffers[d])}if(n&&t&&(c||!this.isFrozen)){const d=t.morphTargetManager;d&&d.numInfluencers>0&&Sa(t,n);const f=t.bakedVertexAnimationManager;if(f&&f.isEnabled){const _=r?s._drawWrapper:this._drawWrapper;(u=t.bakedVertexAnimationManager)==null||u.bind(n,!!_._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;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=_e.Clone(()=>new Qs(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach(i=>{const s=this._options[i];Array.isArray(s)&&(this._options[i]=s.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const 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=_e.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.floatsArrays={};for(t in this._floatsArrays)e.floatsArrays[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=_e.Parse(()=>new Qs(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,k.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let l=0;l<n.length;l++)o.push(k.Parse(n[l],t,i));s.setTextureArray(r,o)}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,q.FromArray(e.colors3[r]));for(r in e.colors3Arrays){const n=e.colors3Arrays[r].reduce((o,l,h)=>(h%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>q.FromArray(o));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,xe.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((o,l,h)=>(h%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>xe.FromArray(o));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,Z.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,m.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,we.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,Q.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,D.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 o=new yi;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=this.Parse(l,i||Ae.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new yi;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),h=this.Parse(l,t||Ae.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()})}}Qs.SnippetUrl="https://snippet.babylonjs.com";Qs.CreateFromSnippetAsync=Qs.ParseFromSnippetAsync;V("BABYLON.ShaderMaterial",Qs);const JR="colorPixelShader",eI=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
#define VERTEXCOLOR
varying vec4 vColor;
#else
uniform vec4 color;
#endif
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
gl_FragColor=vColor;
#else
gl_FragColor=color;
#endif
#include<fogFragment>(color,gl_FragColor)
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[JR]=eI;const tI="colorVertexShader",iI=`attribute vec3 position;
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#ifdef FOG
uniform mat4 view;
#endif
#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<vertexColorMixing>
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[tI]=iI;z._LinesMeshParser=(a,e)=>to.Parse(a,e);class to extends z{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,r,n,o,l){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new q(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const h=[],c={attributes:[y.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};o===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),n?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(y.ColorKind)):(c.uniforms.push("color"),this._color4=new xe),l?this.material=l:(this.material=new Qs("colorShader",this.getScene(),"color",c,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=ee.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:s,g:r,b:n}=this.color;this._color4.set(s,r,n,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(ee.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(ee.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new to(e,this.getScene(),t,this,i)}createInstance(e){const t=new _S(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new to(e.name,t);return i.color=q.FromArray(e.color),i.alpha=e.alpha,i}}class _S extends ym{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function pS(a){const e=[],t=[],i=a.lines,s=a.colors,r=[];let n=0;for(let l=0;l<i.length;l++){const h=i[l];for(let c=0;c<h.length;c++){const{x:u,y:d,z:f}=h[c];if(t.push(u,d,f),s){const _=s[l],{r:p,g,b:x,a:T}=_[c];r.push(p,g,x,T)}c>0&&(e.push(n-1),e.push(n)),n++}}const o=new le;return o.indices=e,o.positions=t,s&&(o.colors=r),o}function mS(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,r=[],n=[],o=m.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,_=0;for(_=0;_<s.length-1;_++)s[_+1].subtractToRef(s[_],o),l+=o.length();for(c=l/i,u=e*c/(e+t),_=0;_<s.length-1;_++){s[_+1].subtractToRef(s[_],o),h=Math.floor(o.length()/c),o.normalize();for(let g=0;g<h;g++)d=c*g,r.push(s[_].x+d*o.x,s[_].y+d*o.y,s[_].z+d*o.z),r.push(s[_].x+(d+u)*o.x,s[_].y+(d+u)*o.y,s[_].z+(d+u)*o.z),n.push(f,f+1),f+=2}const p=new le;return p.positions=r,p.indices=n,p}function sI(a,e,t=null){const i=e.instance,s=e.lines,r=e.colors;if(i){const h=i.getVerticesData(y.PositionKind);let c,u;r&&(c=i.getVerticesData(y.ColorKind));let d=0,f=0;for(let _=0;_<s.length;_++){const p=s[_];for(let g=0;g<p.length;g++)h[d]=p[g].x,h[d+1]=p[g].y,h[d+2]=p[g].z,r&&c&&(u=r[_],c[f]=u[g].r,c[f+1]=u[g].g,c[f+2]=u[g].b,c[f+3]=u[g].a,f+=4),d+=3}return i.updateVerticesData(y.PositionKind,h,!1,!1),r&&c&&i.updateVerticesData(y.ColorKind,c,!1,!1),i}const n=!!r,o=new to(a,t,null,void 0,void 0,n,e.useVertexAlpha,e.material);return pS(e).applyToMesh(o,e.updatable),o}function qm(a,e,t=null){const i=e.colors?[e.colors]:null;return sI(a,{lines:[e.points],updatable:e.updatable,instance:e.instance,colors:i,useVertexAlpha:e.useVertexAlpha,material:e.material},t)}function rI(a,e,t=null){const i=e.points,s=e.instance,r=e.gapSize||1,n=e.dashSize||3;if(s){const h=c=>{const u=m.Zero(),d=c.length/6;let f=0,_=0,p=0,g=0,x=0,T=0,S=0,C=0;for(S=0;S<i.length-1;S++)i[S+1].subtractToRef(i[S],u),f+=u.length();p=f/d;const v=s._creationDataStorage.dashSize,b=s._creationDataStorage.gapSize;for(g=v*p/(v+b),S=0;S<i.length-1;S++)for(i[S+1].subtractToRef(i[S],u),_=Math.floor(u.length()/p),u.normalize(),C=0;C<_&&T<c.length;)x=p*C,c[T]=i[S].x+x*u.x,c[T+1]=i[S].y+x*u.y,c[T+2]=i[S].z+x*u.z,c[T+3]=i[S].x+(x+g)*u.x,c[T+4]=i[S].y+(x+g)*u.y,c[T+5]=i[S].z+(x+g)*u.z,T+=6,C++;for(;T<c.length;)c[T]=i[S].x,c[T+1]=i[S].y,c[T+2]=i[S].z,T+=3};return(e.dashNb||e.dashSize||e.gapSize||e.useVertexAlpha||e.material)&&O.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(h,!1),s}const o=new to(a,t,null,void 0,void 0,void 0,e.useVertexAlpha,e.material);return mS(e).applyToMesh(o,e.updatable),o._creationDataStorage=new zE,o._creationDataStorage.dashSize=n,o._creationDataStorage.gapSize=r,o}le.CreateLineSystem=pS;le.CreateDashedLines=mS;z.CreateLines=(a,e,t=null,i=!1,s=null)=>qm(a,{points:e,updatable:i,instance:s},t);z.CreateDashedLines=(a,e,t,i,s,r=null,n,o)=>rI(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:o},r);class nI extends Z{constructor(e,t){super(e.x,e.y),this.index=t}}class F_{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new nI(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new Z(this.elements[0].x,this.elements[0].y),t=new Z(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class aI{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new F_,this._outlinepoints=new F_,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||Ae.LastCreatedScene;let r;t instanceof Cf?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&O.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new F_;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new z(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(y.PositionKind,r.positions,e),s.setVerticesData(y.NormalKind,r.normals,e),s.setVerticesData(y.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new le,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),r.push(c.x,0,c.y),n.push((c.x-o.min.x)/o.width,(c.y-o.min.y)/o.height)});const l=[],h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c<h.length;c++)l.push(h[c]);if(e>0){const c=r.length/3;this._points.elements.forEach(d=>{s.push(0,-1,0),r.push(d.x,-e,d.y),n.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height)});const u=l.length;for(let d=0;d<u;d+=3){const f=l[d+0],_=l[d+1],p=l[d+2];l.push(p+c),l.push(_+c),l.push(f+c)}this._addSide(r,s,n,l,o,this._outlinepoints,e,!1,t),this._holes.forEach(d=>{this._addSide(r,s,n,l,o,d,e,!0,t)})}return i.indices=l,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,l,h){let c=e.length/3,u=0;for(let d=0;d<n.elements.length;d++){const f=n.elements[d],_=n.elements[(d+1)%n.elements.length];e.push(f.x,0,f.y),e.push(f.x,-o,f.y),e.push(_.x,0,_.y),e.push(_.x,-o,_.y);const p=n.elements[(d+n.elements.length-1)%n.elements.length],g=n.elements[(d+2)%n.elements.length];let x=new m(-(_.y-f.y),0,_.x-f.x),T=new m(-(f.y-p.y),0,f.x-p.x),S=new m(-(g.y-_.y),0,g.x-_.x);l||(x=x.scale(-1),T=T.scale(-1),S=S.scale(-1));const C=x.normalizeToNew();let v=T.normalizeToNew(),b=S.normalizeToNew();const A=m.Dot(v,C);A>h?A<rt-1?v=new m(f.x,0,f.y).subtract(new m(_.x,0,_.y)).normalize():v=T.add(x).normalize():v=C;const P=m.Dot(S,x);P>h?P<rt-1?b=new m(_.x,0,_.y).subtract(new m(f.x,0,f.y)).normalize():b=S.add(x).normalize():b=C,i.push(u/r.width,0),i.push(u/r.width,1),u+=x.length(),i.push(u/r.width,0),i.push(u/r.width,1),t.push(v.x,v.y,v.z),t.push(v.x,v.y,v.z),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),l?(s.push(c),s.push(c+2),s.push(c+1),s.push(c+1),s.push(c+2),s.push(c+3)):(s.push(c),s.push(c+1),s.push(c+2),s.push(c+1),s.push(c+3),s.push(c+2)),c+=4}}}function gS(a,e,t,i,s,r,n){const o=t||new Array(3),l=i,h=[],c=n||!1;for(let L=0;L<3;L++)o[L]===void 0&&(o[L]=new we(0,0,1,1)),l&&l[L]===void 0&&(l[L]=new xe(1,1,1,1));const u=a.getVerticesData(y.PositionKind),d=a.getVerticesData(y.NormalKind),f=a.getVerticesData(y.UVKind),_=a.getIndices(),p=u.length/9;let g=0,x=0,T=0,S=0,C=0;const v=[0];if(c)for(let L=p;L<u.length/3;L+=4)x=u[3*(L+2)]-u[3*L],T=u[3*(L+2)+2]-u[3*L+2],S=Math.sqrt(x*x+T*T),C+=S,v.push(C);let b=0,A=0;for(let L=0;L<d.length;L+=3)Math.abs(d[L+1])<.001&&(A=1),Math.abs(d[L+1]-1)<.001&&(A=0),Math.abs(d[L+1]+1)<.001&&(A=2),b=L/3,A===1?(g=b-p,g%4<1.5?c?f[2*b]=o[A].x+(o[A].z-o[A].x)*v[Math.floor(g/4)]/C:f[2*b]=o[A].x:c?f[2*b]=o[A].x+(o[A].z-o[A].x)*v[Math.floor(g/4)+1]/C:f[2*b]=o[A].z,g%2===0?f[2*b+1]=mt.UseOpenGLOrientationForUV?1-o[A].w:o[A].w:f[2*b+1]=mt.UseOpenGLOrientationForUV?1-o[A].y:o[A].y):(f[2*b]=(1-f[2*b])*o[A].x+f[2*b]*o[A].z,f[2*b+1]=(1-f[2*b+1])*o[A].y+f[2*b+1]*o[A].w,mt.UseOpenGLOrientationForUV&&(f[2*b+1]=1-f[2*b+1])),l&&h.push(l[A].r,l[A].g,l[A].b,l[A].a);le._ComputeSides(e,u,_,d,f,s,r);const P=new le;if(P.indices=_,P.positions=u,P.normals=d,P.uvs=f,l){const L=e===le.DOUBLESIDE?h.concat(h):h;P.colors=L}return P}function xS(a,e,t=null,i=earcut){e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation);const s=e.shape,r=e.holes||[],n=e.depth||0,o=e.smoothingThreshold||2,l=[];let h=[];for(let _=0;_<s.length;_++)l[_]=new Z(s[_].x,s[_].z);const c=1e-8;l[0].equalsWithEpsilon(l[l.length-1],c)&&l.pop();const u=new aI(a,l,t||Ae.LastCreatedScene,i);for(let _=0;_<r.length;_++){h=[];for(let p=0;p<r[_].length;p++)h.push(new Z(r[_][p].x,r[_][p].z));u.addHole(h)}const d=u.build(!1,n,o);return d._originalBuilderSideOrientation=e.sideOrientation,gS(d,e.sideOrientation,e.faceUV,e.faceColors,e.frontUVs,e.backUVs,e.wrap).applyToMesh(d,e.updatable),d}function oI(a,e,t=null,i=earcut){return xS(a,e,t,i)}le.CreatePolygon=gS;z.CreatePolygon=(a,e,t,i,s,r,n=earcut)=>xS(a,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);z.ExtrudePolygon=(a,e,t,i,s,r,n,o=earcut)=>oI(a,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,o);function TS(a,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,o=e.cap===0?0:e.cap||z.NO_CAP,l=e.updatable,h=z._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return ES(a,s,i,r,n,null,null,f,d,o,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function lI(a,e,t=null){const i=e.path,s=e.shape,r=e.scaleFunction||(()=>1),n=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||z.NO_CAP,c=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,f=z._GetDefaultSideOrientation(e.sideOrientation),_=e.instance,p=e.invertUV||!1;return ES(a,s,i,null,null,r,n,o,l,h,!0,t,!!c,f,_||null,p,e.frontUVs||null,e.backUVs||null,u,d)}function ES(a,e,t,i,s,r,n,o,l,h,c,u,d,f,_,p,g,x,T,S){const C=(L,w,$,J,ne,oe,re,ce,Se,Ce,ae)=>{const ie=$.getTangents(),F=$.getNormals(),j=$.getBinormals(),se=$.getDistances();if(ae){for(let Ue=0;Ue<ie.length;Ue++)if(ie[Ue].x==0&&ie[Ue].y==0&&ie[Ue].z==0&&ie[Ue].copyFrom(ie[Ue-1]),F[Ue].x==0&&F[Ue].y==0&&F[Ue].z==0&&F[Ue].copyFrom(F[Ue-1]),j[Ue].x==0&&j[Ue].y==0&&j[Ue].z==0&&j[Ue].copyFrom(j[Ue-1]),Ue>0){let Rt=ie[Ue-1];m.Dot(Rt,ie[Ue])<0&&ie[Ue].scaleInPlace(-1),Rt=F[Ue-1],m.Dot(Rt,F[Ue])<0&&F[Ue].scaleInPlace(-1),Rt=j[Ue-1],m.Dot(Rt,j[Ue])<0&&j[Ue].scaleInPlace(-1)}}let Ie=0;const Ye=()=>ne!==null?ne:1,fe=Ce&&ce?ce:()=>oe!==null?oe:0,me=Ce&&re?re:Ye;let Xe=Se===z.NO_CAP||Se===z.CAP_END?0:2;const Fe=U.Matrix[0];for(let Ue=0;Ue<w.length;Ue++){const Rt=[],hi=fe(Ue,se[Ue]),_i=me(Ue,se[Ue]);D.RotationAxisToRef(ie[Ue],Ie,Fe);for(let pi=0;pi<L.length;pi++){const er=ie[Ue].scale(L[pi].z).add(F[Ue].scale(L[pi].x)).add(j[Ue].scale(L[pi].y)),Os=m.Zero();m.TransformCoordinatesToRef(er,Fe,Os),Os.scaleInPlace(_i).addInPlace(w[Ue]),Rt[pi]=Os}J[Xe]=Rt,Ie+=hi,Xe++}const ke=Ue=>{const Rt=Array(),hi=m.Zero();let _i;for(_i=0;_i<Ue.length;_i++)hi.addInPlace(Ue[_i]);for(hi.scaleInPlace(1/Ue.length),_i=0;_i<Ue.length;_i++)Rt.push(hi);return Rt};switch(Se){case z.NO_CAP:break;case z.CAP_START:J[0]=ke(J[2]),J[1]=J[2];break;case z.CAP_END:J[Xe]=J[Xe-1],J[Xe+1]=ke(J[Xe-1]);break;case z.CAP_ALL:J[0]=ke(J[2]),J[1]=J[2],J[Xe]=J[Xe-1],J[Xe+1]=ke(J[Xe-1]);break}return J};let v,b;if(_){const L=_._creationDataStorage;return v=T?L.path3D.update(t,T):L.path3D.update(t),b=C(e,t,L.path3D,L.pathArray,i,s,r,n,L.cap,c,S),_=zl("",{pathArray:b,closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:_},u||void 0),_}v=T?new bu(t,T):new bu(t);const A=new Array;h=h<0||h>3?0:h,b=C(e,t,v,A,i,s,r,n,h,c,S);const P=zl(a,{pathArray:b,closeArray:o,closePath:l,updatable:d,sideOrientation:f,invertUV:p,frontUVs:g||void 0,backUVs:x||void 0},u);return P._creationDataStorage.pathArray=b,P._creationDataStorage.path3D=v,P._creationDataStorage.cap=h,P}z.ExtrudeShape=(a,e,t,i,s,r,n=null,o,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||z.NO_CAP,sideOrientation:l,instance:h,updatable:o};return TS(a,c,n)};z.ExtrudeShapeCustom=(a,e,t,i,s,r,n,o,l,h,c,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:o===0?0:o||z.NO_CAP,sideOrientation:c,instance:u,updatable:h};return lI(a,d,l)};function hI(a,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,s=e.closed===void 0?!0:e.closed,r=e.shape,n=e.radius||1,o=e.tessellation||64,l=e.clip||0,h=e.updatable,c=z._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||z.NO_CAP,d=Math.PI*2,f=[],_=e.invertUV||!1;let p=0,g=0;const x=d/o*i;let T,S;for(p=0;p<=o-l;p++){for(S=[],(u==z.CAP_START||u==z.CAP_ALL)&&(S.push(new m(0,r[0].y,0)),S.push(new m(Math.cos(p*x)*r[0].x*n,r[0].y,Math.sin(p*x)*r[0].x*n))),g=0;g<r.length;g++)T=new m(Math.cos(p*x)*r[g].x*n,r[g].y,Math.sin(p*x)*r[g].x*n),S.push(T);(u==z.CAP_END||u==z.CAP_ALL)&&(S.push(new m(Math.cos(p*x)*r[r.length-1].x*n,r[r.length-1].y,Math.sin(p*x)*r[r.length-1].x*n)),S.push(new m(0,r[r.length-1].y,0))),f.push(S)}return zl(a,{pathArray:f,closeArray:s,sideOrientation:c,updatable:h,invertUV:_,frontUVs:e.frontUVs,backUVs:e.backUVs},t)}z.CreateLathe=(a,e,t,i,s,r,n)=>hI(a,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function cI(a,e,t=null){const i=e.path;let s=e.instance,r=1;e.radius!==void 0?r=e.radius:s&&(r=s._creationDataStorage.radius);const n=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||z.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=z._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(x,T,S,C,v,b,A,P)=>{const L=T.getTangents(),w=T.getNormals(),$=T.getDistances(),ne=Math.PI*2/v*P,re=b||(()=>C);let ce,Se,Ce,ae;const ie=U.Matrix[0];let F=A===z.NO_CAP||A===z.CAP_END?0:2;for(let se=0;se<x.length;se++){Se=re(se,$[se]),ce=Array(),Ce=w[se];for(let Ie=0;Ie<v;Ie++)D.RotationAxisToRef(L[se],ne*Ie,ie),ae=ce[Ie]?ce[Ie]:m.Zero(),m.TransformCoordinatesToRef(Ce,ie,ae),ae.scaleInPlace(Se).addInPlace(x[se]),ce[Ie]=ae;S[F]=ce,F++}const j=(se,Ie)=>{const Ye=Array();for(let $e=0;$e<se;$e++)Ye.push(x[Ie]);return Ye};switch(A){case z.NO_CAP:break;case z.CAP_START:S[0]=j(v,0),S[1]=S[2].slice(0);break;case z.CAP_END:S[F]=S[F-1].slice(0),S[F+1]=j(v,x.length-1);break;case z.CAP_ALL:S[0]=j(v,0),S[1]=S[2].slice(0),S[F]=S[F-1].slice(0),S[F+1]=j(v,x.length-1);break}return S};let f,_;if(s){const x=s._creationDataStorage,T=e.arc||x.arc;return f=x.path3D.update(i),_=d(i,f,x.pathArray,r,x.tessellation,o,x.cap,T),s=zl("",{pathArray:_,instance:s}),x.path3D=f,x.pathArray=_,x.arc=T,x.radius=r,s}f=new bu(i);const p=new Array;l=l<0||l>3?0:l,_=d(i,f,p,r,n,o,l,e.arc);const g=zl(a,{pathArray:_,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=_,g._creationDataStorage.path3D=f,g._creationDataStorage.tessellation=n,g._creationDataStorage.cap=l,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=r,g}z.CreateTube=(a,e,t,i,s,r,n,o,l,h)=>cI(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:o,sideOrientation:l,instance:h},n);function SS(a){const e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const t=a.type&&(a.type<0||a.type>=e.length)?0:a.type||0,i=a.size,s=a.sizeX||i||1,r=a.sizeY||i||1,n=a.sizeZ||i||1,o=a.custom||e[t],l=o.face.length,h=a.faceUV||new Array(l),c=a.faceColors,u=a.flat===void 0?!0:a.flat,d=a.sideOrientation===0?0:a.sideOrientation||le.DEFAULTSIDE,f=[],_=[],p=[],g=[],x=[];let T=0,S=0;const C=[];let v=0,b=0,A,P,L,w,$,J;if(u)for(b=0;b<l;b++)c&&c[b]===void 0&&(c[b]=new xe(1,1,1,1)),h&&h[b]===void 0&&(h[b]=new we(0,0,1,1));if(u)for(b=0;b<l;b++){const oe=o.face[b].length;for(L=2*Math.PI/oe,w=.5*Math.tan(L/2),$=.5,v=0;v<oe;v++)f.push(o.vertex[o.face[b][v]][0]*s,o.vertex[o.face[b][v]][1]*r,o.vertex[o.face[b][v]][2]*n),C.push(T),T++,A=h[b].x+(h[b].z-h[b].x)*(.5+w),P=h[b].y+(h[b].w-h[b].y)*($-.5),g.push(A,mt.UseOpenGLOrientationForUV?1-P:P),J=w*Math.cos(L)-$*Math.sin(L),$=w*Math.sin(L)+$*Math.cos(L),w=J,c&&x.push(c[b].r,c[b].g,c[b].b,c[b].a);for(v=0;v<oe-2;v++)_.push(C[0+S],C[v+2+S],C[v+1+S]);S+=oe}else{for(v=0;v<o.vertex.length;v++)f.push(o.vertex[v][0]*s,o.vertex[v][1]*r,o.vertex[v][2]*n),g.push(0,mt.UseOpenGLOrientationForUV?1:0);for(b=0;b<l;b++)for(v=0;v<o.face[b].length-2;v++)_.push(o.face[b][0],o.face[b][v+2],o.face[b][v+1])}le.ComputeNormals(f,_,p),le._ComputeSides(d,f,_,p,g,a.frontUVs,a.backUVs);const ne=new le;return ne.positions=f,ne.indices=_,ne.normals=p,ne.uvs=g,c&&u&&(ne.colors=x),ne}function uI(a,e={},t=null){const i=new z(a,t);return e.sideOrientation=z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,SS(e).applyToMesh(i,e.updatable),i}le.CreatePolyhedron=SS;z.CreatePolyhedron=(a,e,t)=>uI(a,e,t);const dI=new m(1,0,0),fI=new m(-1,0,0),_I=new m(0,1,0),pI=new m(0,-1,0),mI=new m(0,0,1),gI=new m(0,0,-1);class tf{constructor(e=m.Zero(),t=m.Up(),i=Z.Zero(),s=0,r=0,n=null,o=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new tf(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(s=this.matrixWeightsOverride)==null?void 0:s.slice())}}function xI(a,e,t){var Se,Ce,ae,ie;const i=!!e.skeleton,s=t.localMode||i,r=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,n=e.getIndices(),o=i?e.getPositionData(!0,!0):e.getVerticesData(y.PositionKind),l=i?e.getNormalsData(!0,!0):e.getVerticesData(y.NormalKind),h=s?i?e.getVerticesData(y.PositionKind):o:null,c=s?i?e.getVerticesData(y.NormalKind):l:null,u=e.getVerticesData(y.UVKind),d=i?e.getVerticesData(y.MatricesIndicesKind):null,f=i?e.getVerticesData(y.MatricesWeightsKind):null,_=i?e.getVerticesData(y.MatricesIndicesExtraKind):null,p=i?e.getVerticesData(y.MatricesWeightsExtraKind):null,g=t.position||m.Zero();let x=t.normal||m.Up();const T=t.size||m.One(),S=t.angle||0;if(!x){const F=new m(0,0,1),j=e.getScene().activeCamera,se=m.TransformCoordinates(F,j.getWorldMatrix());x=j.globalPosition.subtract(se)}const C=-Math.atan2(x.z,x.x)-Math.PI/2,v=Math.sqrt(x.x*x.x+x.z*x.z),b=Math.atan2(x.y,v),A=new le;A.indices=[],A.positions=[],A.normals=[],A.uvs=[],A.matricesIndices=i?[]:null,A.matricesWeights=i?[]:null,A.matricesIndicesExtra=_?[]:null,A.matricesWeightsExtra=p?[]:null;let P=0;const L=(F,j)=>{const se=new tf;if(!n||!o||!l)return se;const Ie=n[F];if(se.vertexIdx=Ie*3,se.vertexIdxForBones=Ie*4,se.position=new m(o[Ie*3],o[Ie*3+1],o[Ie*3+2]),m.TransformCoordinatesToRef(se.position,j,se.position),se.normal=new m(l[Ie*3],l[Ie*3+1],l[Ie*3+2]),m.TransformNormalToRef(se.normal,j,se.normal),t.captureUVS&&u){const Ye=u[Ie*2+1];se.uv=new Z(u[Ie*2],mt.UseOpenGLOrientationForUV?1-Ye:Ye)}return se},w=[0,0,0,0],$=(F,j)=>{if(F.length===0)return F;const se=.5*Math.abs(m.Dot(T,j)),Ie=(fe,me,Xe,Fe)=>{for(let ke=0;ke<Fe;++ke)if(fe[Xe+ke]===me)return Xe+ke;return-1},Ye=(fe,me)=>{const Xe=m.GetClipFactor(fe.position,me.position,j,se);let Fe=w,ke=w;if(d&&f){const Rn=fe.matrixIndicesOverride?0:fe.vertexIdxForBones,Qn=fe.matrixIndicesOverride??d,mo=fe.matrixWeightsOverride??f,Jt=me.matrixIndicesOverride?0:me.vertexIdxForBones,el=me.matrixIndicesOverride??d,tl=me.matrixWeightsOverride??f;Fe=[0,0,0,0],ke=[0,0,0,0];let In=0;for(let fr=0;fr<4;++fr)if(mo[Rn+fr]>0){const ba=Ie(el,Qn[Rn+fr],Jt,4);Fe[In]=Qn[Rn+fr],ke[In]=ge.Lerp(mo[Rn+fr],ba>=0?tl[ba]:0,Xe),In++}for(let fr=0;fr<4&&In<4;++fr){const ba=el[Jt+fr];Ie(Qn,ba,Rn,4)===-1&&(Fe[In]=ba,ke[In]=ge.Lerp(0,tl[Jt+fr],Xe),In++)}const an=ke[0]+ke[1]+ke[2]+ke[3];ke[0]/=an,ke[1]/=an,ke[2]/=an,ke[3]/=an}const Ue=fe.localPositionOverride?fe.localPositionOverride[0]:(h==null?void 0:h[fe.vertexIdx])??0,Rt=fe.localPositionOverride?fe.localPositionOverride[1]:(h==null?void 0:h[fe.vertexIdx+1])??0,hi=fe.localPositionOverride?fe.localPositionOverride[2]:(h==null?void 0:h[fe.vertexIdx+2])??0,_i=me.localPositionOverride?me.localPositionOverride[0]:(h==null?void 0:h[me.vertexIdx])??0,pi=me.localPositionOverride?me.localPositionOverride[1]:(h==null?void 0:h[me.vertexIdx+1])??0,er=me.localPositionOverride?me.localPositionOverride[2]:(h==null?void 0:h[me.vertexIdx+2])??0,Os=fe.localNormalOverride?fe.localNormalOverride[0]:(c==null?void 0:c[fe.vertexIdx])??0,Ca=fe.localNormalOverride?fe.localNormalOverride[1]:(c==null?void 0:c[fe.vertexIdx+1])??0,va=fe.localNormalOverride?fe.localNormalOverride[2]:(c==null?void 0:c[fe.vertexIdx+2])??0,po=me.localNormalOverride?me.localNormalOverride[0]:(c==null?void 0:c[me.vertexIdx])??0,yn=me.localNormalOverride?me.localNormalOverride[1]:(c==null?void 0:c[me.vertexIdx+1])??0,Vc=me.localNormalOverride?me.localNormalOverride[2]:(c==null?void 0:c[me.vertexIdx+2])??0,Qo=Os+(po-Os)*Xe,Zo=Ca+(yn-Ca)*Xe,Jo=va+(Vc-va)*Xe,nn=Math.sqrt(Qo*Qo+Zo*Zo+Jo*Jo);return new tf(m.Lerp(fe.position,me.position,Xe),m.Lerp(fe.normal,me.normal,Xe).normalize(),Z.Lerp(fe.uv,me.uv,Xe),-1,-1,h?[Ue+(_i-Ue)*Xe,Rt+(pi-Rt)*Xe,hi+(er-hi)*Xe]:null,c?[Qo/nn,Zo/nn,Jo/nn]:null,Fe,ke)};let $e=null;F.length>3&&($e=[]);for(let fe=0;fe<F.length;fe+=3){let me=0,Xe=null,Fe=null,ke=null,Ue=null;const Rt=m.Dot(F[fe].position,j)-se,hi=m.Dot(F[fe+1].position,j)-se,_i=m.Dot(F[fe+2].position,j)-se,pi=Rt>0,er=hi>0,Os=_i>0;switch(me=(pi?1:0)+(er?1:0)+(Os?1:0),me){case 0:F.length>3?($e.push(F[fe]),$e.push(F[fe+1]),$e.push(F[fe+2])):$e=F;break;case 1:if($e=$e??new Array,pi&&(Xe=F[fe+1],Fe=F[fe+2],ke=Ye(F[fe],Xe),Ue=Ye(F[fe],Fe)),er){Xe=F[fe],Fe=F[fe+2],ke=Ye(F[fe+1],Xe),Ue=Ye(F[fe+1],Fe),$e.push(ke),$e.push(Fe.clone()),$e.push(Xe.clone()),$e.push(Fe.clone()),$e.push(ke.clone()),$e.push(Ue);break}Os&&(Xe=F[fe],Fe=F[fe+1],ke=Ye(F[fe+2],Xe),Ue=Ye(F[fe+2],Fe)),Xe&&Fe&&ke&&Ue&&($e.push(Xe.clone()),$e.push(Fe.clone()),$e.push(ke),$e.push(Ue),$e.push(ke.clone()),$e.push(Fe.clone()));break;case 2:$e=$e??new Array,pi||(Xe=F[fe].clone(),Fe=Ye(Xe,F[fe+1]),ke=Ye(Xe,F[fe+2]),$e.push(Xe),$e.push(Fe),$e.push(ke)),er||(Xe=F[fe+1].clone(),Fe=Ye(Xe,F[fe+2]),ke=Ye(Xe,F[fe]),$e.push(Xe),$e.push(Fe),$e.push(ke)),Os||(Xe=F[fe+2].clone(),Fe=Ye(Xe,F[fe]),ke=Ye(Xe,F[fe+1]),$e.push(Xe),$e.push(Fe),$e.push(ke));break}}return $e},J=e instanceof z?e:null,ne=J==null?void 0:J._thinInstanceDataStorage.matrixData,oe=(J==null?void 0:J.thinInstanceCount)||1,re=U.Matrix[0];re.copyFrom(D.IdentityReadOnly);for(let F=0;F<oe;++F){if(J!=null&&J.hasThinInstances&&ne){const fe=F*16;re.setRowFromFloats(0,ne[fe+0],ne[fe+1],ne[fe+2],ne[fe+3]),re.setRowFromFloats(1,ne[fe+4],ne[fe+5],ne[fe+6],ne[fe+7]),re.setRowFromFloats(2,ne[fe+8],ne[fe+9],ne[fe+10],ne[fe+11]),re.setRowFromFloats(3,ne[fe+12],ne[fe+13],ne[fe+14],ne[fe+15])}const j=D.RotationYawPitchRoll(C,b,S).multiply(D.Translation(g.x,g.y,g.z)),se=D.Invert(j),Ie=e.getWorldMatrix(),Ye=re.multiply(Ie).multiply(se),$e=new Array(3);for(let fe=0;fe<n.length;fe+=3){let me=$e;if(me[0]=L(fe,Ye),r&&s?(me[1]=L(fe+2,Ye),me[2]=L(fe+1,Ye)):(me[1]=L(fe+1,Ye),me[2]=L(fe+2,Ye)),!(t.cullBackFaces&&-me[0].normal.z<=0&&-me[1].normal.z<=0&&-me[2].normal.z<=0)&&(me=$(me,dI),!!me&&(me=$(me,fI),!!me&&(me=$(me,_I),!!me&&(me=$(me,pI),!!me&&(me=$(me,mI),!!me&&(me=$(me,gI),!!me)))))))for(let Xe=0;Xe<me.length;Xe++){const Fe=me[Xe];if(A.indices.push(P),s?(Fe.localPositionOverride?(A.positions[P*3]=Fe.localPositionOverride[0],A.positions[P*3+1]=Fe.localPositionOverride[1],A.positions[P*3+2]=Fe.localPositionOverride[2]):h&&(A.positions[P*3]=h[Fe.vertexIdx],A.positions[P*3+1]=h[Fe.vertexIdx+1],A.positions[P*3+2]=h[Fe.vertexIdx+2]),Fe.localNormalOverride?(A.normals[P*3]=Fe.localNormalOverride[0],A.normals[P*3+1]=Fe.localNormalOverride[1],A.normals[P*3+2]=Fe.localNormalOverride[2]):c&&(A.normals[P*3]=c[Fe.vertexIdx],A.normals[P*3+1]=c[Fe.vertexIdx+1],A.normals[P*3+2]=c[Fe.vertexIdx+2])):(Fe.position.toArray(A.positions,P*3),Fe.normal.toArray(A.normals,P*3)),A.matricesIndices&&A.matricesWeights&&(Fe.matrixIndicesOverride?(A.matricesIndices[P*4]=Fe.matrixIndicesOverride[0],A.matricesIndices[P*4+1]=Fe.matrixIndicesOverride[1],A.matricesIndices[P*4+2]=Fe.matrixIndicesOverride[2],A.matricesIndices[P*4+3]=Fe.matrixIndicesOverride[3]):(d&&(A.matricesIndices[P*4]=d[Fe.vertexIdxForBones],A.matricesIndices[P*4+1]=d[Fe.vertexIdxForBones+1],A.matricesIndices[P*4+2]=d[Fe.vertexIdxForBones+2],A.matricesIndices[P*4+3]=d[Fe.vertexIdxForBones+3]),_&&A.matricesIndicesExtra&&(A.matricesIndicesExtra[P*4]=_[Fe.vertexIdxForBones],A.matricesIndicesExtra[P*4+1]=_[Fe.vertexIdxForBones+1],A.matricesIndicesExtra[P*4+2]=_[Fe.vertexIdxForBones+2],A.matricesIndicesExtra[P*4+3]=_[Fe.vertexIdxForBones+3])),Fe.matrixWeightsOverride?(A.matricesWeights[P*4]=Fe.matrixWeightsOverride[0],A.matricesWeights[P*4+1]=Fe.matrixWeightsOverride[1],A.matricesWeights[P*4+2]=Fe.matrixWeightsOverride[2],A.matricesWeights[P*4+3]=Fe.matrixWeightsOverride[3]):(f&&(A.matricesWeights[P*4]=f[Fe.vertexIdxForBones],A.matricesWeights[P*4+1]=f[Fe.vertexIdxForBones+1],A.matricesWeights[P*4+2]=f[Fe.vertexIdxForBones+2],A.matricesWeights[P*4+3]=f[Fe.vertexIdxForBones+3]),p&&A.matricesWeightsExtra&&(A.matricesWeightsExtra[P*4]=p[Fe.vertexIdxForBones],A.matricesWeightsExtra[P*4+1]=p[Fe.vertexIdxForBones+1],A.matricesWeightsExtra[P*4+2]=p[Fe.vertexIdxForBones+2],A.matricesWeightsExtra[P*4+3]=p[Fe.vertexIdxForBones+3]))),t.captureUVS)Fe.uv.toArray(A.uvs,P*2);else{A.uvs.push(.5+Fe.position.x/T.x);const ke=.5+Fe.position.y/T.y;A.uvs.push(mt.UseOpenGLOrientationForUV?1-ke:ke)}P++}}}A.indices.length===0&&(A.indices=null),A.positions.length===0&&(A.positions=null),A.normals.length===0&&(A.normals=null),A.uvs.length===0&&(A.uvs=null),((Se=A.matricesIndices)==null?void 0:Se.length)===0&&(A.matricesIndices=null),((Ce=A.matricesWeights)==null?void 0:Ce.length)===0&&(A.matricesWeights=null),((ae=A.matricesIndicesExtra)==null?void 0:ae.length)===0&&(A.matricesIndicesExtra=null),((ie=A.matricesWeightsExtra)==null?void 0:ie.length)===0&&(A.matricesWeightsExtra=null);const ce=new z(a,e.getScene());return A.applyToMesh(ce),s?(ce.skeleton=e.skeleton,ce.parent=e):(ce.position=g.clone(),ce.rotation=new m(b,C,S)),ce.computeWorldMatrix(!0),ce.refreshBoundingInfo(!0,!0),ce}z.CreateDecal=(a,e,t,i,s,r)=>xI(a,e,{position:t,normal:i,size:s,angle:r});z._GoldbergMeshParser=(a,e)=>Qm.Parse(a,e);class Qm extends z{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(O.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(O.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(O.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i<e.length;i++){const s=e[i][0],r=e[i][1],n=e[i][2];for(let o=s;o<r+1;o++)this.goldbergData.faceColors[o]=n}const t=[];for(let i=0;i<12;i++)for(let s=0;s<5;s++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);for(let i=12;i<this.goldbergData.faceColors.length;i++)for(let s=0;s<6;s++)t.push(this.goldbergData.faceColors[i].r,this.goldbergData.faceColors[i].g,this.goldbergData.faceColors[i].b,this.goldbergData.faceColors[i].a);return t}setGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.setVerticesData(y.ColorKind,t)}updateGoldbergFaceColors(e){const t=this._changeGoldbergFaceColors(e);this.updateVerticesData(y.ColorKind,t)}_changeGoldbergFaceUVs(e){const t=this.getVerticesData(y.UVKind);for(let i=0;i<e.length;i++){const s=e[i][0],r=e[i][1],n=e[i][2],o=e[i][3],l=e[i][4],h=[],c=[];let u,d;for(let f=0;f<5;f++)u=n.x+o*Math.cos(l+f*Math.PI/2.5),d=n.y+o*Math.sin(l+f*Math.PI/2.5),u<0&&(u=0),u>1&&(u=1),h.push(u,d);for(let f=0;f<6;f++)u=n.x+o*Math.cos(l+f*Math.PI/3),d=n.y+o*Math.sin(l+f*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,d);for(let f=s;f<Math.min(12,r+1);f++)for(let _=0;_<5;_++)t[10*f+2*_]=h[2*_],t[10*f+2*_+1]=h[2*_+1];for(let f=Math.max(12,s);f<r+1;f++)for(let _=0;_<6;_++)t[12*f-24+2*_]=c[2*_],t[12*f-23+2*_]=c[2*_+1]}return t}setGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.setVerticesData(y.UVKind,t)}updateGoldbergFaceUVs(e){const t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(y.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){const s=m.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=s,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";const t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors){t.faceColors=[];for(const i of this.goldbergData.faceColors)t.faceColors.push(i.asArray())}if(this.goldbergData.faceCenters){t.faceCenters=[];for(const i of this.goldbergData.faceCenters)t.faceCenters.push(i.asArray())}if(this.goldbergData.faceZaxis){t.faceZaxis=[];for(const i of this.goldbergData.faceZaxis)t.faceZaxis.push(i.asArray())}if(this.goldbergData.faceYaxis){t.faceYaxis=[];for(const i of this.goldbergData.faceYaxis)t.faceYaxis.push(i.asArray())}if(this.goldbergData.faceXaxis){t.faceXaxis=[];for(const i of this.goldbergData.faceXaxis)t.faceXaxis.push(i.asArray())}e.goldbergData=t}static Parse(e,t){const i=e.goldbergData;i.faceColors=i.faceColors.map(r=>xe.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>m.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>m.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>m.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>m.FromArray(r));const s=new Qm(e.name,t);return s.goldbergData=i,s}}class TI{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new Cf(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,s){this._currentPath.addQuadraticCurveTo(e,t,i,s,this._resolution)}bezierCurveTo(e,t,i,s,r,n){this._currentPath.addBezierCurveTo(e,t,i,s,r,n,this._resolution)}extractHoles(){for(const e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function EI(a,e,t,i,s,r){const n=r.glyphs[a]||r.glyphs["?"];if(!n)return null;const o=new TI(s);if(n.o){const l=n.o.split(" ");for(let h=0,c=l.length;h<c;)switch(l[h++]){case"m":{const d=parseInt(l[h++])*e+t,f=parseInt(l[h++])*e+i;o.moveTo(d,f);break}case"l":{const d=parseInt(l[h++])*e+t,f=parseInt(l[h++])*e+i;o.lineTo(d,f);break}case"q":{const d=parseInt(l[h++])*e+t,f=parseInt(l[h++])*e+i,_=parseInt(l[h++])*e+t,p=parseInt(l[h++])*e+i;o.quadraticCurveTo(_,p,d,f);break}case"b":{const d=parseInt(l[h++])*e+t,f=parseInt(l[h++])*e+i,_=parseInt(l[h++])*e+t,p=parseInt(l[h++])*e+i,g=parseInt(l[h++])*e+t,x=parseInt(l[h++])*e+i;o.bezierCurveTo(_,p,g,x,d,f);break}}}return o.extractHoles(),{offsetX:n.ha*e,shapePath:o}}function SI(a,e,t,i){const s=Array.from(a),r=e/i.resolution,n=(i.boundingBox.yMax-i.boundingBox.yMin+i.underlineThickness)*r,o=[];let l=0,h=0;for(let c=0;c<s.length;c++){const u=s[c];if(u===`
`)l=0,h-=n;else{const d=EI(u,r,l,h,t,i);d&&(l+=d.offsetX,o.push(d.shapePath))}}return o}class Y{}Y.ALPHA_DISABLE=0;Y.ALPHA_ADD=1;Y.ALPHA_COMBINE=2;Y.ALPHA_SUBTRACT=3;Y.ALPHA_MULTIPLY=4;Y.ALPHA_MAXIMIZED=5;Y.ALPHA_ONEONE=6;Y.ALPHA_PREMULTIPLIED=7;Y.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Y.ALPHA_INTERPOLATE=9;Y.ALPHA_SCREENMODE=10;Y.ALPHA_ONEONE_ONEONE=11;Y.ALPHA_ALPHATOCOLOR=12;Y.ALPHA_REVERSEONEMINUS=13;Y.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;Y.ALPHA_ONEONE_ONEZERO=15;Y.ALPHA_EXCLUSION=16;Y.ALPHA_LAYER_ACCUMULATE=17;Y.ALPHA_EQUATION_ADD=0;Y.ALPHA_EQUATION_SUBSTRACT=1;Y.ALPHA_EQUATION_REVERSE_SUBTRACT=2;Y.ALPHA_EQUATION_MAX=3;Y.ALPHA_EQUATION_MIN=4;Y.ALPHA_EQUATION_DARKEN=5;Y.DELAYLOADSTATE_NONE=0;Y.DELAYLOADSTATE_LOADED=1;Y.DELAYLOADSTATE_LOADING=2;Y.DELAYLOADSTATE_NOTLOADED=4;Y.NEVER=512;Y.ALWAYS=519;Y.LESS=513;Y.EQUAL=514;Y.LEQUAL=515;Y.GREATER=516;Y.GEQUAL=518;Y.NOTEQUAL=517;Y.KEEP=7680;Y.ZERO=0;Y.REPLACE=7681;Y.INCR=7682;Y.DECR=7683;Y.INVERT=5386;Y.INCR_WRAP=34055;Y.DECR_WRAP=34056;Y.TEXTURE_CLAMP_ADDRESSMODE=0;Y.TEXTURE_WRAP_ADDRESSMODE=1;Y.TEXTURE_MIRROR_ADDRESSMODE=2;Y.TEXTURE_CREATIONFLAG_STORAGE=1;Y.TEXTUREFORMAT_ALPHA=0;Y.TEXTUREFORMAT_LUMINANCE=1;Y.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Y.TEXTUREFORMAT_RGB=4;Y.TEXTUREFORMAT_RGBA=5;Y.TEXTUREFORMAT_RED=6;Y.TEXTUREFORMAT_R=6;Y.TEXTUREFORMAT_RG=7;Y.TEXTUREFORMAT_RED_INTEGER=8;Y.TEXTUREFORMAT_R_INTEGER=8;Y.TEXTUREFORMAT_RG_INTEGER=9;Y.TEXTUREFORMAT_RGB_INTEGER=10;Y.TEXTUREFORMAT_RGBA_INTEGER=11;Y.TEXTUREFORMAT_BGRA=12;Y.TEXTUREFORMAT_DEPTH24_STENCIL8=13;Y.TEXTUREFORMAT_DEPTH32_FLOAT=14;Y.TEXTUREFORMAT_DEPTH16=15;Y.TEXTUREFORMAT_DEPTH24=16;Y.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;Y.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;Y.TEXTUREFORMAT_STENCIL8=19;Y.TEXTUREFORMAT_UNDEFINED=4294967295;Y.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;Y.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;Y.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;Y.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;Y.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;Y.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;Y.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;Y.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;Y.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;Y.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;Y.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;Y.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;Y.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;Y.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;Y.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;Y.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;Y.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;Y.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;Y.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;Y.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;Y.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;Y.TEXTURETYPE_UNSIGNED_BYTE=0;Y.TEXTURETYPE_UNSIGNED_INT=0;Y.TEXTURETYPE_FLOAT=1;Y.TEXTURETYPE_HALF_FLOAT=2;Y.TEXTURETYPE_BYTE=3;Y.TEXTURETYPE_SHORT=4;Y.TEXTURETYPE_UNSIGNED_SHORT=5;Y.TEXTURETYPE_INT=6;Y.TEXTURETYPE_UNSIGNED_INTEGER=7;Y.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Y.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Y.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Y.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Y.TEXTURETYPE_UNSIGNED_INT_24_8=12;Y.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Y.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Y.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Y.TEXTURETYPE_UNDEFINED=16;Y.TEXTURE_2D=3553;Y.TEXTURE_2D_ARRAY=35866;Y.TEXTURE_CUBE_MAP=34067;Y.TEXTURE_CUBE_MAP_ARRAY=3735928559;Y.TEXTURE_3D=32879;Y.TEXTURE_NEAREST_SAMPLINGMODE=1;Y.TEXTURE_NEAREST_NEAREST=1;Y.TEXTURE_BILINEAR_SAMPLINGMODE=2;Y.TEXTURE_LINEAR_LINEAR=2;Y.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Y.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Y.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Y.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Y.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Y.TEXTURE_NEAREST_LINEAR=7;Y.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Y.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Y.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Y.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Y.TEXTURE_LINEAR_NEAREST=12;Y.TEXTURE_EXPLICIT_MODE=0;Y.TEXTURE_SPHERICAL_MODE=1;Y.TEXTURE_PLANAR_MODE=2;Y.TEXTURE_CUBIC_MODE=3;Y.TEXTURE_PROJECTION_MODE=4;Y.TEXTURE_SKYBOX_MODE=5;Y.TEXTURE_INVCUBIC_MODE=6;Y.TEXTURE_EQUIRECTANGULAR_MODE=7;Y.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Y.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Y.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;Y.TEXTURE_FILTERING_QUALITY_HIGH=64;Y.TEXTURE_FILTERING_QUALITY_MEDIUM=16;Y.TEXTURE_FILTERING_QUALITY_LOW=8;Y.SCALEMODE_FLOOR=1;Y.SCALEMODE_NEAREST=2;Y.SCALEMODE_CEILING=3;Y.MATERIAL_TextureDirtyFlag=1;Y.MATERIAL_LightDirtyFlag=2;Y.MATERIAL_FresnelDirtyFlag=4;Y.MATERIAL_AttributesDirtyFlag=8;Y.MATERIAL_MiscDirtyFlag=16;Y.MATERIAL_PrePassDirtyFlag=32;Y.MATERIAL_AllDirtyFlag=63;Y.MATERIAL_TriangleFillMode=0;Y.MATERIAL_WireFrameFillMode=1;Y.MATERIAL_PointFillMode=2;Y.MATERIAL_PointListDrawMode=3;Y.MATERIAL_LineListDrawMode=4;Y.MATERIAL_LineLoopDrawMode=5;Y.MATERIAL_LineStripDrawMode=6;Y.MATERIAL_TriangleStripDrawMode=7;Y.MATERIAL_TriangleFanDrawMode=8;Y.MATERIAL_ClockWiseSideOrientation=0;Y.MATERIAL_CounterClockWiseSideOrientation=1;Y.ACTION_NothingTrigger=0;Y.ACTION_OnPickTrigger=1;Y.ACTION_OnLeftPickTrigger=2;Y.ACTION_OnRightPickTrigger=3;Y.ACTION_OnCenterPickTrigger=4;Y.ACTION_OnPickDownTrigger=5;Y.ACTION_OnDoublePickTrigger=6;Y.ACTION_OnPickUpTrigger=7;Y.ACTION_OnPickOutTrigger=16;Y.ACTION_OnLongPressTrigger=8;Y.ACTION_OnPointerOverTrigger=9;Y.ACTION_OnPointerOutTrigger=10;Y.ACTION_OnEveryFrameTrigger=11;Y.ACTION_OnIntersectionEnterTrigger=12;Y.ACTION_OnIntersectionExitTrigger=13;Y.ACTION_OnKeyDownTrigger=14;Y.ACTION_OnKeyUpTrigger=15;Y.PARTICLES_BILLBOARDMODE_Y=2;Y.PARTICLES_BILLBOARDMODE_ALL=7;Y.PARTICLES_BILLBOARDMODE_STRETCHED=8;Y.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;Y.MESHES_CULLINGSTRATEGY_STANDARD=0;Y.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Y.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Y.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Y.SCENELOADER_NO_LOGGING=0;Y.SCENELOADER_MINIMAL_LOGGING=1;Y.SCENELOADER_SUMMARY_LOGGING=2;Y.SCENELOADER_DETAILED_LOGGING=3;Y.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;Y.PREPASS_POSITION_TEXTURE_TYPE=1;Y.PREPASS_VELOCITY_TEXTURE_TYPE=2;Y.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;Y.PREPASS_COLOR_TEXTURE_TYPE=4;Y.PREPASS_DEPTH_TEXTURE_TYPE=5;Y.PREPASS_NORMAL_TEXTURE_TYPE=6;Y.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;Y.BUFFER_CREATIONFLAG_READ=1;Y.BUFFER_CREATIONFLAG_WRITE=2;Y.BUFFER_CREATIONFLAG_READWRITE=3;Y.BUFFER_CREATIONFLAG_UNIFORM=4;Y.BUFFER_CREATIONFLAG_VERTEX=8;Y.BUFFER_CREATIONFLAG_INDEX=16;Y.BUFFER_CREATIONFLAG_STORAGE=32;Y.RENDERPASS_MAIN=0;Y.INPUT_ALT_KEY=18;Y.INPUT_CTRL_KEY=17;Y.INPUT_META_KEY1=91;Y.INPUT_META_KEY2=92;Y.INPUT_META_KEY3=93;Y.INPUT_SHIFT_KEY=16;Y.SNAPSHOTRENDERING_STANDARD=0;Y.SNAPSHOTRENDERING_FAST=1;Y.PERSPECTIVE_CAMERA=0;Y.ORTHOGRAPHIC_CAMERA=1;Y.FOVMODE_VERTICAL_FIXED=0;Y.FOVMODE_HORIZONTAL_FIXED=1;Y.RIG_MODE_NONE=0;Y.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Y.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Y.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Y.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Y.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Y.RIG_MODE_VR=20;Y.RIG_MODE_CUSTOM=22;Y.MAX_SUPPORTED_UV_SETS=6;Y.GL_ALPHA_EQUATION_ADD=32774;Y.GL_ALPHA_EQUATION_MIN=32775;Y.GL_ALPHA_EQUATION_MAX=32776;Y.GL_ALPHA_EQUATION_SUBTRACT=32778;Y.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;Y.GL_ALPHA_FUNCTION_SRC=768;Y.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;Y.GL_ALPHA_FUNCTION_SRC_ALPHA=770;Y.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;Y.GL_ALPHA_FUNCTION_DST_ALPHA=772;Y.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;Y.GL_ALPHA_FUNCTION_DST_COLOR=774;Y.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;Y.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;Y.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;Y.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;Y.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;Y.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;Y.SnippetUrl="https://snippet.babylonjs.com";Y.FOGMODE_NONE=0;Y.FOGMODE_EXP=1;Y.FOGMODE_EXP2=2;Y.FOGMODE_LINEAR=3;Y.BYTE=5120;Y.UNSIGNED_BYTE=5121;Y.SHORT=5122;Y.UNSIGNED_SHORT=5123;Y.INT=5124;Y.UNSIGNED_INT=5125;Y.FLOAT=5126;Y.PositionKind="position";Y.NormalKind="normal";Y.TangentKind="tangent";Y.UVKind="uv";Y.UV2Kind="uv2";Y.UV3Kind="uv3";Y.UV4Kind="uv4";Y.UV5Kind="uv5";Y.UV6Kind="uv6";Y.ColorKind="color";Y.ColorInstanceKind="instanceColor";Y.MatricesIndicesKind="matricesIndices";Y.MatricesWeightsKind="matricesWeights";Y.MatricesIndicesExtraKind="matricesIndicesExtra";Y.MatricesWeightsExtraKind="matricesWeightsExtra";pe.prototype._debugPushGroup=function(a,e){};pe.prototype._debugPopGroup=function(a){};pe.prototype._debugInsertMarker=function(a,e){};pe.prototype._debugFlushPendingCommands=function(){};class CI{constructor(){this._timeElapsedQueryEnded=!1}}class vI{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=ut.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=ut.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}H.prototype.createQuery=function(){const a=this._gl.createQuery();if(!a)throw new Error("Unable to create Occlusion Query");return a};H.prototype.deleteQuery=function(a){return this._gl.deleteQuery(a),this};H.prototype.isQueryResultAvailable=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT_AVAILABLE)};H.prototype.getQueryResult=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT)};H.prototype.beginOcclusionQuery=function(a,e){const t=this._getGlAlgorithmType(a);return this._gl.beginQuery(t,e),!0};H.prototype.endOcclusionQuery=function(a){const e=this._getGlAlgorithmType(a);return this._gl.endQuery(e),this};H.prototype._createTimeQuery=function(){const a=this.getCaps().timerQuery;return a.createQueryEXT?a.createQueryEXT():this.createQuery()};H.prototype._deleteTimeQuery=function(a){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(a);return}this.deleteQuery(a)};H.prototype._getTimeQueryResult=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_EXT):this.getQueryResult(a)};H.prototype._getTimeQueryAvailability=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(a)};H.prototype.startTimeQuery=function(){const a=this.getCaps(),e=a.timerQuery;if(!e)return null;const t=new CI;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),a.canUseTimestampForTimerQuery)t._startTimeQuery=this._createTimeQuery(),e.queryCounterEXT(t._startTimeQuery,e.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;t._timeElapsedQuery=this._createTimeQuery(),e.beginQueryEXT?e.beginQueryEXT(e.TIME_ELAPSED_EXT,t._timeElapsedQuery):this._gl.beginQuery(e.TIME_ELAPSED_EXT,t._timeElapsedQuery),this._currentNonTimestampToken=t}return t};H.prototype.endTimeQuery=function(a){const e=this.getCaps(),t=e.timerQuery;if(!t||!a)return-1;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery)return-1;a._endTimeQuery||(a._endTimeQuery=this._createTimeQuery(),t.queryCounterEXT(a._endTimeQuery,t.TIMESTAMP_EXT))}else if(!a._timeElapsedQueryEnded){if(!a._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),a._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let s=!1;if(a._endTimeQuery?s=this._getTimeQueryAvailability(a._endTimeQuery):a._timeElapsedQuery&&(s=this._getTimeQueryAvailability(a._timeElapsedQuery)),s&&!i){let r=0;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery||!a._endTimeQuery)return-1;const n=this._getTimeQueryResult(a._startTimeQuery);r=this._getTimeQueryResult(a._endTimeQuery)-n,this._deleteTimeQuery(a._startTimeQuery),this._deleteTimeQuery(a._endTimeQuery),a._startTimeQuery=null,a._endTimeQuery=null}else{if(!a._timeElapsedQuery)return-1;r=this._getTimeQueryResult(a._timeElapsedQuery),this._deleteTimeQuery(a._timeElapsedQuery),a._timeElapsedQuery=null,a._timeElapsedQueryEnded=!1}return r}return-1};H.prototype._captureGPUFrameTime=!1;H.prototype._gpuFrameTime=new wr;H.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};H.prototype.captureGPUFrameTime=function(a){a!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=a,a?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))};H.prototype._getGlAlgorithmType=function(a){return a===ut.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(ut.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(a){this._occlusionDataStorage.isOcclusionQueryInProgress=a},enumerable:!1,configurable:!0});Object.defineProperty(ut.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new vI),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(ut.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(a){this._occlusionDataStorage.isOccluded=a},enumerable:!0,configurable:!0});Object.defineProperty(ut.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(a){this._occlusionDataStorage.occlusionQueryAlgorithmType=a},enumerable:!0,configurable:!0});Object.defineProperty(ut.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(a){this._occlusionDataStorage.occlusionType=a},enumerable:!0,configurable:!0});Object.defineProperty(ut.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(a){this._occlusionDataStorage.occlusionRetryCount=a},enumerable:!0,configurable:!0});Object.defineProperty(ut.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(a){this._occlusionDataStorage.forceRenderingWhenOccluded=a},enumerable:!0,configurable:!0});ut.prototype._checkOcclusionQuery=function(){const a=this._occlusionDataStorage;if(a.occlusionType===ut.OCCLUSION_TYPE_NONE)return a.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return a.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=!(s>0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===ut.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===ut.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),e.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};H.prototype.createTransformFeedback=function(){const a=this._gl.createTransformFeedback();if(!a)throw new Error("Unable to create Transform Feedback");return a};H.prototype.deleteTransformFeedback=function(a){this._gl.deleteTransformFeedback(a)};H.prototype.bindTransformFeedback=function(a){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,a)};H.prototype.beginTransformFeedback=function(a=!0){this._gl.beginTransformFeedback(a?this._gl.POINTS:this._gl.TRIANGLES)};H.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};H.prototype.setTranformFeedbackVaryings=function(a,e){this._gl.transformFeedbackVaryings(a,e,this._gl.INTERLEAVED_ATTRIBS)};H.prototype.bindTransformFeedbackBuffer=function(a){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,a?a.underlyingResource:null)};pe.prototype.createExternalTexture=function(a){return null};pe.prototype.setExternalTexture=function(a,e){throw new Error("setExternalTexture: This engine does not support external textures!")};pe.prototype.updateVideoTexture=function(a,e,t){if(!a||a._isDisabled)return;const i=this._getInternalFormat(a.format),s=this._getRGBABufferInternalSizedFormat(0,a.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,e),this._gl.getError()!==0?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,e);else{if(!a._workingCanvas){a._workingCanvas=this.createCanvas(a.width,a.height);const n=a._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");a._workingContext=n,a._workingCanvas.width=a.width,a._workingCanvas.height=a.height}a._workingContext.clearRect(0,0,a.width,a.height),a._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,a.width,a.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,a._workingCanvas)}a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0}catch{a._isDisabled=!0}};pe.prototype.restoreSingleAttachment=function(){const a=this._gl;this.bindAttachments([a.BACK])};pe.prototype.restoreSingleAttachmentForRenderTarget=function(){const a=this._gl;this.bindAttachments([a.COLOR_ATTACHMENT0])};pe.prototype.buildTextureLayout=function(a){const e=this._gl,t=[];for(let i=0;i<a.length;i++)a[i]?t.push(e["COLOR_ATTACHMENT"+i]):t.push(e.NONE);return t};pe.prototype.bindAttachments=function(a){this._gl.drawBuffers(a)};pe.prototype.unBindMultiColorAttachmentFramebuffer=function(a,e=!1,t){this._currentRenderTarget=null;const i=this._gl,s=a._attachments,r=s.length;if(a._MSAAFramebuffer){i.bindFramebuffer(i.READ_FRAMEBUFFER,a._MSAAFramebuffer),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,a._framebuffer);for(let n=0;n<r;n++){const o=a.textures[n];for(let l=0;l<r;l++)s[l]=i.NONE;s[n]=i[this.webGLVersion>1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],i.readBuffer(s[n]),i.drawBuffers(s),i.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let n=0;n<r;n++)s[n]=i[this.webGLVersion>1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"];i.drawBuffers(s)}for(let n=0;n<r;n++){const o=a.textures[n];o!=null&&o.generateMipMaps&&!e&&!o.isCube&&(this._bindTextureDirectly(i.TEXTURE_2D,o,!0),i.generateMipmap(i.TEXTURE_2D),this._bindTextureDirectly(i.TEXTURE_2D,null))}t&&(a._MSAAFramebuffer&&this._bindUnboundFramebuffer(a._framebuffer),t()),this._bindUnboundFramebuffer(null)};pe.prototype.createMultipleRenderTarget=function(a,e,t=!0){let i=!1,s=!0,r=!1,n=!1,o=15,l=1;const h=0,c=3,u=!1,d=5,f=3553;let _=[],p=[],g=[],x=[],T=[],S=[],C=[],v=[];const b=this._createHardwareRenderTargetWrapper(!0,!1,a);e!==void 0&&(i=e.generateMipMaps===void 0?!1:e.generateMipMaps,s=e.generateDepthBuffer===void 0?!0:e.generateDepthBuffer,r=e.generateStencilBuffer===void 0?!1:e.generateStencilBuffer,n=e.generateDepthTexture===void 0?!1:e.generateDepthTexture,l=e.textureCount||1,e.types&&(_=e.types),e.samplingModes&&(p=e.samplingModes),e.useSRGBBuffers&&(g=e.useSRGBBuffers),e.formats&&(x=e.formats),e.targetTypes&&(T=e.targetTypes),e.faceIndex&&(S=e.faceIndex),e.layerIndex&&(C=e.layerIndex),e.layerCounts&&(v=e.layerCounts),this.webGLVersion>1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),b.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const A=this._gl,P=A.createFramebuffer();this._bindUnboundFramebuffer(P);const L=a.width||a,w=a.height||a,$=[],J=[],ne=this.webGLVersion>1&&n&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),oe=this._setupFramebufferDepthAttachments(!ne&&r,!n&&s,L,w);b._framebuffer=P,b._depthStencilBuffer=oe,b._generateDepthBuffer=!n&&s,b._generateStencilBuffer=!ne&&r,b._attachments=J;for(let re=0;re<l;re++){let ce=p[re]||c,Se=_[re]||h,Ce=g[re]||u;const ae=x[re]||d,ie=T[re]||f,F=v[re]??1;(Se===1&&!this._caps.textureFloatLinearFiltering||Se===2&&!this._caps.textureHalfFloatLinearFiltering)&&(ce=1);const j=this._getSamplingParameters(ce,i);Se===1&&!this._caps.textureFloat&&(Se=0,O.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),Ce=Ce&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);const se=this.webGLVersion>1,Ie=A[se?"COLOR_ATTACHMENT"+re:"COLOR_ATTACHMENT"+re+"_WEBGL"];if(J.push(Ie),ie===-1)continue;const Ye=new Tt(this,et.MultiRenderTarget);$[re]=Ye,A.activeTexture(A["TEXTURE"+re]),A.bindTexture(ie,Ye._hardwareTexture.underlyingResource),A.texParameteri(ie,A.TEXTURE_MAG_FILTER,j.mag),A.texParameteri(ie,A.TEXTURE_MIN_FILTER,j.min),A.texParameteri(ie,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(ie,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE);const $e=this._getRGBABufferInternalSizedFormat(Se,ae,Ce),fe=this._getInternalFormat(ae),me=this._getWebGLTextureType(Se);if(se&&(ie===35866||ie===32879))ie===35866?Ye.is2DArray=!0:Ye.is3D=!0,Ye.baseDepth=Ye.depth=F,A.texImage3D(ie,0,$e,L,w,F,0,fe,me,null);else if(ie===34067){for(let Xe=0;Xe<6;Xe++)A.texImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+Xe,0,$e,L,w,0,fe,me,null);Ye.isCube=!0}else A.texImage2D(A.TEXTURE_2D,0,$e,L,w,0,fe,me,null);i&&A.generateMipmap(ie),this._bindTextureDirectly(ie,null),Ye.baseWidth=L,Ye.baseHeight=w,Ye.width=L,Ye.height=w,Ye.isReady=!0,Ye.samples=1,Ye.generateMipMaps=i,Ye.samplingMode=ce,Ye.type=Se,Ye._useSRGBBuffer=Ce,Ye.format=ae,this._internalTexturesCache.push(Ye)}if(n&&this._caps.depthTextureExtension){const re=new Tt(this,et.Depth);let ce=5,Se=A.DEPTH_COMPONENT16,Ce=A.DEPTH_COMPONENT,ae=A.UNSIGNED_SHORT,ie=A.DEPTH_ATTACHMENT;this.webGLVersion<2?Se=A.DEPTH_COMPONENT:o===14?(ce=1,ae=A.FLOAT,Se=A.DEPTH_COMPONENT32F):o===18?(ce=0,ae=A.FLOAT_32_UNSIGNED_INT_24_8_REV,Se=A.DEPTH32F_STENCIL8,Ce=A.DEPTH_STENCIL,ie=A.DEPTH_STENCIL_ATTACHMENT):o===16?(ce=0,ae=A.UNSIGNED_INT,Se=A.DEPTH_COMPONENT24,ie=A.DEPTH_ATTACHMENT):(o===13||o===17)&&(ce=12,ae=A.UNSIGNED_INT_24_8,Se=A.DEPTH24_STENCIL8,Ce=A.DEPTH_STENCIL,ie=A.DEPTH_STENCIL_ATTACHMENT),A.activeTexture(A.TEXTURE0),A.bindTexture(A.TEXTURE_2D,re._hardwareTexture.underlyingResource),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE),A.texImage2D(A.TEXTURE_2D,0,Se,L,w,0,Ce,ae,null),A.framebufferTexture2D(A.FRAMEBUFFER,ie,A.TEXTURE_2D,re._hardwareTexture.underlyingResource,0),re.baseWidth=L,re.baseHeight=w,re.width=L,re.height=w,re.isReady=!0,re.samples=1,re.generateMipMaps=i,re.samplingMode=1,re.format=o,re.type=ce,$[l]=re,this._internalTexturesCache.push(re)}return b.setTextures($),t&&A.drawBuffers(J),this._bindUnboundFramebuffer(null),b.setLayerAndFaceIndices(C,S),this.resetTextureCache(),b};pe.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,e,t=!0){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const i=a._attachments.length;if(i===0)return 1;const s=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const r=!!a._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(s.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null),e>1&&typeof s.renderbufferStorageMultisample=="function"){const n=s.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let l=0;l<i;l++)a.textures[l]._hardwareTexture.releaseMSAARenderBuffers();for(let l=0;l<i;l++){const h=a.textures[l],c=h._hardwareTexture,u=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(h.width,h.height,e,-1,this._getRGBABufferInternalSizedFormat(h.type,h.format,h._useSRGBBuffer),u);if(!d)throw new Error("Unable to create multi sampled framebuffer");c.addMSAARenderBuffer(d),h.samples=e,o.push(u)}t&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(a._framebuffer);return r&&(a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e)),this._bindUnboundFramebuffer(null),e};pe.prototype._createDepthStencilCubeTexture=function(a,e){const t=new Tt(this,et.DepthStencil);if(t.isCube=!0,this.webGLVersion===1)return O.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let r=0;r<6;r++)i.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH24_STENCIL8,a,a,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH_COMPONENT24,a,a,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};pe.prototype._partialLoadFile=function(a,e,t,i,s=null){const r=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},n=(o,l)=>{s&&o&&s(o.status+" "+o.statusText,l)};this._loadFile(a,r,void 0,void 0,!0,n)};pe.prototype._cascadeLoadFiles=function(a,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};pe.prototype._cascadeLoadImgs=function(a,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,n,a,e,t,s,r)};pe.prototype._partialLoadImg=function(a,e,t,i,s,r,n=null,o){const l=en();Hu(a,u=>{t[e]=u,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&r&&r(s,t)},(u,d)=>{i&&i.removePendingData(l),n&&n(u,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};pe.prototype._setCubeMapTextureParams=function(a,e,t){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),a.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),a._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};pe.prototype.createCubeTextureBase=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d=null,f=null,_=!1){const p=u||new Tt(this,et.Cube);p.isCube=!0,p.url=a,p.generateMipMaps=!i,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!i),p!==u&&(p.label=a.substring(0,60)),this._doNotHandleContextLost||(p._extension=o,p._files=t);const g=a;this._transformTextureUrl&&!u&&(a=this._transformTextureUrl(a));const x=a.split("?")[0],T=x.lastIndexOf("."),S=o||(T>-1?x.substring(T).toLowerCase():"");let C=null;for(const b of pe._TextureLoaders)if(b.canLoad(S)){C=b;break}const v=(b,A)=>{a===g?r&&b&&r(b.status+" "+b.statusText,A):(O.Warn(`Failed to load ${a}, falling back to the ${g}`),this.createCubeTextureBase(g,e,t,!!i,s,r,n,o,l,h,c,p,d,f,_))};if(C){const b=A=>{d&&d(p,A),C.loadCubeData(A,p,l,s,r)};t&&t.length===6?C.supportCascades?this._cascadeLoadFiles(e,A=>b(A.map(P=>new Uint8Array(P))),t,r):r?r("Textures type does not support cascades."):O.Warn("Texture loader does not support cascades."):this._loadFile(a,A=>b(new Uint8Array(A)),void 0,void 0,!0,v)}else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,p,(b,A)=>{f&&f(b,A)},t,r)}return this._internalTexturesCache.push(p),p};pe.prototype.createCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d,f=!1){const _=this._gl;return this.createCubeTextureBase(a,e,t,!!i,s,r,n,o,l,h,c,u,p=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,p,!0),(p,g)=>{const x=this.needPOTTextures?pe.GetExponentOfTwo(g[0].width,this._caps.maxCubemapTextureSize):g[0].width,T=x,S=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);const C=n?this._getInternalFormat(n,p._useSRGBBuffer):p._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let v=n?this._getInternalFormat(n):_.RGBA;p._useSRGBBuffer&&this.webGLVersion===1&&(v=C);for(let b=0;b<S.length;b++)if(g[b].width!==x||g[b].height!==T){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){O.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=x,this._workingCanvas.height=T,this._workingContext.drawImage(g[b],0,0,g[b].width,g[b].height,0,0,x,T),_.texImage2D(S[b],0,C,v,_.UNSIGNED_BYTE,this._workingCanvas)}else _.texImage2D(S[b],0,C,v,_.UNSIGNED_BYTE,g[b]);i||_.generateMipmap(_.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(p,!i),p.width=x,p.height=T,p.isReady=!0,n&&(p.format=n),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),s&&s()},!!f)};pe.prototype.setTextureSampler=function(a,e){throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!")};const CS=new G,vS=new G;Object.defineProperty(H.prototype,"onBeforeViewRenderObservable",{get:function(){return CS}});Object.defineProperty(H.prototype,"onAfterViewRenderObservable",{get:function(){return vS}});Object.defineProperty(H.prototype,"inputElement",{get:function(){return this._inputElement},set:function(a){var e;this._inputElement!==a&&(this._inputElement=a,(e=this._onEngineViewChanged)==null||e.call(this))}});H.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()};H.prototype.registerView=function(a,e,t){this.views||(this.views=[]);for(const r of this.views)if(r.target===a)return r;const i=this.getRenderingCanvas();i&&(a.width=i.width,a.height=i.height);const s={target:a,camera:e,clearBeforeCopy:t,enabled:!0,id:(Math.random()*1e5).toFixed()};return this.views.push(s),e&&!Array.isArray(e)&&e.onDisposeObservable.add(()=>{this.unRegisterView(a)}),s};H.prototype.unRegisterView=function(a){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===a){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};H.prototype._renderViewStep=function(a){const e=a.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();CS.notifyObservers(a);const s=a.camera;let r=null,n=null,o=null;if(s&&(o=Array.isArray(s)?s[0].getScene():s.getScene(),r=o.activeCamera,n=o.activeCameras,this.activeView=a,Array.isArray(s)?o.activeCameras=s:(o.activeCamera=s,o.activeCameras=null)),a.customResize)a.customResize(e);else{const l=Math.floor(e.clientWidth/this._hardwareScalingLevel),h=Math.floor(e.clientHeight/this._hardwareScalingLevel),c=l!==e.width||i.width!==e.width||h!==e.height||i.height!==e.height;e.clientWidth&&e.clientHeight&&c&&(e.width=l,e.height=h,this.setSize(l,h))}return!i.width||!i.height?!1:(this._renderFrame(),this.flushFramebuffer(),a.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),o&&(o.activeCameras=n,o.activeCamera=r),vS.notifyObservers(a),!0)};H.prototype._renderViews=function(){if(!this.views||this.views.length===0||!this.getRenderingCanvas())return!1;let e;for(const t of this.views){if(!t.enabled)continue;if(t.target===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return e&&!this._renderViewStep(e)?!1:(this.activeView=null,!0)};pe.prototype.createStorageBuffer=function(a,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};pe.prototype.updateStorageBuffer=function(a,e,t,i){};pe.prototype.readFromStorageBuffer=function(a,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};pe.prototype.setStorageBuffer=function(a,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function bI(a){const e=r=>{const n="\\b"+r+"\\b";return a&&(a===r||a.match(new RegExp(n,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return a;const t=a.lastIndexOf("."),i=a.lastIndexOf("?"),s=i>-1?a.substring(i,a.length):"";return(t>-1?a.substring(0,t):a)+this._textureFormatInUse+s}Object.defineProperty(H.prototype,"texturesSupported",{get:function(){const a=[];return this._caps.astc&&a.push("-astc.ktx"),this._caps.s3tc&&a.push("-dxt.ktx"),this._caps.pvrtc&&a.push("-pvrtc.ktx"),this._caps.etc2&&a.push("-etc2.ktx"),this._caps.etc1&&a.push("-etc1.ktx"),a},enumerable:!0,configurable:!0});Object.defineProperty(H.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});H.prototype.setCompressedTextureExclusions=function(a){this._excludedCompressedTextures=a};H.prototype.setTextureFormatToUse=function(a){const e=this.texturesSupported;for(let t=0,i=e.length;t<i;t++)for(let s=0,r=a.length;s<r;s++)if(e[t]===a[s].toLowerCase())return this._transformTextureUrl=bI.bind(this),this._textureFormatInUse=e[t];return this._textureFormatInUse="",this._transformTextureUrl=null,null};class Lo{constructor(){const e=new ArrayBuffer(Lo.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=Lo.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream(()=>{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}Lo.DEFAULT_BUFFER_SIZE=65536;const Pn=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],AI=[()=>1,a=>a.y,a=>a.z,a=>a.x,a=>a.x*a.y,a=>a.y*a.z,a=>3*a.z*a.z-1,a=>a.x*a.z,a=>a.x*a.x-a.y*a.y],Zn=(a,e)=>Pn[a]*AI[a](e),Jn=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class Bo{constructor(){this.preScaled=!1,this.l00=m.Zero(),this.l1_1=m.Zero(),this.l10=m.Zero(),this.l11=m.Zero(),this.l2_2=m.Zero(),this.l2_1=m.Zero(),this.l20=m.Zero(),this.l21=m.Zero(),this.l22=m.Zero()}addLight(e,t,i){U.Vector3[0].set(t.r,t.g,t.b);const s=U.Vector3[0],r=U.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(Zn(0,e),U.Vector3[2]),this.l00.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(1,e),U.Vector3[2]),this.l1_1.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(2,e),U.Vector3[2]),this.l10.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(3,e),U.Vector3[2]),this.l11.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(4,e),U.Vector3[2]),this.l2_2.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(5,e),U.Vector3[2]),this.l2_1.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(6,e),U.Vector3[2]),this.l20.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(7,e),U.Vector3[2]),this.l21.addInPlace(U.Vector3[2]),r.scaleToRef(Zn(8,e),U.Vector3[2]),this.l22.addInPlace(U.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Jn[0]),this.l1_1.scaleInPlace(Jn[1]),this.l10.scaleInPlace(Jn[2]),this.l11.scaleInPlace(Jn[3]),this.l2_2.scaleInPlace(Jn[4]),this.l2_1.scaleInPlace(Jn[5]),this.l20.scaleInPlace(Jn[6]),this.l21.scaleInPlace(Jn[7]),this.l22.scaleInPlace(Jn[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Pn[0]),this.l1_1.scaleInPlace(Pn[1]),this.l10.scaleInPlace(Pn[2]),this.l11.scaleInPlace(Pn[3]),this.l2_2.scaleInPlace(Pn[4]),this.l2_1.scaleInPlace(Pn[5]),this.l20.scaleInPlace(Pn[6]),this.l21.scaleInPlace(Pn[7]),this.l22.scaleInPlace(Pn[8])}updateFromArray(e){return m.FromArrayToRef(e[0],0,this.l00),m.FromArrayToRef(e[1],0,this.l1_1),m.FromArrayToRef(e[2],0,this.l10),m.FromArrayToRef(e[3],0,this.l11),m.FromArrayToRef(e[4],0,this.l2_2),m.FromArrayToRef(e[5],0,this.l2_1),m.FromArrayToRef(e[6],0,this.l20),m.FromArrayToRef(e[7],0,this.l21),m.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return m.FromFloatsToRef(e[0],e[1],e[2],this.l00),m.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),m.FromFloatsToRef(e[6],e[7],e[8],this.l10),m.FromFloatsToRef(e[9],e[10],e[11],this.l11),m.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),m.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),m.FromFloatsToRef(e[18],e[19],e[20],this.l20),m.FromFloatsToRef(e[21],e[22],e[23],this.l21),m.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new Bo().updateFromArray(e)}static FromPolynomial(e){const t=new Bo;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class ma{constructor(){this.x=m.Zero(),this.y=m.Zero(),this.z=m.Zero(),this.xx=m.Zero(),this.yy=m.Zero(),this.zz=m.Zero(),this.xy=m.Zero(),this.yz=m.Zero(),this.zx=m.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Bo.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){U.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=U.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),U.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).addInPlace(U.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).subtractInPlace(U.Vector3[1]),this.zz.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(U.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new ma().updateFromHarmonics(e)}static FromArray(e){const t=new ma;return m.FromArrayToRef(e[0],0,t.x),m.FromArrayToRef(e[1],0,t.y),m.FromArrayToRef(e[2],0,t.z),m.FromArrayToRef(e[3],0,t.xx),m.FromArrayToRef(e[4],0,t.yy),m.FromArrayToRef(e[5],0,t.zz),m.FromArrayToRef(e[6],0,t.yz),m.FromArrayToRef(e[7],0,t.zx),m.FromArrayToRef(e[8],0,t.xy),t}}const yI="rgbdDecodePixelShader",RI=`varying vec2 vUV;uniform sampler2D textureSampler;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;W.ShadersStore[yI]=RI;function II(a,e,t,i=!0){const s=a.getScene(),r=s.getEngine(),n=new oi("resized"+a.name,{width:e,height:t},s,!a.noMipmap,!0,a._texture.type,!1,a.samplingMode,!1);n.wrapU=a.wrapU,n.wrapV=a.wrapV,n.uOffset=a.uOffset,n.vOffset=a.vOffset,n.uScale=a.uScale,n.vScale=a.vScale,n.uAng=a.uAng,n.vAng=a.vAng,n.wAng=a.wAng,n.coordinatesIndex=a.coordinatesIndex,n.level=a.level,n.anisotropicFilteringLevel=a.anisotropicFilteringLevel,n._texture.isReady=!1,a.wrapU=k.CLAMP_ADDRESSMODE,a.wrapV=k.CLAMP_ADDRESSMODE;const o=new An("pass",1,null,i?k.BILINEAR_SAMPLINGMODE:k.NEAREST_SAMPLINGMODE,r,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(h){h.setTexture("textureSampler",a)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([o],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),o.dispose(),n.getInternalTexture().isReady=!0)}),n}function Zm(a,e,t,i,s,r,n,o){const l=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,o=o??e.height,i===-1&&(i=0),new Promise(h=>{const c=new De("postprocess",a,null,null,1,null,s,l,!1,void 0,i,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:n,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:r});c.getEffect().executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,h(e)})})}let Id,Ax;function Ln(a){Id||(Id=new Float32Array(1),Ax=new Int32Array(Id.buffer)),Id[0]=a;const e=Ax[0];let t=e>>16&32768,i=e>>12&2047;const s=e>>23&255;return s<103?t:s>142?(t|=31744,t|=(s==255?0:1)&&e&8388607,t):s<113?(i|=2048,t|=(i>>114-s)+(i>>113-s&1),t):(t|=s-112<<10|i>>1,t+=i&1,t)}function Mn(a){const e=(a&32768)>>15,t=(a&31744)>>10,i=a&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}const PI=async(a,e,t,i,s)=>{const r=a.getScene(),n=r.getEngine();let o;if(!a.isCube)o=new De("lod","lod",["lod","gamma"],null,1,null,k.NEAREST_NEAREST_MIPNEAREST,n);else{const c=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];o=new De("lodCube","lodCube",["lod","gamma"],null,1,null,k.NEAREST_NEAREST_MIPNEAREST,n,!1,c[i])}await new Promise(c=>{o.getEffect().executeWhenCompiled(()=>{c(0)})});const l=new oi("temp",{width:e,height:t},r,!1);o.onApply=function(c){c.setTexture("textureSampler",a),c.setFloat("lod",s),c.setBool("gamma",a.gammaSpace)};const h=a.getInternalTexture();try{if(l.renderTarget&&h){const c=h.samplingMode;s!==0?a.updateSamplingMode(k.NEAREST_NEAREST_MIPNEAREST):a.updateSamplingMode(k.NEAREST_NEAREST),r.postProcessManager.directRender([o],l.renderTarget,!0),a.updateSamplingMode(c);const u=await n.readPixels(0,0,e,t),d=new Uint8Array(u.buffer,0,u.byteLength);return n.unBindFramebuffer(l.renderTarget),d}else throw Error("Render to texture failed.")}finally{l.dispose(),o.dispose()}};async function MI(a,e,t,i=0,s=0){return!a.isReady()&&a._texture&&await new Promise((r,n)=>{if(a._texture===null){n(0);return}a._texture.onLoadedObservable.addOnce(()=>{r(0)})}),await PI(a,e,t,i,s)}const DI={CreateResizedCopy:II,ApplyPostProcess:Zm,ToHalfFloat:Ln,FromHalfFloat:Mn,GetTextureDataAsync:MI};class yx{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const l=new De("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);l.externalTextureSamplerBinding=!0;const h=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});l.getEffect().executeWhenCompiled(()=>{l.onApply=c=>{c._bindTexture("textureSampler",t),c.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([l],h,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),l&&l.dispose(),h._swapAndDie(t),t.isReady=!0})};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return Zm("rgbdEncode",e,t,i,1,5)}}class ol{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class yc{static ConvertCubeMapTextureToSphericalPolynomial(e){var d;if(!e.isCube)return null;(d=e.getScene())==null||d.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,c=5;let u=0;return(e.textureType==1||e.textureType==2)&&(u=1),new Promise(f=>{Promise.all([s,i,r,n,o,l]).then(([_,p,g,x,T,S])=>{const C={size:t,right:p,left:_,up:g,down:x,front:T,back:S,format:c,type:u,gammaSpace:h};f(this.ConvertCubeMapToSphericalPolynomial(C))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Bo;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],_=e[f.name];let p=o;const g=e.format===5?4:3;for(let x=0;x<e.size;x++){let T=o;for(let S=0;S<e.size;S++){const C=f.worldAxisForFileX.scale(T).add(f.worldAxisForFileY.scale(p)).add(f.worldAxisForNormal);C.normalize();const v=this._AreaElement(T-n,p-n)-this._AreaElement(T-n,p+n)-this._AreaElement(T+n,p-n)+this._AreaElement(T+n,p+n);let b=_[x*e.size*g+S*g+0],A=_[x*e.size*g+S*g+1],P=_[x*e.size*g+S*g+2];isNaN(b)&&(b=0),isNaN(A)&&(A=0),isNaN(P)&&(P=0),e.type===0&&(b/=255,A/=255,P/=255),e.gammaSpace&&(b=Math.pow(ge.Clamp(b),Ud),A=Math.pow(ge.Clamp(A),Ud),P=Math.pow(ge.Clamp(P),Ud));const L=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const $=Math.max(b,A,P);if($>L){const J=L/$;b*=J,A*=J,P*=J}}else b=ge.Clamp(b,0,L),A=ge.Clamp(A,0,L),P=ge.Clamp(P,0,L);const w=new q(b,A,P);t.addLight(C,w,v),i+=v,T+=s}p+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),ma.FromHarmonics(t)}}yc._FileFaces=[new ol("right",new m(1,0,0),new m(0,0,-1),new m(0,-1,0)),new ol("left",new m(-1,0,0),new m(0,0,1),new m(0,-1,0)),new ol("up",new m(0,1,0),new m(1,0,0),new m(0,0,1)),new ol("down",new m(0,-1,0),new m(1,0,0),new m(0,0,-1)),new ol("front",new m(0,0,1),new m(1,0,0),new m(0,-1,0)),new ol("back",new m(0,0,-1),new m(-1,0,0),new m(0,-1,0))];yc.MAX_HDRI_VALUE=4096;yc.PRESERVE_CLAMPED_COLORS=!1;Et.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Et.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=yc.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(a=>{this._texture._sphericalPolynomial=a,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(a){this._texture&&(this._texture._sphericalPolynomial=a)},enumerable:!0,configurable:!0});const OI="rgbdEncodePixelShader",NI=`varying vec2 vUV;uniform sampler2D textureSampler;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;W.ShadersStore[OI]=NI;const bS="image/png",Rx=2,Ix=[134,22,135,150,246,214,150,54];function AS(a){const e=new DataView(a.buffer,a.byteOffset,a.byteLength);let t=0;for(let n=0;n<Ix.length;n++)if(e.getUint8(t++)!==Ix[n])return O.Error("Not a babylon environment map"),null;let i="",s=0;for(;s=e.getUint8(t++);)i+=String.fromCharCode(s);let r=JSON.parse(i);return r=jf(r),r.specular&&(r.specular.specularDataPosition=t,r.specular.lodGenerationScale=r.specular.lodGenerationScale||.8),r}function jf(a){if(a.version>Rx)throw new Error(`Unsupported babylon environment map version "${a.version}". Latest supported version is "${Rx}".`);return a.version===2||(a={...a,version:2,imageType:bS}),a}function yS(a,e){e=jf(e);const t=e.specular;let i=ge.Log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);const s=new Array(i);for(let r=0;r<i;r++){s[r]=new Array(6);for(let n=0;n<6;n++){const o=t.mipmaps[r*6+n];s[r][n]=new Uint8Array(a.buffer,a.byteOffset+t.specularDataPosition+o.position,o.length)}}return s}function FI(a,e,t){t=jf(t);const i=t.specular;if(!i)return Promise.resolve();a._lodGenerationScale=i.lodGenerationScale;const s=yS(e,t);return hp(a,s,t.imageType)}function Px(a,e,t,i,s,r,n,o,l,h,c){return new Promise((u,d)=>{if(t){const f=e.createTexture(null,!0,!0,null,1,null,_=>{d(_)},a);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=_=>{_._bindTexture("textureSampler",f),_.setFloat2("scale",1,e._features.needsInvertingBitmap&&a instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],h,!0,r,n),e.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(s),u())})}else{if(e._uploadImageToTexture(c,a,r,n),o){const f=l[n];f&&e._uploadImageToTexture(f._texture,a,r,0)}u()}})}function hp(a,e,t=bS){if(!X.IsExponentOfTwo(a.width))throw new Error("Texture size must be a power of two");const i=ge.ILog2(a.width)+1,s=a.getEngine();let r=!1,n=!1,o=null,l=null,h=null;const c=s.getCaps();if(a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,a),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,a.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,a.type=1):r=!1:(r=!1,n=!0,h={}),r)o=new De("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,a.type,void 0,null,!1),a._isRGBD=!1,a.invertY=!1,l=s.createRenderTargetCubeTexture(a.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:a.type,format:5});else if(a._isRGBD=!0,a.invertY=!0,n){const f=a._lodGenerationScale,_=a._lodGenerationOffset;for(let p=0;p<3;p++){const x=1-p/2,T=_,S=(i-1)*f+_,C=T+(S-T)*x,v=Math.round(Math.min(Math.max(C,0),S)),b=new Tt(s,et.Temp);b.isCube=!0,b.invertY=!0,b.generateMipMaps=!1,s.updateTextureSamplingMode(2,b);const A=new Et(null);switch(A._isCube=!0,A._texture=b,h[v]=A,p){case 0:a._lodTextureLow=A;break;case 1:a._lodTextureMid=A;break;case 2:a._lodTextureHigh=A;break}}}const u=[];for(let d=0;d<e.length;d++)for(let f=0;f<6;f++){const _=e[d][f],p=new Blob([_],{type:t}),g=URL.createObjectURL(p);let x;if(s._features.forceBitmapOverHTMLImageElement)x=s.createImageBitmap(p,{premultiplyAlpha:"none"}).then(T=>Px(T,s,r,o,g,f,d,n,h,l,a));else{const T=new Image;T.src=g,x=new Promise((S,C)=>{T.onload=()=>{Px(T,s,r,o,g,f,d,n,h,l,a).then(()=>S()).catch(v=>{C(v)})},T.onerror=v=>{C(v)}})}u.push(x)}if(e.length<i){let d;const f=Math.pow(2,i-1-e.length),_=f*f*4;switch(a.type){case 0:{d=new Uint8Array(_);break}case 2:{d=new Uint16Array(_);break}case 1:{d=new Float32Array(_);break}}for(let p=e.length;p<i;p++)for(let g=0;g<6;g++)s._uploadArrayBufferViewToTexture(a,d,g,p)}return Promise.all(u).then(()=>{l&&(s._releaseTexture(a),l._swapAndDie(a)),o&&o.dispose(),n&&(a._lodTextureHigh&&a._lodTextureHigh._texture&&(a._lodTextureHigh._texture.isReady=!0),a._lodTextureMid&&a._lodTextureMid._texture&&(a._lodTextureMid._texture.isReady=!0),a._lodTextureLow&&a._lodTextureLow._texture&&(a._lodTextureLow._texture.isReady=!0))})}function RS(a,e){e=jf(e);const t=e.irradiance;if(!t)return;const i=new ma;m.FromArrayToRef(t.x,0,i.x),m.FromArrayToRef(t.y,0,i.y),m.FromArrayToRef(t.z,0,i.z),m.FromArrayToRef(t.xx,0,i.xx),m.FromArrayToRef(t.yy,0,i.yy),m.FromArrayToRef(t.zz,0,i.zz),m.FromArrayToRef(t.yz,0,i.yz),m.FromArrayToRef(t.zx,0,i.zx),m.FromArrayToRef(t.xy,0,i.xy),a._sphericalPolynomial=i}function wI(a,e,t,i,s){const r=a.getEngine().createRawCubeTexture(null,a.width,a.format,a.type,a.generateMipMaps,a.invertY,a.samplingMode,a._compression),n=hp(r,e).then(()=>a);return a.onRebuildCallback=o=>({proxy:n,isReady:!0,isAsync:!0}),a._source=et.CubeRawRGBD,a._bufferViewArrayArray=e,a._lodGenerationScale=i,a._lodGenerationOffset=s,a._sphericalPolynomial=t,hp(a,e).then(()=>(a.isReady=!0,a))}function Pd(a,e,t,i){let s=i,r=0,n="";for(;s<t.length;){const o=t.charAt(s);if(n)o===n?n==='"'||n==="'"?t.charAt(s-1)!=="\\"&&(n=""):n="":n==="*/"&&o==="*"&&s+1<t.length&&(t.charAt(s+1)==="/"&&(n=""),n===""&&s++);else switch(o){case a:r++;break;case e:r--;break;case'"':case"'":case"`":n=o;break;case"/":if(s+1<t.length){const l=t.charAt(s+1);l==="/"?n=`
`:l==="*"&&(n="*/")}break}if(s++,r===0)break}return r===0?s-1:-1}function Mx(a,e){for(;e<a.length;){const t=a[e];if(t!==" "&&t!==`
`&&t!=="\r"&&t!=="	"&&t!==`
`&&t!==" ")break;e++}return e}function w_(a){const e=a.charCodeAt(0);return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function cp(a){let e=0,t="",i=!1;const s=[];for(;e<a.length;){const r=a.charAt(e);if(t)r===t?t==='"'||t==="'"?(a.charAt(e-1)!=="\\"&&(t=""),s.push(r)):(t="",i=!1):t==="*/"&&r==="*"&&e+1<a.length?(a.charAt(e+1)==="/"&&(t=""),t===""&&(i=!1,e++)):i||s.push(r);else{switch(r){case'"':case"'":case"`":t=r;break;case"/":if(e+1<a.length){const n=a.charAt(e+1);n==="/"?(t=`
`,i=!0):n==="*"&&(t="*/",i=!0)}break}i||s.push(r)}e++}return s.join("")}function LI(a,e,t,i){for(;e>=0&&a.charAt(e)!==t&&(!i||a.charAt(e)!==i);)e--;return e}function BI(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class Do{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&O.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&O.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e<this._sourceCode.length;){const t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;const i=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(i<0){this.debug&&O.Warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}const s=Do._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,i));if(!s){this.debug&&O.Warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,i)}`),e=t+this.inlineToken.length;continue}const[r,n]=[s[3],s[4]],o=Pd("(",")",this._sourceCode,i);if(o<0){this.debug&&O.Warn(`Could not extract the parameters the function '${n}' (type=${r}). funcParamsStartIndex=${i}`),e=t+this.inlineToken.length;continue}const l=this._sourceCode.substring(i+1,o),h=Mx(this._sourceCode,o+1);if(h===this._sourceCode.length){this.debug&&O.Warn(`Could not extract the body of the function '${n}' (type=${r}). funcParamsEndIndex=${o}`),e=t+this.inlineToken.length;continue}const c=Pd("{","}",this._sourceCode,h);if(c<0){this.debug&&O.Warn(`Could not extract the body of the function '${n}' (type=${r}). funcBodyStartIndex=${h}`),e=t+this.inlineToken.length;continue}const u=this._sourceCode.substring(h,c+1),d=cp(l).split(","),f=[];for(let g=0;g<d.length;++g){const x=d[g].trim(),T=x.lastIndexOf(" ");T>=0&&f.push(x.substring(T+1))}r!=="void"&&f.push("return"),this._functionDescr.push({name:n,type:r,parameters:f,body:u,callIndex:0}),e=c+1;const _=t>0?this._sourceCode.substring(0,t):"",p=c+1<this._sourceCode.length-1?this._sourceCode.substring(c+1):"";this._sourceCode=_+p,e-=c+1-t}this.debug&&O.Log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=${this._functionDescr}`)}_processInlining(e=20){for(;e-->=0&&this._replaceFunctionCallsByCode(););return this.debug&&O.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o<this._sourceCode.length;){const l=this._sourceCode.indexOf(i,o);if(l<0)break;if(l===0||w_(this._sourceCode.charAt(l-1))){o=l+i.length;continue}const h=Mx(this._sourceCode,l+i.length);if(h===this._sourceCode.length||this._sourceCode.charAt(h)!=="("){o=l+i.length;continue}const c=Pd("(",")",this._sourceCode,h);if(c<0){this.debug&&O.Warn(`Could not extract the parameters of the function call. Function '${i}' (type=${s}). callParamsStartIndex=${h}`),o=l+i.length;continue}const u=this._sourceCode.substring(h+1,c),f=(S=>{const C=[];let v=0,b=0;for(;v<S.length;){if(S.charAt(v)==="("){const A=Pd("(",")",S,v);if(A<0)return null;v=A}else S.charAt(v)===","&&(C.push(S.substring(b,v)),b=v+1);v++}return b<v&&C.push(S.substring(b,v)),C})(cp(u));if(f===null){this.debug&&O.Warn(`Invalid function call: can't extract the parameters of the function call. Function '${i}' (type=${s}). callParamsStartIndex=${h}, callParams=`+u),o=l+i.length;continue}const _=[];for(let S=0;S<f.length;++S){const C=f[S].trim();_.push(C)}const p=s!=="void"?i+"_"+t.callIndex++:null;if(p&&_.push(p+" ="),_.length!==r.length){this.debug&&O.Warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${i}' (type=${s}). function parameters=${r}, call parameters=${_}`),o=l+i.length;continue}o=c+1;const g=this._replaceNames(n,r,_);let x=l>0?this._sourceCode.substring(0,l):"";const T=c+1<this._sourceCode.length-1?this._sourceCode.substring(c+1):"";if(p){const S=LI(this._sourceCode,l-1,`
`,"{");x=this._sourceCode.substring(0,S+1);const C=this._sourceCode.substring(S+1,l);this._sourceCode=x+s+" "+p+`;
`+g+`
`+C+p+T,this.debug&&O.Log(`Replace function call by code. Function '${i}' (type=${s}). injectDeclarationIndex=${S}, call parameters=${_}`)}else this._sourceCode=x+g+T,o+=g.length-(c+1-l),this.debug&&O.Log(`Replace function call by code. Function '${i}' (type=${s}). functionCallIndex=${l}, call parameters=${_}`);e=!0}}return e}_replaceNames(e,t,i){for(let s=0;s<t.length;++s){const r=new RegExp(BI(t[s]),"g"),n=t[s].length,o=i[s];e=e.replace(r,(l,...h)=>{const c=h[0];return w_(e.charAt(c-1))||w_(e.charAt(c+n))?t[s]:o})}return e}}Do._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class UI{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+(typeof e=="string"?`
`+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}_fillEffectInformation(e,t,i,s,r,n,o,l){const h=this._engine;if(h.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this._engine.getUniforms(this,i).forEach((d,f)=>{s[i[f]]=d}),this._uniforms=s;let u;for(u=0;u<r.length;u++)e.getUniform(r[u])==null&&(r.splice(u,1),u--);r.forEach((d,f)=>{n[d]=f}),l.push(...h.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class VI extends Pm{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class Dx{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function L_(a,e){switch(a){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:return _native.Engine.TEXTURE_FORMAT_BC1;case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break}case 5:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break}case 6:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break}case 7:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break}case 12:{switch(e){case 0:return _native.Engine.TEXTURE_FORMAT_BGRA8}break}}throw new Sn(`Unsupported texture format or type: format ${a}, type ${e}.`,ca.UnsupportedTextureError)}function zc(a){switch(a){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${a}.`)}}function B_(a){switch(a){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+a+".")}}function kI(a){switch(a){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${a}.`)}}function GI(a){switch(a){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${a}.`)}}function zI(a){switch(a){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${a}.`)}}function WI(a){switch(a){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${a}.`)}}function HI(a){switch(a){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${a}.`)}}function XI(a){switch(a){case y.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case y.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case y.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case y.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case y.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${a}.`)}}const IS=new G;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let a;Object.defineProperty(self,"_native",{get:()=>a,set:e=>{a=e,a&&IS.notifyObservers(a)}})}function YI(){return new Promise(a=>{typeof _native>"u"?IS.addOnce(e=>a(e)):a(_native)})}async function $I(a,e){(await YI())[a]=e}class Ox extends ko{}class KI{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=Wl._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class Wl extends H{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new KI(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==Wl.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${Wl.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback(()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()}),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},X.Log("Babylon Native (v"+H.Version+") launched"),X.LoadScript=function(s,r,n,o){X.LoadFile(s,l=>{Function(l).apply(null),r&&r()},void 0,void 0,!1,(l,h)=>{n&&n("LoadScript Error",h)})},typeof URL>"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(s){return s}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function s(){const r=isNaN(arguments[0])?1:Number(arguments[0]);return r?Array.prototype.reduce.call(this,function(n,o){return Array.isArray(o)?n.push.apply(n,s.call(o,r-1)):n.push(o),n},[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new vE,this.onNewSceneAddedObservable.add(s=>{const r=s.render;s.render=(...n)=>{this._commandBufferEncoder.beginCommandScope(),r.apply(s,n),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new Lo}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new Ox;return r.references=1,r.is32Bits=s.BYTES_PER_ELEMENT===4,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new Ox;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let o=0;o<n.length;o++){const l=s.getAttributeLocation(o);if(l>=0){const h=n[o];let c=null;if(r&&(c=r[h]),c||(c=t[h]),c){const u=c.getBuffer();u&&u.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,u.nativeVertexBuffer,l,c.byteOffset,c.byteStride,c.getSize(),XI(c.type),c.normalized,c.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.program,t)}drawElementsType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){const e=!!(this._caps.parallelShaderCompile&&this._engine.createProgramAsync);return new UI(this,e)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,o,l){s?this.createRawShaderProgram():this.createShaderProgram(e,t,i,l)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(i.isAsync)if(i.onCompiled){const s=i.onCompiled;i.onCompiled=()=>{s(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Do(t);n.processCode(),t=n.code;const o=new Do(i);o.processCode(),i=o.code,t=pe._ConcatenateShader(t,s),i=pe._ConcatenateShader(i,s);const l=()=>{var h;r.isCompiled=!0,(h=r.onCompiled)==null||h.call(r),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,l,h=>{r.compilationError=h});else try{r.program=this._engine.createProgram(t,i),l()}catch(h){const c=h==null?void 0:h.message;throw new Error("SHADER ERROR"+(typeof c=="string"?`
`+c:""))}return r.program}inlineShaderCode(e){const t=new Do(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}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}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()}setViewport(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()}enableScissor(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand()}disableScissor(){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.finishEncodingCommand()}setState(e,t=0,i,s=!1,r,n,o=0){this._zOffset=t,this._zOffsetUnits=o,this._zOffset!==0&&X.Warn("zOffset is not supported in Native engine."),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(o),this._commandBufferEncoder.encodeCommandArgAsUInt32(this.cullBackFaces??r??!0?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.finishEncodingCommand()}getInputElementClientRect(){return{bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:()=>{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL;break}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,GI(this._stencilOpStencilFail),zI(this._stencilOpDepthFail),WI(this._stencilOpStencilDepthPass),kI(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=HI(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(e===0),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setIntArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloatArray4(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setArray(e,t){return e?this.setFloatArray(e,new Float32Array(t)):!1}setArray2(e,t){return e?this.setFloatArray2(e,new Float32Array(t)):!1}setArray3(e,t){return e?this.setFloatArray3(e,new Float32Array(t)):!1}setArray4(e,t){return e?this.setFloatArray4(e,new Float32Array(t)):!1}setMatrices(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix3x3(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setMatrix2x2(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat(e,t){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat2(e,t,i){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat3(e,t,i,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,s,r){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setColor3(e,t){return e?(this.setFloat3(e,t.r,t.g,t.b),!0):!1}setColor4(e,t,i){return e?(this.setFloat4(e,t.r,t.g,t.b,i),!0):!1}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(s===void 0&&(s=!1),e&&e._hardwareTexture){const n=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,n),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,l=null,h=0,c=0,u=!1){const d=new Tt(this,et.Raw);if(d.format=s,d.generateMipMaps=r,d.samplingMode=o,d.invertY=n,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=l,d.type=h,d._useSRGBBuffer=this._getUseSRGBBuffer(u,!r),this.updateRawTexture(d,e,s,n,l,h,d._useSRGBBuffer),d._hardwareTexture){const f=d._hardwareTexture.underlyingResource,_=zc(o);this._setTextureSampling(f,_)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,s,r,n,o,l,h=null,c=0){const u=new Tt(this,et.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=s,u.width=t,u.height=i,u.depth=s,u.format=r,u.type=c,u.generateMipMaps=n,u.samplingMode=l,u.is2DArray=!0,u._hardwareTexture){const d=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(d,e,t,i,s,L_(r,c),n,o);const f=zc(l);this._setTextureSampling(d,f)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,L_(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,_,p=!1){e=e||"";const g=e.substr(0,5)==="data:",x=g&&e.indexOf(";base64,")!==-1,T=h||new Tt(this,et.Url),S=e;this._transformTextureUrl&&!x&&!h&&!l&&(e=this._transformTextureUrl(e));const C=e.lastIndexOf("."),v=u||(C>-1?e.substring(C).toLowerCase():"");let b=null;for(const L of H._TextureLoaders)if(L.canLoad(v)){b=L;break}s&&s.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=r,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(T._buffer=l);let A=null;n&&!h&&(A=T.onLoadedObservable.add(n)),h||this._internalTexturesCache.push(T);const P=(L,w)=>{s&&s.removePendingData(T),e===S?(A&&T.onLoadedObservable.remove(A),Ae.UseFallbackTexture&&this.createTexture(Ae.FallbackTexture,t,T.invertY,s,r,null,o,l,T),o&&o((L||"Unknown error")+(Ae.UseFallbackTexture?" - Fallback texture was used":""),w)):(O.Warn(`Failed to load ${e}, falling back to ${S}`),this.createTexture(S,t,T.invertY,s,r,n,o,l,T,c,u,d,f))};if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const L=w=>{if(!T._hardwareTexture){s&&s.removePendingData(T);return}const $=T._hardwareTexture.underlyingResource;this._engine.loadTexture($,w,!t,i,T._useSRGBBuffer,()=>{T.baseWidth=this._engine.getTextureWidth($),T.baseHeight=this._engine.getTextureHeight($),T.width=T.baseWidth,T.height=T.baseHeight,T.isReady=!0;const J=zc(r);this._setTextureSampling($,J),s&&s.removePendingData(T),T.onLoadedObservable.notifyObservers(T),T.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(g&&l)if(l instanceof ArrayBuffer)L(new Uint8Array(l));else if(ArrayBuffer.isView(l))L(l);else if(typeof l=="string")L(new Uint8Array(X.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else x?L(new Uint8Array(X.DecodeBase64(e))):this._loadFile(e,w=>L(new Uint8Array(w)),void 0,void 0,!0,(w,$)=>{P("Unable to load "+(w&&w.responseURL,$))})}return T}wrapNativeTexture(e,t=!1,i=3){const s=new Dx(e,this._engine),r=new Tt(this,et.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new Tt(this,et.DepthStencil),l=e.width??e,h=e.height??e,c=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,s,!0,r);return n._framebufferDepthStencil=c,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=this.createCanvasImage();n.onload=()=>{try{const o=this._engine.createImageBitmap(n);s(o)}catch(o){r(`Error loading image ${n.src} with exception: ${o}`)}},n.onerror=o=>{r(`Error loading image ${n.src} with exception: ${o}`)},n.src=e})}createImageBitmap(e,t){return new Promise((i,s)=>{if(Array.isArray(e)){const r=e;if(r.length){const n=this._engine.createImageBitmap(r[0]);if(n){i(n);return}}}s("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,l=null,h=!1,c=0,u=0,d=null,f,_=!1){const p=d||new Tt(this,et.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=c,p._lodGenerationOffset=u,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(p._extension=l,p._files=i);const g=e.lastIndexOf(".");if((l||(g>-1?e.substring(g).toLowerCase():""))===".env"){const T=S=>{const C=AS(S);p.width=C.width,p.height=C.width,RS(p,C);const v=C.specular;if(!v)throw new Error("Nothing else parsed so far");p._lodGenerationScale=v.lodGenerationScale;const b=yS(S,C);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(k.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,b,!1,p._useSRGBBuffer,()=>{p.isReady=!0,r&&r()},()=>{throw new Error("Could not load a native cube texture.")})};if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");{const S=(C,v)=>{n&&C&&n(C.status+" "+C.statusText,v)};this._loadFile(e,C=>{T(new Uint8Array(C,0,C.byteLength))},void 0,void 0,!0,S)}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const T=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(T.map(S=>this._loadFileAsync(S,void 0,!0).then(C=>new Uint8Array(C,0,C.byteLength)))).then(S=>new Promise((C,v)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,S,!s,!0,p._useSRGBBuffer,C,v)})).then(()=>{p.isReady=!0,r&&r()},S=>{n&&n(`Failed to load cubemap: ${S.message}`,S)})}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new Dx(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new VI(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=et.Unknown){let r=!1,n=0,o=3,l=5,h=!1,c=1,u;t!==void 0&&typeof t=="object"?(r=!!t.generateMipMaps,n=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,l=t.format===void 0?5:t.format,h=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,c=t.samples??1,u=t.label):r=!!t,h=this._getUseSRGBBuffer(h,!r),(n===1&&!this._caps.textureFloatLinearFiltering||n===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),n===1&&!this._caps.textureFloat&&(n=0,O.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new Tt(this,s),f=e.width??e,_=e.height??e,p=e.layers||0;if(p!==0)throw new Error("Texture layers are not supported in Babylon Native");const g=d._hardwareTexture.underlyingResource,x=L_(l,n);return this._engine.initializeTexture(g,f,_,r,x,!0,h,c),this._setTextureSampling(g,zc(o)),d._useSRGBBuffer=h,d.baseWidth=f,d.baseHeight=_,d.width=f,d.height=_,d.depth=p,d.isReady=!0,d.samples=c,d.generateMipMaps=r,d.samplingMode=o,d.type=n,d.format=l,d.label=u,this._internalTexturesCache.push(d),d}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s=!0,r=!1,n=!1,o,l=1;t!==void 0&&typeof t=="object"&&(s=t.generateDepthBuffer??!0,r=!!t.generateStencilBuffer,n=!!t.noColorAttachment,o=t.colorAttachment,l=t.samples??1);const h=o||(n?null:this._createInternalTexture(e,t,!0,et.RenderTarget)),c=e.width??e,u=e.height??e,d=this._engine.createFrameBuffer(h?h._hardwareTexture.underlyingResource:null,c,u,r,s,l);return i._framebuffer=d,i._generateDepthBuffer=s,i._generateStencilBuffer=r,i._samples=l,i.setTextures(h),i}updateRenderTargetTextureSampleCount(e,t){return O.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=zc(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=r.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;return 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,this._activeChannel=e,!n||!n._hardwareTexture?!1:(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,B_(t.wrapU),B_(t.wrapV),B_(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(r,n._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;!t||!t._hardwareTexture||t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const s=t._hardwareTexture.underlyingResource;this._setTextureCore(i,s)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,l=0,h=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,l,h,c){var u;if(s!==void 0&&s!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture((u=e._hardwareTexture)==null?void 0:u.underlyingResource,r??0,h??0,c??0,t,i,(n==null?void 0:n.buffer)??null,(n==null?void 0:n.byteOffset)??0,(n==null?void 0:n.byteLength)??0).then(d=>(n||(n=new Uint8Array(d)),n))}}Wl.PROTOCOL_VERSION=8;Wl._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new jI:new Lo};class jI extends Lo{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var Nx;(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(Nx||(Nx={}));var Fn;(function(a){a.DepthClipControl="depth-clip-control",a.Depth32FloatStencil8="depth32float-stencil8",a.TextureCompressionBC="texture-compression-bc",a.TextureCompressionETC2="texture-compression-etc2",a.TextureCompressionASTC="texture-compression-astc",a.TimestampQuery="timestamp-query",a.IndirectFirstInstance="indirect-first-instance",a.ShaderF16="shader-f16",a.RG11B10UFloatRenderable="rg11b10ufloat-renderable",a.BGRA8UnormStorage="bgra8unorm-storage",a.Float32Filterable="float32-filterable"})(Fn||(Fn={}));var Fx;(function(a){a.Unmapped="unmapped",a.Pending="pending",a.Mapped="mapped"})(Fx||(Fx={}));var kt;(function(a){a[a.MapRead=1]="MapRead",a[a.MapWrite=2]="MapWrite",a[a.CopySrc=4]="CopySrc",a[a.CopyDst=8]="CopyDst",a[a.Index=16]="Index",a[a.Vertex=32]="Vertex",a[a.Uniform=64]="Uniform",a[a.Storage=128]="Storage",a[a.Indirect=256]="Indirect",a[a.QueryResolve=512]="QueryResolve"})(kt||(kt={}));var Oo;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(Oo||(Oo={}));var tn;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(tn||(tn={}));var ri;(function(a){a[a.CopySrc=1]="CopySrc",a[a.CopyDst=2]="CopyDst",a[a.TextureBinding=4]="TextureBinding",a[a.StorageBinding=8]="StorageBinding",a[a.RenderAttachment=16]="RenderAttachment"})(ri||(ri={}));var Dt;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})(Dt||(Dt={}));var gn;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})(gn||(gn={}));var N;(function(a){a.R8Unorm="r8unorm",a.R8Snorm="r8snorm",a.R8Uint="r8uint",a.R8Sint="r8sint",a.R16Uint="r16uint",a.R16Sint="r16sint",a.R16Float="r16float",a.RG8Unorm="rg8unorm",a.RG8Snorm="rg8snorm",a.RG8Uint="rg8uint",a.RG8Sint="rg8sint",a.R32Uint="r32uint",a.R32Sint="r32sint",a.R32Float="r32float",a.RG16Uint="rg16uint",a.RG16Sint="rg16sint",a.RG16Float="rg16float",a.RGBA8Unorm="rgba8unorm",a.RGBA8UnormSRGB="rgba8unorm-srgb",a.RGBA8Snorm="rgba8snorm",a.RGBA8Uint="rgba8uint",a.RGBA8Sint="rgba8sint",a.BGRA8Unorm="bgra8unorm",a.BGRA8UnormSRGB="bgra8unorm-srgb",a.RGB9E5UFloat="rgb9e5ufloat",a.RGB10A2UINT="rgb10a2uint",a.RGB10A2Unorm="rgb10a2unorm",a.RG11B10UFloat="rg11b10ufloat",a.RG32Uint="rg32uint",a.RG32Sint="rg32sint",a.RG32Float="rg32float",a.RGBA16Uint="rgba16uint",a.RGBA16Sint="rgba16sint",a.RGBA16Float="rgba16float",a.RGBA32Uint="rgba32uint",a.RGBA32Sint="rgba32sint",a.RGBA32Float="rgba32float",a.Stencil8="stencil8",a.Depth16Unorm="depth16unorm",a.Depth24Plus="depth24plus",a.Depth24PlusStencil8="depth24plus-stencil8",a.Depth32Float="depth32float",a.BC1RGBAUnorm="bc1-rgba-unorm",a.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",a.BC2RGBAUnorm="bc2-rgba-unorm",a.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",a.BC3RGBAUnorm="bc3-rgba-unorm",a.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",a.BC4RUnorm="bc4-r-unorm",a.BC4RSnorm="bc4-r-snorm",a.BC5RGUnorm="bc5-rg-unorm",a.BC5RGSnorm="bc5-rg-snorm",a.BC6HRGBUFloat="bc6h-rgb-ufloat",a.BC6HRGBFloat="bc6h-rgb-float",a.BC7RGBAUnorm="bc7-rgba-unorm",a.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",a.ETC2RGB8Unorm="etc2-rgb8unorm",a.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",a.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",a.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",a.ETC2RGBA8Unorm="etc2-rgba8unorm",a.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",a.EACR11Unorm="eac-r11unorm",a.EACR11Snorm="eac-r11snorm",a.EACRG11Unorm="eac-rg11unorm",a.EACRG11Snorm="eac-rg11snorm",a.ASTC4x4Unorm="astc-4x4-unorm",a.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",a.ASTC5x4Unorm="astc-5x4-unorm",a.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",a.ASTC5x5Unorm="astc-5x5-unorm",a.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",a.ASTC6x5Unorm="astc-6x5-unorm",a.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",a.ASTC6x6Unorm="astc-6x6-unorm",a.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",a.ASTC8x5Unorm="astc-8x5-unorm",a.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",a.ASTC8x6Unorm="astc-8x6-unorm",a.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",a.ASTC8x8Unorm="astc-8x8-unorm",a.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",a.ASTC10x5Unorm="astc-10x5-unorm",a.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",a.ASTC10x6Unorm="astc-10x6-unorm",a.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",a.ASTC10x8Unorm="astc-10x8-unorm",a.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",a.ASTC10x10Unorm="astc-10x10-unorm",a.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",a.ASTC12x10Unorm="astc-12x10-unorm",a.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",a.ASTC12x12Unorm="astc-12x12-unorm",a.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",a.Depth32FloatStencil8="depth32float-stencil8"})(N||(N={}));var ml;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(ml||(ml={}));var ct;(function(a){a.Nearest="nearest",a.Linear="linear"})(ct||(ct={}));var wx;(function(a){a.Nearest="nearest",a.Linear="linear"})(wx||(wx={}));var ms;(function(a){a.Never="never",a.Less="less",a.Equal="equal",a.LessEqual="less-equal",a.Greater="greater",a.NotEqual="not-equal",a.GreaterEqual="greater-equal",a.Always="always"})(ms||(ms={}));var Da;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(Da||(Da={}));var Wa;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(Wa||(Wa={}));var io;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(io||(io={}));var br;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(br||(br={}));var up;(function(a){a.WriteOnly="write-only",a.ReadOnly="read-only",a.ReadWrite="read-write"})(up||(up={}));var Lx;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(Lx||(Lx={}));var Bx;(function(a){a.Validation="validation",a.Internal="internal"})(Bx||(Bx={}));var Ru;(function(a){a.Auto="auto"})(Ru||(Ru={}));var Tr;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(Tr||(Tr={}));var sf;(function(a){a.CCW="ccw",a.CW="cw"})(sf||(sf={}));var Jc;(function(a){a.None="none",a.Front="front",a.Back="back"})(Jc||(Jc={}));var Ux;(function(a){a[a.Red=1]="Red",a[a.Green=2]="Green",a[a.Blue=4]="Blue",a[a.Alpha=8]="Alpha",a[a.All=15]="All"})(Ux||(Ux={}));var Ns;(function(a){a.Zero="zero",a.One="one",a.Src="src",a.OneMinusSrc="one-minus-src",a.SrcAlpha="src-alpha",a.OneMinusSrcAlpha="one-minus-src-alpha",a.Dst="dst",a.OneMinusDst="one-minus-dst",a.DstAlpha="dst-alpha",a.OneMinusDstAlpha="one-minus-dst-alpha",a.SrcAlphaSaturated="src-alpha-saturated",a.Constant="constant",a.OneMinusConstant="one-minus-constant"})(Ns||(Ns={}));var Oa;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(Oa||(Oa={}));var hn;(function(a){a.Keep="keep",a.Zero="zero",a.Replace="replace",a.Invert="invert",a.IncrementClamp="increment-clamp",a.DecrementClamp="decrement-clamp",a.IncrementWrap="increment-wrap",a.DecrementWrap="decrement-wrap"})(hn||(hn={}));var so;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(so||(so={}));var ci;(function(a){a.Uint8x2="uint8x2",a.Uint8x4="uint8x4",a.Sint8x2="sint8x2",a.Sint8x4="sint8x4",a.Unorm8x2="unorm8x2",a.Unorm8x4="unorm8x4",a.Snorm8x2="snorm8x2",a.Snorm8x4="snorm8x4",a.Uint16x2="uint16x2",a.Uint16x4="uint16x4",a.Sint16x2="sint16x2",a.Sint16x4="sint16x4",a.Unorm16x2="unorm16x2",a.Unorm16x4="unorm16x4",a.Snorm16x2="snorm16x2",a.Snorm16x4="snorm16x4",a.Float16x2="float16x2",a.Float16x4="float16x4",a.Float32="float32",a.Float32x2="float32x2",a.Float32x3="float32x3",a.Float32x4="float32x4",a.Uint32="uint32",a.Uint32x2="uint32x2",a.Uint32x3="uint32x3",a.Uint32x4="uint32x4",a.Sint32="sint32",a.Sint32x2="sint32x2",a.Sint32x3="sint32x3",a.Sint32x4="sint32x4",a.UNORM10x10x10x2="unorm10-10-10-2"})(ci||(ci={}));var rf;(function(a){a.Vertex="vertex",a.Instance="instance"})(rf||(rf={}));var Vx;(function(a){a.Beginning="beginning",a.End="end"})(Vx||(Vx={}));var kx;(function(a){a.Beginning="beginning",a.End="end"})(kx||(kx={}));var Ki;(function(a){a.Load="load",a.Clear="clear"})(Ki||(Ki={}));var Mr;(function(a){a.Store="store",a.Discard="discard"})(Mr||(Mr={}));var nf;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(nf||(nf={}));var af;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(af||(af={}));var Gx;(function(a){a.Unknown="unknown",a.Destroyed="destroyed"})(Gx||(Gx={}));var zx;(function(a){a.Validation="validation",a.OutOfMemory="out-of-memory",a.Internal="internal"})(zx||(zx={}));class ai{constructor(){this.shaderLanguage=Zt.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let r=0;r<this._webgpuProcessingContext.leftOverUniforms.length;r++)if(this._webgpuProcessingContext.leftOverUniforms[r].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:s})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";const e=ai.LeftOvertUBOName;let t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,Wa.Uniform,!0),this._addBufferBindingDescription(e,t,Wa.Uniform,!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(t===void 0){this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[];continue}for(let i=0;i<t.length;i++){const s=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][s.binding].name,n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][s.binding].nameInArrayOfTexture;s&&(s.texture||s.externalTexture||s.storageTexture?this._webgpuProcessingContext.textureNames.push(n):s.sampler?this._webgpuProcessingContext.samplerNames.push(r):s.buffer&&this._webgpuProcessingContext.bufferNames.push(r))}}}_preCreateBindGroupEntries(){const e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){const i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],s=[];for(let r=0;r<i.length;r++){const n=this._webgpuProcessingContext.bindGroupLayoutEntries[t][r];n.sampler||n.texture||n.storageTexture||n.externalTexture?s.push({binding:n.binding,resource:void 0}):n.buffer&&s.push({binding:n.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=s}}_addTextureBindingDescription(e,t,i,s,r,n){let{groupIndex:o,bindingIndex:l}=t.textures[i];if(this._webgpuProcessingContext.bindGroupLayoutEntries[o]||(this._webgpuProcessingContext.bindGroupLayoutEntries[o]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][l]){let h;s===null?h=this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:l,visibility:0,externalTexture:{}}):r?h=this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:l,visibility:0,storageTexture:{access:up.WriteOnly,format:r,viewDimension:s}}):h=this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:l,visibility:0,texture:{sampleType:t.sampleType,viewDimension:s,multisampled:!1}});const c=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][l]={name:e,index:h-1,nameInArrayOfTexture:c}}l=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][l].index,n?this._webgpuProcessingContext.bindGroupLayoutEntries[o][l].visibility|=Da.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[o][l].visibility|=Da.Fragment}_addSamplerBindingDescription(e,t,i){let{groupIndex:s,bindingIndex:r}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r]){const n=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:r,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r]={name:e,index:n-1}}r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][r].index,i?this._webgpuProcessingContext.bindGroupLayoutEntries[s][r].visibility|=Da.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[s][r].visibility|=Da.Fragment}_addBufferBindingDescription(e,t,i,s){let{groupIndex:r,bindingIndex:n}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[r]||(this._webgpuProcessingContext.bindGroupLayoutEntries[r]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][n]){const o=this._webgpuProcessingContext.bindGroupLayoutEntries[r].push({binding:n,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][n]={name:e,index:o-1}}n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][n].index,s?this._webgpuProcessingContext.bindGroupLayoutEntries[r][n].visibility|=Da.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[r][n].visibility|=Da.Fragment}_injectStartingAndEndingCode(e,t,i,s){let r=e.indexOf(t);if(r<0)return O.Error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;r++<e.length&&e.charAt(r)!="{";);if(r<e.length){const n=e.substring(0,r+1),o=e.substring(r+1);e=n+i+o}}if(s){const n=e.lastIndexOf("}");e=e.substring(0,n),e+=s+`
}`}return e}}ai.AutoSamplerSuffix="Sampler";ai.LeftOvertUBOName="LeftOver";ai.InternalsUBOName="Internals";ai.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16};ai._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"};ai._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"};ai._GpuTextureViewDimensionByWebGPUTextureType={textureCube:Dt.Cube,textureCubeArray:Dt.CubeArray,texture2D:Dt.E2d,texture2DArray:Dt.E2dArray,texture3D:Dt.E3d};ai._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"};ai._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};class qI{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t,this.vertexBufferKindToType={}}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,i,s,r,n,o,l){const h=this.engine;h._doNotHandleContextLost&&(e._fragmentSourceCode="",e._vertexSourceCode="");const c=this.shaderProcessingContext.availableTextures;let u;for(u=0;u<r.length;u++){const _=r[u],p=c[r[u]];p==null||p==null?(r.splice(u,1),u--):n[_]=u}for(const _ of h.getAttributes(this,o))l.push(_);this.buildUniformLayout();const d=[],f=[];for(u=0;u<o.length;u++){const _=l[u];_>=0&&(d.push(o[u]),f.push(_))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new be(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=ai.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return(e=this.sources)==null?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)==null?void 0:e.fragment}}const QI=4,ZI=65536,Wx={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Lr{static get KnownUBOs(){return Lr._SimplifiedKnownBindings?Lr._SimplifiedKnownUBOs:Lr._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Lr.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(Wx[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(Wx[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>ZI-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===QI)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Lr._SimplifiedKnownBindings=!0;Lr._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}};Lr._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class JI extends ai{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Zt.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const o=e.substring(r+1,n);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO
uniform ${ai.InternalsUBOName} {
float yFactor_;
float textureOutputHeight_;
};
`,s=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+`##INJECTCODE##
`+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,s=/(flat\s)?\s*\bin\b/,r=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?i:r).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,r=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,l=(t&&this._fragmentIsGLES3?r:!t&&this._vertexIsGLES3?s:n).exec(e);if(l!==null){const h=l[1]??"",c=l[2],u=l[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[u],this._missingVaryings[d]="",d===void 0&&O.Warn(`Invalid fragment shader: The varying named "${u}" is not declared in the vertex shader! This declaration will be ignored.`)):(d=this._webgpuProcessingContext.getVaryingNextLocation(c,this._getArraySize(u,c,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=d,this._missingVaryings[d]=`layout(location = ${d}) ${h} in ${c} ${u};`),e=e.replace(l[0],d===void 0?"":`layout(location = ${d}) ${h} ${t?"in":"out"} ${c} ${u};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,s=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,n=(this._vertexIsGLES3?i:s).exec(e);if(n!==null){const o=n[1],l=n[2],h=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=h,this._webgpuProcessingContext.orderedAttributes[h]=l;const c=this.vertexBufferKindToNumberOfComponents[l];if(c!==void 0){const u=c<0?c===-1?"int":"ivec"+-c:c===1?"uint":"uvec"+c,d=`_int_${l}_`;e=e.replace(n[0],`layout(location = ${h}) in ${u} ${d}; ${o} ${l} = ${o}(${d});`)}else e=e.replace(n[0],`layout(location = ${h}) in ${o} ${l};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const r=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(r!==null){let n=r[1],o=r[2];if(n.indexOf("sampler")===0||n.indexOf("sampler")===1){let l=0;[o,n,l]=this._getArraySize(o,n,i);let h=this._webgpuProcessingContext.availableTextures[o];if(!h){h={autoBindSampler:!0,isTextureArray:l>0,isStorageTexture:!1,textures:[],sampleType:br.Float};for(let A=0;A<(l||1);++A)h.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const c=ai._SamplerTypeByWebGLSamplerType[n]??"sampler",u=!!ai._IsComparisonSamplerByWebGPUSamplerType[c],d=u?io.Comparison:io.Filtering,f=o+ai.AutoSamplerSuffix;let _=this._webgpuProcessingContext.availableSamplers[f];_||(_={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const p=n.charAt(0)==="u"?"u":n.charAt(0)==="i"?"i":"";p&&(n=n.substr(1));const g=u?br.Depth:p==="u"?br.Uint:p==="i"?br.Sint:br.Float;h.sampleType=g;const x=l>0,T=_.binding.groupIndex,S=_.binding.bindingIndex,C=ai._SamplerFunctionByWebGLSamplerType[n],v=ai._TextureTypeByWebGLSamplerType[n],b=ai._GpuTextureViewDimensionByWebGPUTextureType[v];if(!x)l=1,e=`layout(set = ${T}, binding = ${S}) uniform ${c} ${f};
                        layout(set = ${h.textures[0].groupIndex}, binding = ${h.textures[0].bindingIndex}) uniform ${p}${v} ${o}Texture;
                        #define ${o} ${p}${C}(${o}Texture, ${f})`;else{const A=[];A.push(`layout(set = ${T}, binding = ${S}) uniform ${p}${c} ${f};`),e=`
`;for(let P=0;P<l;++P){const L=h.textures[P].groupIndex,w=h.textures[P].bindingIndex;A.push(`layout(set = ${L}, binding = ${w}) uniform ${v} ${o}Texture${P};`),e+=`${P>0?`
`:""}#define ${o}${P} ${p}${C}(${o}Texture${P}, ${f})`}e=A.join(`
`)+e,this._textureArrayProcessing.push(o)}this._webgpuProcessingContext.availableTextures[o]=h,this._webgpuProcessingContext.availableSamplers[f]=_,this._addSamplerBindingDescription(f,_,!t);for(let A=0;A<l;++A)this._addTextureBindingDescription(o,h,A,b,null,!t)}else this._addUniformToLeftOverUBO(o,n,i),e=""}return e}uniformBufferProcessor(e,t){const s=/uniform\s+(\w+)/gm.exec(e);if(s!==null){const r=s[1];let n=this._webgpuProcessingContext.availableBuffers[r];if(!n){const o=Lr.KnownUBOs[r];let l;o&&o.binding.groupIndex!==-1?l=o.binding:l=this._webgpuProcessingContext.getNextFreeUBOBinding(),n={binding:l},this._webgpuProcessingContext.availableBuffers[r]=n}this._addBufferBindingDescription(r,n,Wa.Uniform,!t),e=e.replace("uniform",`layout(set = ${n.binding.groupIndex}, binding = ${n.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,i,s,r){const n=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,o=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(o,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const l=e.indexOf("gl_FragCoord")>=0,h=`
                glFragCoord_ = gl_FragCoord;
                if (yFactor_ == 1.) {
                    glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;
                }
            `,c=l?`vec4 glFragCoord_;
`:"",u=e.search(/layout *\(location *= *0\) *out/g)!==-1;if(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/gl_FragCoord/g,"glFragCoord_"),!this._fragmentIsGLES3)e=e.replace(/void\s+?main\s*\(/g,(n||u?"":`layout(location = 0) out vec4 glFragColor;
`)+"void main(");else{const d=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);d!==null&&(e=e.substring(0,d.index)+"layout(location = 0) "+e.substring(d.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",c),l&&(e=this._injectStartingAndEndingCode(e,"void main",h))}else if(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex"),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
`+e;if(!i){const l=e.lastIndexOf("}");e=e.substring(0,l),e+=`gl_Position.y *= yFactor_;
`,r.isNDCHalfZRange||(e+=`gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;
`),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;s!==null;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {
    `;for(const s of this._webgpuProcessingContext.leftOverUniforms)s.length>0?i+=`    ${s.type} ${s.name}[${s.length}];
`:i+=`    ${s.type} ${s.name};
`;return i+=`};

`,i}finalizeShaders(e,t){for(let s=0;s<this._textureArrayProcessing.length;++s){const r=this._textureArrayProcessing[s];e=this._applyTextureArrayProcessing(e,r),t=this._applyTextureArrayProcessing(t,r)}for(let s=0;s<this._missingVaryings.length;++s){const r=this._missingVaryings[s];r&&r.length>0&&(t=r+`
`+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const e0="bonesDeclaration",t0=`#if NUM_BONE_INFLUENCERS>0
attribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>;
#if NUM_BONE_INFLUENCERS>4
attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32;
#else
uniform mBones : array<mat4x4,BonesPerMesh>;
#ifdef BONES_VELOCITY_ENABLED
uniform mPreviousBones : array<mat4x4,BonesPerMesh>;
#endif
#endif
#ifdef BONETEXTURE
fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>
{let offset=i32(index) *4; 
let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);}
#endif
#endif
#endif
`;W.IncludesShadersStoreWGSL[e0]=t0;const i0="bonesVertex",s0=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
var influence : mat4x4<f32>;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];
#endif 
#if NUM_BONE_INFLUENCERS>2
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];
#endif 
#if NUM_BONE_INFLUENCERS>3
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];
#endif 
#if NUM_BONE_INFLUENCERS>4
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];
#endif 
#if NUM_BONE_INFLUENCERS>5
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];
#endif 
#if NUM_BONE_INFLUENCERS>6
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];
#endif 
#if NUM_BONE_INFLUENCERS>7
influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];
#endif 
#else 
influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];
#endif 
#if NUM_BONE_INFLUENCERS>2
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];
#endif 
#if NUM_BONE_INFLUENCERS>3
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];
#endif 
#if NUM_BONE_INFLUENCERS>4
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];
#endif 
#if NUM_BONE_INFLUENCERS>5
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];
#endif 
#if NUM_BONE_INFLUENCERS>6
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];
#endif 
#if NUM_BONE_INFLUENCERS>7
influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];
#endif 
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`;W.IncludesShadersStoreWGSL[i0]=s0;const r0="bakedVertexAnimationDeclaration",n0=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>;
#ifdef INSTANCES
attribute bakedVertexAnimationSettingsInstanced : vec4<f32>;
#endif
fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>
{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);}
#endif
`;W.IncludesShadersStoreWGSL[r0]=n0;const a0="bakedVertexAnimation",o0=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;
#else
let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;
#endif
let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;W.IncludesShadersStoreWGSL[a0]=o0;const l0="clipPlaneFragment",h0=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fragmentInputs.fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fragmentInputs.fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fragmentInputs.fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fragmentInputs.fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fragmentInputs.fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fragmentInputs.fClipDistance6>0.0)
{discard;}
#endif
`;W.IncludesShadersStoreWGSL[l0]=h0;const c0="clipPlaneFragmentDeclaration",u0=`#ifdef CLIPPLANE
varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
varying fClipDistance6: f32;
#endif
`;W.IncludesShadersStoreWGSL[c0]=u0;const d0="clipPlaneVertex",f0=`#ifdef CLIPPLANE
vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);
#endif
#ifdef CLIPPLANE2
vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);
#endif
#ifdef CLIPPLANE3
vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);
#endif
#ifdef CLIPPLANE4
vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);
#endif
#ifdef CLIPPLANE5
vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);
#endif
#ifdef CLIPPLANE6
vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);
#endif
`;W.IncludesShadersStoreWGSL[d0]=f0;const _0="clipPlaneVertexDeclaration",p0=`#ifdef CLIPPLANE
uniform vClipPlane: vec4<f32>;varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32;
#endif
`;W.IncludesShadersStoreWGSL[_0]=p0;const m0="instancesDeclaration",g0=`#ifdef INSTANCES
attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;
#ifdef INSTANCESCOLOR
attribute instanceColor : vec4<f32>;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>;
#ifdef THIN_INSTANCES
uniform previousWorld : mat4x4<f32>;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY)
uniform previousWorld : mat4x4<f32>;
#endif
#endif
`;W.IncludesShadersStoreWGSL[m0]=g0;const x0="instancesVertex",T0=`#ifdef INSTANCES
var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
#if !defined(WORLD_UBO)
finalWorld=uniforms.world*finalWorld;
#else
finalWorld=mesh.world*finalWorld;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
var finalWorld=uniforms.world;
#else
var finalWorld=mesh.world;
#endif
#if defined(PREPASS_VELOCITY) || defined(VELOCITY)
var finalPreviousWorld=previousWorld;
#endif
#endif
`;W.IncludesShadersStoreWGSL[x0]=T0;const E0="meshUboDeclaration",S0=`struct Mesh {world : mat4x4<f32>,
visibility : f32,};var<uniform> mesh : Mesh;
#define WORLD_UBO
`;W.IncludesShadersStoreWGSL[E0]=S0;const C0="morphTargetsVertex",v0=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;}
vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;
#ifdef MORPHTARGETS_NORMAL
normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];
#endif
}
#endif
#else
positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];
#endif
#endif
#endif
`;W.IncludesShadersStoreWGSL[C0]=v0;const b0="morphTargetsVertexDeclaration",A0=`#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
attribute position{X} : vec3<f32>;
#ifdef MORPHTARGETS_NORMAL
attribute normal{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_TANGENT
attribute tangent{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_UV
attribute uv_{X} : vec2<f32>;
#endif
#elif {X}==0
uniform morphTargetCount: i32;
#endif
#endif
`;W.IncludesShadersStoreWGSL[b0]=A0;const y0="morphTargetsVertexGlobal",R0=`#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
var vertexID : f32;
#endif
#endif
`;W.IncludesShadersStoreWGSL[y0]=R0;const I0="morphTargetsVertexGlobalDeclaration",P0=`#ifdef MORPHTARGETS
uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;
#ifdef MORPHTARGETS_TEXTURE 
uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>
{ 
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}
#endif
#endif
`;W.IncludesShadersStoreWGSL[I0]=P0;const M0="sceneUboDeclaration",D0=`struct Scene {viewProjection : mat4x4<f32>,
#ifdef MULTIVIEW
viewProjectionR : mat4x4<f32>,
#endif 
view : mat4x4<f32>,
projection : mat4x4<f32>,
vEyePosition : vec4<f32>,};var<uniform> scene : Scene;
`;W.IncludesShadersStoreWGSL[M0]=D0;const Hx="fragmentOutputs.fragDepth",O0="uniforms",N0="internals",F0={texture_1d:Dt.E1d,texture_2d:Dt.E2d,texture_2d_array:Dt.E2dArray,texture_3d:Dt.E3d,texture_cube:Dt.Cube,texture_cube_array:Dt.CubeArray,texture_multisampled_2d:Dt.E2d,texture_depth_2d:Dt.E2d,texture_depth_2d_array:Dt.E2dArray,texture_depth_cube:Dt.Cube,texture_depth_cube_array:Dt.CubeArray,texture_depth_multisampled_2d:Dt.E2d,texture_storage_1d:Dt.E1d,texture_storage_2d:Dt.E2d,texture_storage_2d_array:Dt.E2dArray,texture_storage_3d:Dt.E3d,texture_external:null};class w0 extends ai{constructor(){super(...arguments),this.shaderLanguage=Zt.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let n=r;for(;n>0&&t.charAt(n)!==" "&&t.charAt(n)!==",";)n--;const o=t.substring(n+1,r);for(s=+o,isNaN(s)&&(s=+i[o.trim()]);n>0&&(t.charAt(n)===" "||t.charAt(n)===",");)n--;t=t.substring(t.indexOf("<")+1,n+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${ai.InternalsUBOName} {
  yFactor_: f32,
  textureOutputHeight_: f32,
};
var<uniform> ${N0} : ${ai.InternalsUBOName};
`;return e.indexOf(t)!==-1?e:t+cp(e)}varyingProcessor(e,t,i){const r=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[1]??"perspective",o=r[2]??"center",l=r[4],h=r[3];let c;t?(c=this._webgpuProcessingContext.availableVaryings[h],c===void 0&&O.Warn(`Invalid fragment shader: The varying named "${h}" is not declared in the vertex shader! This declaration will be ignored.`)):(c=this._webgpuProcessingContext.getVaryingNextLocation(l,this._getArraySize(h,l,i)[2]),this._webgpuProcessingContext.availableVaryings[h]=c,this._varyingsWGSL.push(`  @location(${c}) @interpolate(${n}, ${o}) ${h} : ${l},`),this._varyingNamesWGSL.push(h)),e=""}return e}attributeProcessor(e,t){const s=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const r=s[2],n=s[1],o=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=o,this._webgpuProcessingContext.orderedAttributes[o]=n;const l=this.vertexBufferKindToNumberOfComponents[n];if(l!==void 0){const h=l<0?l===-1?"i32":"vec"+-l+"<i32>":l===1?"u32":"vec"+l+"<u32>",c=`_int_${n}_`;this._attributesInputWGSL.push(`@location(${o}) ${c} : ${h},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = ${r}(vertexInputs_.${c});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${o}) ${n} : ${r},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = vertexInputs_.${n};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(s!==null){const r=s[2],n=s[1];this._addUniformToLeftOverUBO(n,r,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(s!==null){const r=s[1],n=s[2],o=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let d=o?this._getArraySize(r,n,i)[2]:0,f=this._webgpuProcessingContext.availableTextures[r];if(f)d=f.textures.length;else{f={isTextureArray:d>0,isStorageTexture:h,textures:[],sampleType:br.Float},d=d||1;for(let x=0;x<d;++x)f.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[r]=f;const _=l.indexOf("depth")>0,p=F0[l],g=_?br.Depth:c==="u32"?br.Uint:c==="i32"?br.Sint:br.Float;if(f.sampleType=g,p===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let x=0;x<d;++x){const{groupIndex:T,bindingIndex:S}=f.textures[x];x===0&&(e=`@group(${T}) @binding(${S}) ${e}`),this._addTextureBindingDescription(r,f,x,p,u,!t)}}return e}postProcessor(e,t){const i={};for(const s of t){const r=s.split(/ +/);i[r[1]]=r.length>2?r[2]:""}return e.replace(/\$(\w+)\$/g,(s,r)=>i[r]??r)}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?`
            if (internals.yFactor_ == 1.) {
                fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;
            }
        `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();e=s+e,t=s+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r=`struct VertexInputs {
  @builtin(vertex_index) vertexIndex : u32,
  @builtin(instance_index) instanceIndex : u32,
`;this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join(`
`)),r+=`
};
var<private> vertexInputs`+(this._hasNonFloatAttribute?"_":"")+` : VertexInputs;
`,this._hasNonFloatAttribute&&(r+=`struct VertexInputs_ {
  vertexIndex : u32, instanceIndex : u32,
`,r+=this._attributesWGSL.join(`
`),r+=`
};
var<private> vertexInputs : VertexInputs_;
`);let n=`struct FragmentInputs {
  @builtin(position) position : vec4<f32>,
`;this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join(`
`)),n+=`
};
var<private> vertexOutputs : FragmentInputs;
`,e=r+n+e;let o=`
  vertexInputs${this._hasNonFloatAttribute?"_":""} = input;
`;this._hasNonFloatAttribute&&(o+=`vertexInputs.vertexIndex = vertexInputs_.vertexIndex;
vertexInputs.instanceIndex = vertexInputs_.instanceIndex;
`,o+=this._attributesConversionCodeWGSL.join(`
`),o+=`
`);const l=`  vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;
  return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",o,l),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let h=`struct FragmentInputs {
  @builtin(position) position : vec4<f32>,
  @builtin(front_facing) frontFacing : bool,
`;this._varyingsWGSL.length>0&&(h+=this._varyingsWGSL.join(`
`)),h+=`
};
var<private> fragmentInputs : FragmentInputs;
`;let c=`struct FragmentOutputs {
  @location(0) color : vec4<f32>,
`,u=!1,d=0;for(;!u&&(d=t.indexOf(Hx,d),!(d<0));){const p=d;for(u=!0;d>1&&t.charAt(d)!==`
`;){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=p+Hx.length}u&&(c+=`  @builtin(frag_depth) fragDepth: f32,
`),c+=`};
var<private> fragmentOutputs : FragmentOutputs;
`,t=h+c+t;const f=`  fragmentInputs = input;
  `+i,_="  return fragmentOutputs;";return t=this._injectStartingAndEndingCode(t,"fn main",f,_),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {
`;for(const r of this._webgpuProcessingContext.leftOverUniforms){const n=r.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=ai.UniformSizes[n];if(r.length>0)if(o<=2){const l=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${l} {
                        @size(16)
                        el: ${n},
                    }`,this._stridedUniformArrays.push(r.name),s+=` @align(16) ${r.name} : array<${l}, ${r.length}>,
`}else s+=` ${r.name} : array<${r.type}, ${r.length}>,
`;else s+=`  ${r.name} : ${r.type},
`}return s+=`};
`,s=`${i}
${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> ${O0} : ${e};
`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const r=s[1],n=s[2],o=r.indexOf(ai.AutoSamplerSuffix)===r.length-ai.AutoSamplerSuffix.length?r.substring(0,r.indexOf(ai.AutoSamplerSuffix)):null,l=n==="sampler_comparison"?io.Comparison:io.Filtering;if(o){const f=this._webgpuProcessingContext.availableTextures[o];f&&(f.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[r];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[r]=h),this._addSamplerBindingDescription(r,h,t);const c=e.substring(0,s.index),u=`@group(${h.binding.groupIndex}) @binding(${h.binding.bindingIndex}) `,d=e.substring(s.index);e=c+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const r=s[1],n=s[3];let o=s[4];const l=s[5];let h=this._webgpuProcessingContext.availableBuffers[o];if(!h){const p=r==="uniform"?Lr.KnownUBOs[l]:null;let g;p?(o=l,g=p.binding,g.groupIndex===-1&&(g=this._webgpuProcessingContext.getNextFreeUBOBinding())):g=this._webgpuProcessingContext.getNextFreeUBOBinding(),h={binding:g},this._webgpuProcessingContext.availableBuffers[o]=h}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],n==="read_write"?Wa.Storage:r==="storage"?Wa.ReadOnlyStorage:Wa.Uniform,t);const c=h.binding.groupIndex,u=h.binding.bindingIndex,d=e.substring(0,s.index),f=`@group(${c}) @binding(${u}) `,_=e.substring(s.index);e=d+f+_,i.lastIndex+=f.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class vt{static ComputeNumMipmapLevels(e,t){return ge.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case N.R8Unorm:case N.R8Snorm:case N.R8Uint:case N.R8Sint:case N.RG8Unorm:case N.RG8Snorm:case N.RG8Uint:case N.RG8Sint:case N.RGBA8Unorm:case N.RGBA8UnormSRGB:case N.RGBA8Snorm:case N.RGBA8Uint:case N.RGBA8Sint:case N.BGRA8Unorm:case N.BGRA8UnormSRGB:case N.RGB10A2UINT:case N.RGB10A2Unorm:case N.RGB9E5UFloat:case N.RG11B10UFloat:case N.BC7RGBAUnorm:case N.BC7RGBAUnormSRGB:case N.BC6HRGBUFloat:case N.BC6HRGBFloat:case N.BC5RGUnorm:case N.BC5RGSnorm:case N.BC3RGBAUnorm:case N.BC3RGBAUnormSRGB:case N.BC2RGBAUnorm:case N.BC2RGBAUnormSRGB:case N.BC4RUnorm:case N.BC4RSnorm:case N.BC1RGBAUnorm:case N.BC1RGBAUnormSRGB:case N.ETC2RGB8Unorm:case N.ETC2RGB8UnormSRGB:case N.ETC2RGB8A1Unorm:case N.ETC2RGB8A1UnormSRGB:case N.ETC2RGBA8Unorm:case N.ETC2RGBA8UnormSRGB:case N.EACR11Unorm:case N.EACR11Snorm:case N.EACRG11Unorm:case N.EACRG11Snorm:case N.ASTC4x4Unorm:case N.ASTC4x4UnormSRGB:case N.ASTC5x4Unorm:case N.ASTC5x4UnormSRGB:case N.ASTC5x5Unorm:case N.ASTC5x5UnormSRGB:case N.ASTC6x5Unorm:case N.ASTC6x5UnormSRGB:case N.ASTC6x6Unorm:case N.ASTC6x6UnormSRGB:case N.ASTC8x5Unorm:case N.ASTC8x5UnormSRGB:case N.ASTC8x6Unorm:case N.ASTC8x6UnormSRGB:case N.ASTC8x8Unorm:case N.ASTC8x8UnormSRGB:case N.ASTC10x5Unorm:case N.ASTC10x5UnormSRGB:case N.ASTC10x6Unorm:case N.ASTC10x6UnormSRGB:case N.ASTC10x8Unorm:case N.ASTC10x8UnormSRGB:case N.ASTC10x10Unorm:case N.ASTC10x10UnormSRGB:case N.ASTC12x10Unorm:case N.ASTC12x10UnormSRGB:case N.ASTC12x12Unorm:case N.ASTC12x12UnormSRGB:case N.Stencil8:return 0;case N.R16Uint:case N.R16Sint:case N.RG16Uint:case N.RG16Sint:case N.RGBA16Uint:case N.RGBA16Sint:case N.Depth16Unorm:return 5;case N.R16Float:case N.RG16Float:case N.RGBA16Float:return 2;case N.R32Uint:case N.R32Sint:case N.RG32Uint:case N.RG32Sint:case N.RGBA32Uint:case N.RGBA32Sint:return 7;case N.R32Float:case N.RG32Float:case N.RGBA32Float:case N.Depth32Float:case N.Depth32FloatStencil8:case N.Depth24Plus:case N.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case N.R8Unorm:case N.R8Snorm:case N.R8Uint:case N.R8Sint:return{width:1,height:1,length:1};case N.R16Uint:case N.R16Sint:case N.R16Float:case N.RG8Unorm:case N.RG8Snorm:case N.RG8Uint:case N.RG8Sint:return{width:1,height:1,length:2};case N.R32Uint:case N.R32Sint:case N.R32Float:case N.RG16Uint:case N.RG16Sint:case N.RG16Float:case N.RGBA8Unorm:case N.RGBA8UnormSRGB:case N.RGBA8Snorm:case N.RGBA8Uint:case N.RGBA8Sint:case N.BGRA8Unorm:case N.BGRA8UnormSRGB:case N.RGB9E5UFloat:case N.RGB10A2UINT:case N.RGB10A2Unorm:case N.RG11B10UFloat:return{width:1,height:1,length:4};case N.RG32Uint:case N.RG32Sint:case N.RG32Float:case N.RGBA16Uint:case N.RGBA16Sint:case N.RGBA16Float:return{width:1,height:1,length:8};case N.RGBA32Uint:case N.RGBA32Sint:case N.RGBA32Float:return{width:1,height:1,length:16};case N.Stencil8:throw"No fixed size for Stencil8 format!";case N.Depth16Unorm:return{width:1,height:1,length:2};case N.Depth24Plus:throw"No fixed size for Depth24Plus format!";case N.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case N.Depth32Float:return{width:1,height:1,length:4};case N.Depth32FloatStencil8:return{width:1,height:1,length:5};case N.BC7RGBAUnorm:case N.BC7RGBAUnormSRGB:case N.BC6HRGBUFloat:case N.BC6HRGBFloat:case N.BC5RGUnorm:case N.BC5RGSnorm:case N.BC3RGBAUnorm:case N.BC3RGBAUnormSRGB:case N.BC2RGBAUnorm:case N.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case N.BC4RUnorm:case N.BC4RSnorm:case N.BC1RGBAUnorm:case N.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case N.ETC2RGB8Unorm:case N.ETC2RGB8UnormSRGB:case N.ETC2RGB8A1Unorm:case N.ETC2RGB8A1UnormSRGB:case N.EACR11Unorm:case N.EACR11Snorm:return{width:4,height:4,length:8};case N.ETC2RGBA8Unorm:case N.ETC2RGBA8UnormSRGB:case N.EACRG11Unorm:case N.EACRG11Snorm:return{width:4,height:4,length:16};case N.ASTC4x4Unorm:case N.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case N.ASTC5x4Unorm:case N.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case N.ASTC5x5Unorm:case N.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case N.ASTC6x5Unorm:case N.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case N.ASTC6x6Unorm:case N.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case N.ASTC8x5Unorm:case N.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case N.ASTC8x6Unorm:case N.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case N.ASTC8x8Unorm:case N.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case N.ASTC10x5Unorm:case N.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case N.ASTC10x6Unorm:case N.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case N.ASTC10x8Unorm:case N.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case N.ASTC10x10Unorm:case N.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case N.ASTC12x10Unorm:case N.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case N.ASTC12x12Unorm:case N.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return e.close!==void 0}static IsImageBitmapArray(e){return Array.isArray(e)&&e[0].close!==void 0}static IsCompressedFormat(e){switch(e){case N.BC7RGBAUnormSRGB:case N.BC7RGBAUnorm:case N.BC6HRGBFloat:case N.BC6HRGBUFloat:case N.BC5RGSnorm:case N.BC5RGUnorm:case N.BC4RSnorm:case N.BC4RUnorm:case N.BC3RGBAUnormSRGB:case N.BC3RGBAUnorm:case N.BC2RGBAUnormSRGB:case N.BC2RGBAUnorm:case N.BC1RGBAUnormSRGB:case N.BC1RGBAUnorm:case N.ETC2RGB8Unorm:case N.ETC2RGB8UnormSRGB:case N.ETC2RGB8A1Unorm:case N.ETC2RGB8A1UnormSRGB:case N.ETC2RGBA8Unorm:case N.ETC2RGBA8UnormSRGB:case N.EACR11Unorm:case N.EACR11Snorm:case N.EACRG11Unorm:case N.EACRG11Snorm:case N.ASTC4x4Unorm:case N.ASTC4x4UnormSRGB:case N.ASTC5x4Unorm:case N.ASTC5x4UnormSRGB:case N.ASTC5x5Unorm:case N.ASTC5x5UnormSRGB:case N.ASTC6x5Unorm:case N.ASTC6x5UnormSRGB:case N.ASTC6x6Unorm:case N.ASTC6x6UnormSRGB:case N.ASTC8x5Unorm:case N.ASTC8x5UnormSRGB:case N.ASTC8x6Unorm:case N.ASTC8x6UnormSRGB:case N.ASTC8x8Unorm:case N.ASTC8x8UnormSRGB:case N.ASTC10x5Unorm:case N.ASTC10x5UnormSRGB:case N.ASTC10x6Unorm:case N.ASTC10x6UnormSRGB:case N.ASTC10x8Unorm:case N.ASTC10x8UnormSRGB:case N.ASTC10x10Unorm:case N.ASTC10x10UnormSRGB:case N.ASTC12x10Unorm:case N.ASTC12x10UnormSRGB:case N.ASTC12x12Unorm:case N.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return N.Depth16Unorm;case 16:return N.Depth24Plus;case 13:return N.Depth24PlusStencil8;case 14:return N.Depth32Float;case 18:return N.Depth32FloatStencil8;case 19:return N.Stencil8;case 36492:return i?N.BC7RGBAUnormSRGB:N.BC7RGBAUnorm;case 36495:return N.BC6HRGBUFloat;case 36494:return N.BC6HRGBFloat;case 33779:return i?N.BC3RGBAUnormSRGB:N.BC3RGBAUnorm;case 33778:return i?N.BC2RGBAUnormSRGB:N.BC2RGBAUnorm;case 33777:case 33776:return i?N.BC1RGBAUnormSRGB:N.BC1RGBAUnorm;case 37808:return i?N.ASTC4x4UnormSRGB:N.ASTC4x4Unorm;case 36196:case 37492:return i?N.ETC2RGB8UnormSRGB:N.ETC2RGB8Unorm;case 37496:return i?N.ETC2RGBA8UnormSRGB:N.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return N.R8Snorm;case 7:return N.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return N.R8Sint;case 9:return N.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA8Sint;default:return N.RGBA8Snorm}case 0:switch(t){case 6:return N.R8Unorm;case 7:return N.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?N.RGBA8UnormSRGB:N.RGBA8Unorm;case 12:return i?N.BGRA8UnormSRGB:N.BGRA8Unorm;case 8:return N.R8Uint;case 9:return N.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return N.RGBA8Unorm}case 4:switch(t){case 8:return N.R16Sint;case 9:return N.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA16Sint;default:return N.RGBA16Sint}case 5:switch(t){case 8:return N.R16Uint;case 9:return N.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA16Uint;default:return N.RGBA16Uint}case 6:switch(t){case 8:return N.R32Sint;case 9:return N.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA32Sint;default:return N.RGBA32Sint}case 7:switch(t){case 8:return N.R32Uint;case 9:return N.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return N.RGBA32Uint;default:return N.RGBA32Uint}case 1:switch(t){case 6:return N.R32Float;case 7:return N.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return N.RGBA32Float;default:return N.RGBA32Float}case 2:switch(t){case 6:return N.R16Float;case 7:return N.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return N.RGBA16Float;default:return N.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return N.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return N.RG11B10UFloat}case 14:switch(t){case 5:return N.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return N.RGB9E5UFloat}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:return N.RGB10A2Unorm;case 11:return N.RGB10A2UINT;default:return N.RGB10A2Unorm}}return i?N.RGBA8UnormSRGB:N.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case N.R8Unorm:case N.R8Snorm:case N.R8Uint:case N.R8Sint:case N.BC4RUnorm:case N.BC4RSnorm:case N.R16Uint:case N.R16Sint:case N.Depth16Unorm:case N.R16Float:case N.R32Uint:case N.R32Sint:case N.R32Float:case N.Depth32Float:case N.Stencil8:case N.Depth24Plus:case N.EACR11Unorm:case N.EACR11Snorm:return 1;case N.RG8Unorm:case N.RG8Snorm:case N.RG8Uint:case N.RG8Sint:case N.Depth32FloatStencil8:case N.BC5RGUnorm:case N.BC5RGSnorm:case N.RG16Uint:case N.RG16Sint:case N.RG16Float:case N.RG32Uint:case N.RG32Sint:case N.RG32Float:case N.Depth24PlusStencil8:case N.EACRG11Unorm:case N.EACRG11Snorm:return 2;case N.RGB9E5UFloat:case N.RG11B10UFloat:case N.BC6HRGBUFloat:case N.BC6HRGBFloat:case N.ETC2RGB8Unorm:case N.ETC2RGB8UnormSRGB:return 3;case N.RGBA8Unorm:case N.RGBA8UnormSRGB:case N.RGBA8Snorm:case N.RGBA8Uint:case N.RGBA8Sint:case N.BGRA8Unorm:case N.BGRA8UnormSRGB:case N.RGB10A2UINT:case N.RGB10A2Unorm:case N.BC7RGBAUnorm:case N.BC7RGBAUnormSRGB:case N.BC3RGBAUnorm:case N.BC3RGBAUnormSRGB:case N.BC2RGBAUnorm:case N.BC2RGBAUnormSRGB:case N.BC1RGBAUnorm:case N.BC1RGBAUnormSRGB:case N.RGBA16Uint:case N.RGBA16Sint:case N.RGBA16Float:case N.RGBA32Uint:case N.RGBA32Sint:case N.RGBA32Float:case N.ETC2RGB8A1Unorm:case N.ETC2RGB8A1UnormSRGB:case N.ETC2RGBA8Unorm:case N.ETC2RGBA8UnormSRGB:case N.ASTC4x4Unorm:case N.ASTC4x4UnormSRGB:case N.ASTC5x4Unorm:case N.ASTC5x4UnormSRGB:case N.ASTC5x5Unorm:case N.ASTC5x5UnormSRGB:case N.ASTC6x5Unorm:case N.ASTC6x5UnormSRGB:case N.ASTC6x6Unorm:case N.ASTC6x6UnormSRGB:case N.ASTC8x5Unorm:case N.ASTC8x5UnormSRGB:case N.ASTC8x6Unorm:case N.ASTC8x6UnormSRGB:case N.ASTC8x8Unorm:case N.ASTC8x8UnormSRGB:case N.ASTC10x5Unorm:case N.ASTC10x5UnormSRGB:case N.ASTC10x6Unorm:case N.ASTC10x6UnormSRGB:case N.ASTC10x8Unorm:case N.ASTC10x8UnormSRGB:case N.ASTC10x10Unorm:case N.ASTC10x10UnormSRGB:case N.ASTC12x10Unorm:case N.ASTC12x10UnormSRGB:case N.ASTC12x12Unorm:case N.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case N.Stencil8:case N.Depth32FloatStencil8:case N.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case N.Depth32FloatStencil8:case N.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case N.Depth16Unorm:return N.Depth16Unorm;case N.Depth24Plus:return N.Depth24Plus;case N.Depth24PlusStencil8:return N.Depth24Plus;case N.Depth32Float:return N.Depth32Float;case N.Depth32FloatStencil8:return N.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Hd{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t;return((t=this._webgpuMSAATexture)==null?void 0:t[e])??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=N.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,l){let h=Dt.E2d,c=1;s?(h=i?Dt.CubeArray:Dt.Cube,c=6*(l||1)):r?h=Dt.E3d:i&&(h=Dt.E2dArray,c=l);const u=vt.GetDepthFormatOnly(this.format),d=vt.HasDepthAndStencilAspects(this.format)?gn.DepthOnly:gn.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+c:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${h}`,format:u,dimension:h,mipLevelCount:t?ge.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:c,aspect:d})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;(e=this._webgpuTexture)==null||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)==null||t.destroy(),this.reset()}}const L0=`
    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
    const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));

    layout(location = 0) out vec2 vTex;

    void main() {
        vTex = tex[gl_VertexIndex];
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `,B0=`
    layout(set = 0, binding = 0) uniform sampler imgSampler;
    layout(set = 0, binding = 1) uniform texture2D img;

    layout(location = 0) in vec2 vTex;
    layout(location = 0) out vec4 outColor;

    void main() {
        outColor = texture(sampler2D(img, imgSampler), vTex);
    }
    `,PS=`
    #extension GL_EXT_samplerless_texture_functions : enable

    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));
    const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));

    layout(set = 0, binding = 0) uniform texture2D img;

    #ifdef INVERTY
        layout(location = 0) out flat ivec2 vTextureSize;
    #endif

    void main() {
        #ifdef INVERTY
            vTextureSize = textureSize(img, 0);
        #endif
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `,U0=`
    #extension GL_EXT_samplerless_texture_functions : enable

    layout(set = 0, binding = 0) uniform texture2D img;

    #ifdef INVERTY
        layout(location = 0) in flat ivec2 vTextureSize;
    #endif
    layout(location = 0) out vec4 outColor;

    void main() {
    #ifdef INVERTY
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);
    #else
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);
    #endif
    #ifdef PREMULTIPLYALPHA
        color.rgb *= color.a;
    #endif
        outColor = color;
    }
    `,V0=PS,k0=`
    #extension GL_EXT_samplerless_texture_functions : enable

    layout(set = 0, binding = 0) uniform texture2D img;
    layout(set = 0, binding = 1) uniform Params {
        float ofstX;
        float ofstY;
        float width;
        float height;
    };

    #ifdef INVERTY
        layout(location = 0) in flat ivec2 vTextureSize;
    #endif
    layout(location = 0) out vec4 outColor;

    void main() {
        if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {
            discard;
        }
        if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {
            discard;
        }
    #ifdef INVERTY
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);
    #else
        vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);
    #endif
    #ifdef PREMULTIPLYALPHA
        color.rgb *= color.a;
    #endif
        outColor = color;
    }
    `,G0=`
    const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));

    void main() {
        gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    }
    `,z0=`
    layout(set = 0, binding = 0) uniform Uniforms {
        uniform vec4 color;
    };

    layout(location = 0) out vec4 outColor;

    void main() {
        outColor = color;
    }
    `,W0=`
    struct VertexOutput {
        @builtin(position) Position : vec4<f32>,
        @location(0) fragUV : vec2<f32>
    }

    @vertex
    fn main(
        @builtin(vertex_index) VertexIndex : u32
    ) -> VertexOutput {
        var pos = array<vec2<f32>, 4>(
            vec2(-1.0,  1.0),
            vec2( 1.0,  1.0),
            vec2(-1.0, -1.0),
            vec2( 1.0, -1.0)
        );
        var tex = array<vec2<f32>, 4>(
            vec2(0.0, 0.0),
            vec2(1.0, 0.0),
            vec2(0.0, 1.0),
            vec2(1.0, 1.0)
        );

        var output: VertexOutput;

        output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);
        output.fragUV = tex[VertexIndex];

        return output;
    }
    `,H0=`
    @group(0) @binding(0) var videoSampler: sampler;
    @group(0) @binding(1) var videoTexture: texture_external;

    @fragment
    fn main(
        @location(0) fragUV: vec2<f32>
    ) -> @location(0) vec4<f32> {
        return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);
    }
    `,X0=`
    @group(0) @binding(0) var videoSampler: sampler;
    @group(0) @binding(1) var videoTexture: texture_external;

    @fragment
    fn main(
        @location(0) fragUV: vec2<f32>
    ) -> @location(0) vec4<f32> {
        return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y));
    }
    `;var Qr;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Qr||(Qr={}));var gl;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(gl||(gl={}));const Xx=[{vertex:L0,fragment:B0},{vertex:PS,fragment:U0},{vertex:G0,fragment:z0},{vertex:V0,fragment:k0}],Un={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class Y0{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,n.indexOf(Fn.RG11B10UFloatRenderable)!==-1){const o=Object.keys(Un);Un[N.RG11B10UFloat]=Un[o[o.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:ct.Linear}),this._videoSampler=t.createSampler({minFilter:ct.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,kt.Uniform|kt.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(N.RGBA8Unorm),this._getVideoPipeline(N.RGBA8Unorm)}_getPipeline(e,t=Qr.MipMap,i){const s=t===Qr.MipMap?1:t===Qr.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Qr.Clear?8:t===Qr.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n=`#version 450
`;(t===Qr.InvertYPremultiplyAlpha||t===Qr.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+=`#define INVERTY
`),i.premultiplyAlpha&&(n+=`#define PREMULTIPLYALPHA
`));let o=this._compiledShaders[s];if(!o){let h=this._glslang.compileGLSL(n+Xx[t].vertex,"vertex"),c=this._glslang.compileGLSL(n+Xx[t].fragment,"fragment");this._tintWASM&&(h=this._tintWASM.convertSpirV2WGSL(h),c=this._tintWASM.convertSpirV2WGSL(c));const u=this._device.createShaderModule({code:h}),d=this._device.createShaderModule({code:c});o=this._compiledShaders[s]=[u,d]}const l=this._device.createRenderPipeline({layout:Ru.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Tr.TriangleStrip,stripIndexFormat:so.Uint16}});r=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=gl.DontInvertY){const i=t===gl.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let r=this._videoCompiledShaders[i];if(!r){const o=this._device.createShaderModule({code:W0}),l=this._device.createShaderModule({code:i===0?H0:X0});r=this._videoCompiledShaders[i]=[o,l]}const n=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:Ru.Auto,vertex:{module:r[0],entryPoint:"main"},fragment:{module:r[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Tr.TriangleStrip,stripIndexFormat:so.Uint16}});s=this._videoPipelines[e][i]=[n,n.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){var _,p;const n=r===void 0,[o,l]=this._getVideoPipeline(i,s?gl.InvertY:gl.DontInvertY);n&&(r=this._device.createCommandEncoder({})),(_=r.pushDebugGroup)==null||_.call(r,`copy video to texture - invertY=${s}`);const h=t._hardwareTexture,c={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:h.underlyingResource.createView({format:i,dimension:Dt.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:gn.All}),loadOp:Ki.Load,storeOp:Mr.Store}]},u=r.beginRenderPass(c),d={layout:l,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(d);u.setPipeline(o),u.setBindGroup(0,f),u.draw(4,1,0,0),u.end(),(p=r.popDebugGroup)==null||p.call(r),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,l=0,h=1,c=0,u=0,d=0,f=0,_,p){var w,$;const g=d!==0,x=_===void 0,[T,S]=this._getPipeline(s,g?Qr.InvertYPremultiplyAlphaWithOfst:Qr.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});o=Math.max(o,0),x&&(_=this._device.createCommandEncoder({})),(w=_.pushDebugGroup)==null||w.call(_,`internal process texture - invertY=${r} premultiplyAlpha=${n}`);let C;if(vt.IsHardwareTexture(e)?(C=e.underlyingResource,r&&!n&&h===1&&o===0||(e=void 0)):(C=e,e=void 0),!C)return;g&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,d,f]),0,4*4);const v=e,b=(v==null?void 0:v._copyInvertYTempTexture)??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,ri.CopySrc|ri.RenderAttachment|ri.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),A=(v==null?void 0:v._copyInvertYRenderPassDescr)??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:b.createView({format:s,dimension:Dt.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Ki.Load,storeOp:Mr.Store}]},P=_.beginRenderPass(A);let L=g?v==null?void 0:v._copyInvertYBindGroupWithOfst:v==null?void 0:v._copyInvertYBindGroup;if(!L){const J={layout:S,entries:[{binding:0,resource:C.createView({format:s,dimension:Dt.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:o})}]};g&&J.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),L=this._device.createBindGroup(J)}P.setPipeline(T),P.setBindGroup(0,L),P.draw(4,1,0,0),P.end(),_.copyTextureToTexture({texture:b},{texture:C,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),v?(v._copyInvertYTempTexture=b,v._copyInvertYRenderPassDescr=A,g?v._copyInvertYBindGroupWithOfst=L:v._copyInvertYBindGroup=L):this._deferredReleaseTextures.push([b,null]),($=_.popDebugGroup)==null||$.call(_),x&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){var c,u;const r=s===void 0,[n,o]=this._getPipeline(t,Qr.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),(c=s.pushDebugGroup)==null||c.call(s,"internal copy texture with invertY");const l=s.beginRenderPass(i),h=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});l.setPipeline(n),l.setBindGroup(0,h),l.draw(4,1,0,0),l.end(),(u=s.popDebugGroup)==null||u.call(s),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=N.RGBA8Unorm,l=1,h,c=-1,u=0,d){l=vt.GetSample(l);const f=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:f},p=Un[o]?ri.RenderAttachment:0,g=vt.IsCompressedFormat(o),x=t?vt.ComputeNumMipmapLevels(e.width,e.height):1,T=c>=0?c:ri.CopySrc|ri.CopyDst|ri.TextureBinding;u|=t&&!g?ri.CopySrc|p:0,!g&&!n&&(u|=p|ri.CopyDst);const S=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${d?d+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${l}`,size:_,dimension:n?tn.E3d:tn.E2d,format:o,usage:T|u,sampleCount:l,mipLevelCount:x});return vt.IsImageBitmap(e)&&(this.updateTexture(e,S,e.width,e.height,f,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(S,o,x,0,h)),S}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=N.RGBA8Unorm,o=1,l,h=-1,c=0,u){o=vt.GetSample(o);const d=vt.IsImageBitmapArray(e)?e[0].width:e.width,f=vt.IsImageBitmapArray(e)?e[0].height:e.height,_=Un[n]?ri.RenderAttachment:0,p=vt.IsCompressedFormat(n),g=t?vt.ComputeNumMipmapLevels(d,f):1,x=h>=0?h:ri.CopySrc|ri.CopyDst|ri.TextureBinding;c|=t&&!p?ri.CopySrc|_:0,p||(c|=_|ri.CopyDst);const T=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${u?u+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:tn.E2d,format:n,usage:x|c,sampleCount:o,mipLevelCount:g});return vt.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,T,d,f,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(T,n,g,l)),T}generateCubeMipmaps(e,t,i,s){var n,o;const r=s===void 0;r&&(s=this._device.createCommandEncoder({})),(n=s.pushDebugGroup)==null||n.call(s,`create cube mipmaps - ${i} levels`);for(let l=0;l<6;++l)this.generateMipmaps(e,t,i,l,s);(o=s.popDebugGroup)==null||o.call(s),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r){var u,d,f,_;const n=r===void 0,[o,l]=this._getPipeline(t);s=Math.max(s,0),n&&(r=this._device.createCommandEncoder({})),(u=r.pushDebugGroup)==null||u.call(r,`create mipmaps for face #${s} - ${i} levels`);let h;if(vt.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let p=1;p<i;++p){const g=((d=c==null?void 0:c._mipmapGenRenderPassDescr[s])==null?void 0:d[p-1])??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_generateMipmaps_${t}_faceIndex${s}_level${p}`,colorAttachments:[{view:h.createView({format:t,dimension:Dt.E2d,baseMipLevel:p,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:s}),loadOp:Ki.Load,storeOp:Mr.Store}]};c&&(c._mipmapGenRenderPassDescr[s]=c._mipmapGenRenderPassDescr[s]||[],c._mipmapGenRenderPassDescr[s][p-1]=g);const x=r.beginRenderPass(g),T=((f=c==null?void 0:c._mipmapGenBindGroup[s])==null?void 0:f[p-1])??this._device.createBindGroup({layout:l,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:h.createView({format:t,dimension:Dt.E2d,baseMipLevel:p-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:s})}]});c&&(c._mipmapGenBindGroup[s]=c._mipmapGenBindGroup[s]||[],c._mipmapGenBindGroup[s][p-1]=T),x.setPipeline(o),x.setBindGroup(0,T),x.draw(4,1,0,0),x.end()}(_=r.popDebugGroup)==null||_.call(r),n&&(this._device.queue.submit([r.finish()]),r=null)}createGPUTextureForInternalTexture(e,t,i,s,r){e._hardwareTexture||(e._hardwareTexture=new Hd),t===void 0&&(t=e.width),i===void 0&&(i=e.height),s===void 0&&(s=e.depth);const n=e._hardwareTexture,o=((r??0)&1)!==0;n.format=vt.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),n.textureUsages=e._source===et.RenderTarget||e.source===et.MultiRenderTarget?ri.TextureBinding|ri.CopySrc|ri.RenderAttachment:e._source===et.DepthStencil?ri.TextureBinding|ri.RenderAttachment:-1,n.textureAdditionalUsages=o?ri.StorageBinding:0;const l=e.generateMipMaps,h=s||1;let c;if(e._maxLodLevel!==null?c=e._maxLodLevel:c=l?vt.ComputeNumMipmapLevels(t,i):1,e.isCube){const u=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,n.format,1,this._commandEncoderForCreation,n.textureUsages,n.textureAdditionalUsages,e.label);n.set(u);const d=e.is3D?1:h,f=vt.GetDepthFormatOnly(n.format),_=vt.HasDepthAndStencilAspects(n.format)?gn.DepthOnly:gn.All,p=e.is2DArray?Dt.CubeArray:Dt.Cube;n.createView({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureViewCube${e.is2DArray?"_Array"+d:""}_${t}x${i}_${l?"wmips":"womips"}_${f}_${p}_${_}`,format:f,dimension:p,mipLevelCount:c,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:_},o)}else{const u=this.createTexture({width:t,height:i,layers:h},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,n.format,1,this._commandEncoderForCreation,n.textureUsages,n.textureAdditionalUsages,e.label);n.set(u);const d=e.is3D?1:h,f=vt.GetDepthFormatOnly(n.format),_=vt.HasDepthAndStencilAspects(n.format)?gn.DepthOnly:gn.All,p=e.is2DArray?Dt.E2dArray:e.is3D?tn.E3d:Dt.E2d;n.createView({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureView${e.is3D?"3D":"2D"}${e.is2DArray?"_Array"+d:""}_${t}x${i}_${l?"wmips":"womips"}_${f}_${p}_${_}`,format:f,dimension:p,mipLevelCount:c,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:d,aspect:_},o)}return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=s,this.createMSAATexture(e,e.samples),n}createMSAATexture(e,t,i=!0,s=-1){const r=e._hardwareTexture;if(i&&(r==null||r.releaseMSAATexture()),!r||(t??1)<=1)return;const n=e.width,o=e.height,l=this.createTexture({width:n,height:o,layers:1},!1,!1,!1,!1,!1,r.format,t,this._commandEncoderForCreation,ri.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);r.setMSAATexture(l,s)}updateCubeTextures(e,t,i,s,r,n=!1,o=!1,l=0,h=0){const c=[0,3,1,4,2,5];for(let u=0;u<c.length;++u){const d=e[c[u]];this.updateTexture(d,t,i,s,1,r,u,0,n,o,l,h)}}updateTexture(e,t,i,s,r,n,o=0,l=0,h=!1,c=!1,u=0,d=0,f){const _=vt.IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,p=vt.GetBlockInformationFromFormat(n),g=vt.IsInternalTexture(t)?t._hardwareTexture:t,x={texture:_,origin:{x:u,y:d,z:Math.max(o,0)},mipLevel:l,premultipliedAlpha:c},T={width:Math.ceil(i/p.width)*p.width,height:Math.ceil(s/p.height)*p.height,depthOrArrayLayers:r||1};if(e.byteLength!==void 0){e=e;const S=Math.ceil(i/p.width)*p.length;if(Math.ceil(S/256)*256===S){const v=this._device.createCommandEncoder({}),b=this._bufferManager.createRawBuffer(e.byteLength,kt.MapWrite|kt.CopySrc,!0,"TempBufferForUpdateTexture"+(_?"_"+_.label:"")),A=b.getMappedRange();new Uint8Array(A).set(e),b.unmap(),v.copyBufferToTexture({buffer:b,offset:0,bytesPerRow:S,rowsPerImage:s},x,T),this._device.queue.submit([v.finish()]),this._bufferManager.releaseBuffer(b)}else this._device.queue.writeTexture(x,e,{offset:0,bytesPerRow:S,rowsPerImage:s},T);if(h||c)if(vt.IsInternalTexture(t)){const v=u===0&&d===0&&i===t.width&&s===t.height;this.invertYPreMultiplyAlpha(g,t.width,t.height,n,h,c,o,l,r||1,u,d,v?0:i,v?0:s,void 0,f)}else throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"}else if(e=e,h)if(x.premultipliedAlpha=!1,vt.IsInternalTexture(t)&&u===0&&d===0&&i===t.width&&s===t.height)this._device.queue.copyExternalImageToTexture({source:e},x,T),this.invertYPreMultiplyAlpha(g,i,s,n,h,c,o,l,r||1,0,0,0,0,void 0,f);else{const S=this._device.createCommandEncoder({}),C=this.createTexture({width:i,height:s,layers:1},!1,!1,!1,!1,!1,n,1,S,ri.CopySrc|ri.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([C,null]),T.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:C},T),T.depthOrArrayLayers=r||1,this.invertYPreMultiplyAlpha(C,i,s,n,h,c,o,l,r||1,0,0,0,0,S,f),S.copyTextureToTexture({texture:C},x,T),this._device.queue.submit([S.finish()])}else this._device.queue.copyExternalImageToTexture({source:e},x,T)}readPixels(e,t,i,s,r,n,o=0,l=0,h=null,c=!1){const u=vt.GetBlockInformationFromFormat(n),d=Math.ceil(s/u.width)*u.length,f=Math.ceil(d/256)*256,_=f*r,p=this._bufferManager.createRawBuffer(_,kt.MapRead|kt.CopyDst,void 0,"TempBufferForReadPixels"+(e.label?"_"+e.label:"")),g=this._device.createCommandEncoder({});return g.copyTextureToBuffer({texture:e,mipLevel:l,origin:{x:t,y:i,z:Math.max(o,0)}},{buffer:p,offset:0,bytesPerRow:f},{width:s,height:r,depthOrArrayLayers:1}),this._device.queue.submit([g.finish()]),this._bufferManager.readDataFromBuffer(p,_,s,r,d,f,vt.GetTextureTypeFromFormat(n),0,h,!0,c)}releaseTexture(e){if(vt.IsInternalTexture(e)){const t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){const[t,i]=this._deferredReleaseTextures[e];t&&(vt.IsHardwareTexture(t)?t.release():t.destroy()),i==null||i.dispose()}this._deferredReleaseTextures.length=0}}class $0 extends ko{constructor(e,t=0){super(),this.engineId=-1,this.capacity=t,this._buffer=e}get underlyingResource(){return this._buffer}}class of{static _IsGPUBuffer(e){return e.underlyingResource===void 0}static _FlagsToString(e,t=""){let i=t;for(let s=0;s<=9;++s)e&1<<s&&(i&&(i+="_"),i+=kt[1<<s]);return i}constructor(e,t){this._deferredReleaseBuffers=[],this._engine=e,this._device=t}createRawBuffer(e,t,i=!1,s){const r=e.byteLength!==void 0?e.byteLength+3&-4:e+3&-4,n={label:"BabylonWebGPUDevice"+this._engine.uniqueId+"_"+of._FlagsToString(t,s??"Buffer")+"_size"+r,mappedAtCreation:i,size:r,usage:t};return this._device.createBuffer(n)}createBuffer(e,t,i){const s=e.byteLength!==void 0,r=this.createRawBuffer(e,t,void 0,i),n=new $0(r);return n.references=1,n.capacity=s?e.byteLength:e,n.engineId=this._engine.uniqueId,s&&this.setSubData(n,0,e),n}setRawData(e,t,i,s,r){this._device.queue.writeBuffer(e,t,i.buffer,s,r)}setSubData(e,t,i,s=0,r=0){const n=e.underlyingResource;r=r||i.byteLength,r=Math.min(r,e.capacity-t);let o=i.byteOffset+s,l=o+r;const h=r+3&-4;if(h!==r){const d=new Uint8Array(i.buffer.slice(o,l));i=new Uint8Array(h),i.set(d),s=0,o=0,l=h,r=h}const c=1024*1024*15;let u=0;for(;l-(o+u)>c;)this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,c),u+=c;this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,r-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=Mn(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,l=0,h=null,c=!0,u=!1){const d=o===1?2:o===2?1:0,f=this._engine.uniqueId;return new Promise((_,p)=>{e.mapAsync(Oo.Read,l,t).then(()=>{const g=e.getMappedRange(l,t);let x=h;if(u)x===null?x=np(o,t,!0,g):x=np(o,x.buffer,void 0,g);else if(x===null)switch(d){case 0:x=new Uint8Array(t),x.set(new Uint8Array(g));break;case 1:x=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g);break;case 2:x=new Float32Array(t/4),x.set(new Float32Array(g));break}else switch(d){case 0:x=new Uint8Array(x.buffer),x.set(new Uint8Array(g));break;case 1:x=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,g,h);break;case 2:x=new Float32Array(x.buffer),x.set(new Float32Array(g));break}if(r!==n){d===1&&!u&&(r*=2,n*=2);const T=new Uint8Array(x.buffer);let S=r,C=0;for(let v=1;v<s;++v){C=v*n;for(let b=0;b<r;++b)T[S++]=T[C++]}d!==0&&!u?x=new Float32Array(T.buffer,0,S/4):x=new Uint8Array(T.buffer,0,S)}e.unmap(),c&&this.releaseBuffer(e),_(x)},g=>{this._engine.isDisposed||this._engine.uniqueId!==f?_(new Uint8Array):p(g)})})}releaseBuffer(e){return of._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}}const K0=[0,0,3,7,0,2,6,2,4,1,5,3,1],j0=[0,64,32,96,16,80,48,112,8],q0=[0,128,128,0,0,0,0,128,0,0,0,0,128];class yo{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){const t=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1;return K0[e.samplingMode]+j0[(e._comparisonFunction||514)-512+1]+q0[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=ct.Linear,s=ct.Linear,r=ct.Nearest,l||(n=o=0);break;case 3:case 3:i=ct.Linear,s=ct.Linear,l?r=ct.Linear:(r=ct.Nearest,n=o=0);break;case 8:i=ct.Nearest,s=ct.Nearest,l?r=ct.Linear:(r=ct.Nearest,n=o=0);break;case 4:i=ct.Nearest,s=ct.Nearest,r=ct.Nearest,l||(n=o=0);break;case 5:i=ct.Nearest,s=ct.Linear,r=ct.Nearest,l||(n=o=0);break;case 6:i=ct.Nearest,s=ct.Linear,l?r=ct.Linear:(r=ct.Nearest,n=o=0);break;case 7:i=ct.Nearest,s=ct.Linear,r=ct.Nearest,n=o=0;break;case 1:case 1:i=ct.Nearest,s=ct.Nearest,r=ct.Nearest,n=o=0;break;case 9:i=ct.Linear,s=ct.Nearest,r=ct.Nearest,l||(n=o=0);break;case 10:i=ct.Linear,s=ct.Nearest,l?r=ct.Linear:(r=ct.Nearest,n=o=0);break;case 2:case 2:i=ct.Linear,s=ct.Linear,r=ct.Nearest,n=o=0;break;case 12:i=ct.Linear,s=ct.Nearest,r=ct.Nearest,n=o=0;break;default:i=ct.Nearest,s=ct.Nearest,r=ct.Nearest,n=o=0;break}return t>1&&(n!==0||o!==0)&&r!==ct.Nearest?{magFilter:ct.Linear,minFilter:ct.Linear,mipmapFilter:ct.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return ml.Repeat;case 0:return ml.ClampToEdge;case 2:return ml.MirrorRepeat}return ml.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?yo.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return ms.Always;case 514:return ms.Equal;case 516:return ms.Greater;case 518:return ms.GreaterEqual;case 513:return ms.Less;case 515:return ms.LessEqual;case 512:return ms.Never;case 517:return ms.NotEqual;default:return ms.Less}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(yo._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=yo.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(yo._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var Mi;(function(a){a[a.StencilReadMask=0]="StencilReadMask",a[a.StencilWriteMask=1]="StencilWriteMask",a[a.DepthBias=2]="DepthBias",a[a.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",a[a.DepthStencilState=4]="DepthStencilState",a[a.MRTAttachments1=5]="MRTAttachments1",a[a.MRTAttachments2=6]="MRTAttachments2",a[a.RasterizationState=7]="RasterizationState",a[a.ColorStates=8]="ColorStates",a[a.ShaderStage=9]="ShaderStage",a[a.TextureStage=10]="TextureStage",a[a.VertexState=11]="VertexState",a[a.NumStates=12]="NumStates"})(Mi||(Mi={}));const Md={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},ll={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},Q0={[y.PositionKind]:!0,[y.NormalKind]:!0,[y.TangentKind]:!0,[y.UVKind]:!0,[y.UV2Kind]:!0,[y.UV3Kind]:!0,[y.UV4Kind]:!0,[y.UV5Kind]:!0,[y.UV6Kind]:!0,[y.ColorKind]:!0,[y.ColorInstanceKind]:!0,[y.MatricesIndicesKind]:!0,[y.MatricesWeightsKind]:!0,[y.MatricesIndicesExtraKind]:!0,[y.MatricesWeightsExtraKind]:!0};class ni{static _IsSignedType(e){switch(e){case y.BYTE:case y.SHORT:case y.INT:case y.FLOAT:return!0;case y.UNSIGNED_BYTE:case y.UNSIGNED_SHORT:case y.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[N.BGRA8Unorm],this.setColorFormat(N.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(N.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=vt.GetSample(i),this.disabled){const n=ni._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,i),ni.NumCacheMiss++,ni._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,ni.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return ni.NumCacheHitWithHash++,this._parameter.pipeline;const r=ni._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),ni.NumCacheMiss++,ni._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){ni.NumPipelineCreationLastFrame=ni._NumPipelineCreationCurrentFrame,ni._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(l??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[Mi.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[Mi.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Un[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i<e.length;++i)e[i]!==0&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.MRTAttachments1))}setMRT(e,t){if(t=t??e.length,t>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o<t;++o){const l=e[o],h=l==null?void 0:l._hardwareTexture;this._mrtFormats[n]=(h==null?void 0:h.format)??this._webgpuColorFormat[0],i[s]+=Un[this._mrtFormats[n]??""]<<r,r+=6,n++,r>=32&&(r=0,s++)}this._mrtFormats.length=n,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[Mi.MRTAttachments1]=i[0],this._states[Mi.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=e===void 0?0:Un[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=e===null?1:ll[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:ll[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:ll[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[Mi.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[Mi.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:ll[i],this._stencilFrontPassOp=s===null?2:ll[s],this._stencilFrontFailOp=r===null?1:ll[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return Tr.TriangleList;case 2:return Tr.PointList;case 1:return Tr.LineList;case 3:return Tr.PointList;case 4:return Tr.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Tr.LineStrip;case 7:return Tr.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return Tr.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return Oa.Add;case 32778:return Oa.Subtract;case 32779:return Oa.ReverseSubtract;case 32775:return Oa.Min;case 32776:return Oa.Max;default:return Oa.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return Ns.Zero;case 1:return Ns.One;case 768:return Ns.Src;case 769:return Ns.OneMinusSrc;case 770:return Ns.SrcAlpha;case 771:return Ns.OneMinusSrcAlpha;case 772:return Ns.DstAlpha;case 773:return Ns.OneMinusDstAlpha;case 774:return Ns.Dst;case 775:return Ns.OneMinusDst;case 776:return Ns.SrcAlphaSaturated;case 32769:return Ns.Constant;case 32770:return Ns.OneMinusConstant;case 32771:return Ns.Constant;case 32772:return Ns.OneMinusConstant;default:return Ns.One}}static _GetCompareFunction(e){switch(e){case 0:return ms.Never;case 1:return ms.Less;case 2:return ms.Equal;case 3:return ms.LessEqual;case 4:return ms.Greater;case 5:return ms.NotEqual;case 6:return ms.GreaterEqual;case 7:return ms.Always}return ms.Never}static _GetStencilOpFunction(e){switch(e){case 0:return hn.Zero;case 1:return hn.Keep;case 2:return hn.Replace;case 3:return hn.IncrementClamp;case 4:return hn.DecrementClamp;case 5:return hn.Invert;case 6:return hn.IncrementWrap;case 7:return hn.DecrementWrap}return hn.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case y.BYTE:switch(s){case 1:case 2:return i?ci.Snorm8x2:ci.Sint8x2;case 3:case 4:return i?ci.Snorm8x4:ci.Sint8x4}break;case y.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?ci.Unorm8x2:ci.Uint8x2;case 3:case 4:return i?ci.Unorm8x4:ci.Uint8x4}break;case y.SHORT:switch(s){case 1:case 2:return i?ci.Snorm16x2:ci.Sint16x2;case 3:case 4:return i?ci.Snorm16x4:ci.Sint16x4}break;case y.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?ci.Unorm16x2:ci.Uint16x2;case 3:case 4:return i?ci.Unorm16x4:ci.Uint16x4}break;case y.INT:switch(s){case 1:return ci.Sint32;case 2:return ci.Sint32x2;case 3:return ci.Sint32x3;case 4:return ci.Sint32x4}break;case y.UNSIGNED_INT:switch(s){case 1:return ci.Uint32;case 2:return ci.Uint32x2;case 3:return ci.Uint32x3;case 4:return ci.Uint32x4}break;case y.FLOAT:switch(s){case 1:return ci.Float32;case 2:return ci.Float32x2;case 3:return ci.Float32x3;case 4:return ci.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:ni._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:ni._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:ni._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:ni._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:ni._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:ni._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[Mi.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,r=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,o=i-1+(s<<1)+(r<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[Mi.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((this._alphaBlendFuncParams[0]===null?2:Md[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:Md[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:Md[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:Md[this._alphaBlendFuncParams[3]])<<12)+((this._alphaBlendEqParams[0]===null?1:this._alphaBlendEqParams[0]-32773)<<16)+((this._alphaBlendEqParams[1]===null?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[Mi.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[Mi.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.DepthStencilState))}_setVertexState(e){var h;const t=this._statesLength;let i=Mi.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,l=0;for(let c=0;c<r.length;c++){const u=n[c];let d=(this._overrideVertexBuffers&&this._overrideVertexBuffers[r[c]])??this._vertexBuffers[r[c]];d||(d=this._emptyVertexBuffer);const f=(h=d.effectiveBuffer)==null?void 0:h.underlyingResource;if(d._validOffsetRange===void 0){const p=d.effectiveByteOffset,g=d.getSize(!0),x=d.effectiveByteStride;d._validOffsetRange=p+g<=this._kMaxVertexBufferStride&&x===0||x!==0&&p+g<=x}o&&o===f&&d._validOffsetRange||(this.vertexBuffers[l++]=d,o=d._validOffsetRange?f:null);const _=d.hashCode+(u<<7);this._isDirty=this._isDirty||this._states[i]!==_,this._states[i++]=_}this.vertexBuffers.length=l,this._statesLength=i,this._isDirty=this._isDirty||i!==t,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[Mi.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Mi.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);const t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries;for(let s=0;s<i.length;s++){const r=i[s];t[s]=this._device.createBindGroupLayout({entries:r})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){const t=e.shaderProcessingContext,i=t.bindGroupLayoutEntries;let s=1;for(let n=0;n<i.length;n++){const o=i[n];for(let l=0;l<o.length;l++){const h=i[n][l];if(h.texture){const c=t.bindGroupLayoutEntryInfo[n][h.binding].name,u=t.availableTextures[c],d=u.autoBindSampler?t.availableSamplers[c+ai.AutoSamplerSuffix]:null;let f=u.sampleType,_=(d==null?void 0:d.type)??io.Filtering;if(this._textureState&s&&f!==br.Depth&&(u.autoBindSampler&&(_=io.NonFiltering),f=br.UnfilterableFloat),h.texture.sampleType=f,d){const p=t.bindGroupLayoutEntryInfo[d.binding.groupIndex][d.binding.bindingIndex].index;i[d.binding.groupIndex][p].sampler.type=_}s=s<<1}}}const r=[];for(let n=0;n<i.length;++n)r[n]=this._device.createBindGroupLayout({entries:i[n]});return e.bindGroupLayouts[this._textureState]=r,this._device.createPipelineLayout({bindGroupLayouts:r})}_getVertexInputDescriptor(e){var l;const t=[],i=e._pipelineContext,s=i.shaderProcessingContext.attributeNamesFromEffect,r=i.shaderProcessingContext.attributeLocationsFromEffect;let n,o;for(let h=0;h<s.length;h++){const c=r[h];let u=(this._overrideVertexBuffers&&this._overrideVertexBuffers[s[h]])??this._vertexBuffers[s[h]];u||(u=this._emptyVertexBuffer);let d=(l=u.effectiveBuffer)==null?void 0:l.underlyingResource,f=u.effectiveByteOffset;const _=!u._validOffsetRange;if(!(n&&o&&n===d)||_){const p={arrayStride:u.effectiveByteStride,stepMode:u.getIsInstanced()?rf.Instance:rf.Vertex,attributes:[]};t.push(p),o=p.attributes,_&&(f=0,d=null)}o.push({shaderLocation:c,offset:f,format:ni._GetVertexInputDescriptorFormat(u)}),n=d}return t}_processNonFloatVertexBuffers(e,t){const i=e.engine._getShaderProcessor(e.shaderProcessingContext.shaderLanguage);let s=!1;for(const r in this._vertexBuffers){const n=this._vertexBuffers[r];if(!n||!Q0[r])continue;const o=n.normalized?y.FLOAT:n.type,l=e.vertexBufferKindToType[r];(o!==y.FLOAT&&l===void 0||l!==void 0&&l!==o)&&(s=!0,e.vertexBufferKindToType[r]=o,o!==y.FLOAT&&(i.vertexBufferKindToNumberOfComponents[r]=y.DeduceStride(r),ni._IsSignedType(o)&&(i.vertexBufferKindToNumberOfComponents[r]*=-1)))}s&&t._processShaderCode(i,!0)}_createRenderPipeline(e,t,i){var f;const s=e._pipelineContext,r=this._getVertexInputDescriptor(e),n=this._createPipelineLayout(s),o=[],l=this._getAphaBlendState(),h=this._getColorBlendState();if(this._processNonFloatVertexBuffers(s,e),this._mrtAttachments1>0)for(let _=0;_<this._mrtFormats.length;++_){const p=this._mrtFormats[_];if(p){const g={format:p,writeMask:this._mrtEnabledMask&1<<_?this._writeMask:0};l&&h&&(g.blend={alpha:l,color:h}),o.push(g)}else o.push(null)}else if(this._webgpuColorFormat[0]){const _={format:this._webgpuColorFormat[0],writeMask:this._writeMask};l&&h&&(_.blend={alpha:l,color:h}),o.push(_)}else o.push(null);const c={compare:ni._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:ni._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:ni._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:ni._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)};let u;(t===Tr.LineStrip||t===Tr.TriangleStrip)&&(u=!this._indexBuffer||this._indexBuffer.is32Bits?so.Uint32:so.Uint16);const d=this._webgpuDepthStencilFormat?vt.HasStencilAspect(this._webgpuDepthStencilFormat):!1;return this._device.createRenderPipeline({label:`RenderPipeline_${((f=o[0])==null?void 0:f.format)??"nooutput"}_${this._webgpuDepthStencilFormat??"nodepth"}_samples${i}_textureState${this._textureState}`,layout:n,vertex:{module:s.stages.vertexStage.module,entryPoint:s.stages.vertexStage.entryPoint,buffers:r},primitive:{topology:t,stripIndexFormat:u,frontFace:this._frontFace===1?sf.CCW:sf.CW,cullMode:this._cullEnabled?this._cullFace===2?Jc.Front:Jc.Back:Jc.None},fragment:s.stages.fragmentStage?{module:s.stages.fragmentStage.module,entryPoint:s.stages.fragmentStage.entryPoint,targets:o}:void 0,multisample:{count:i},depthStencil:this._webgpuDepthStencilFormat===void 0?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?ni._GetCompareFunction(this._depthCompare):ms.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&d?c:void 0,stencilBack:this._stencilEnabled&&d?c:void 0,stencilReadMask:this._stencilEnabled&&d?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&d?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})}}ni.NumCacheHitWithoutHash=0;ni.NumCacheHitWithHash=0;ni.NumCacheMiss=0;ni.NumPipelineCreationLastFrame=0;ni._NumPipelineCreationCurrentFrame=0;class dp{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(const i in this.values){const s=this.values[i],[r,n]=s.count();e+=r,t+=n,e++}return[e,t]}}class fn extends ni{static GetNodeCounts(){const e=fn._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,i,s){if(e.pipeline){const r=i.slice();r.length=s,t.push(r)}for(const r in e.values){const n=e.values[r];i[s]=parseInt(r),fn._GetPipelines(n,t,i,s+1)}}static GetPipelines(){const e=[];return fn._GetPipelines(fn._Cache,e,[],0),e}static ResetCache(){fn._Cache=new dp}reset(){this._nodeStack=[],this._nodeStack[0]=fn._Cache,super.reset()}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let i=this._stateDirtyLowestIndex;i<this._statesLength;++i){let s=t.values[this._states[i]];s||(s=new dp,t.values[this._states[i]]=s),t=s,this._nodeStack[i+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}}fn._Cache=new dp;class Z0 extends bE{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){var t;const e=(t=this.stencilMaterial)==null?void 0:t.enabled;this.enabled=e?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=e?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=e?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=e?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=e?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=e?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=e?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=e?this.stencilMaterial.mask:this.stencilGlobal.mask)}}class J0 extends SE{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(e??1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(e??2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}}class MS{static IsExternalTexture(e){return e.underlyingResource!==void 0}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=16,this.format=4294967295,this._video=e,this.uniqueId=Tt._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}}class qf{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=qf._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?yo.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){var n;let i=this.textures[e],s=-1;i?s=((n=i.texture)==null?void 0:n.uniqueId)??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,i.isExternalTexture=MS.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==((t==null?void 0:t.uniqueId)??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}qf._Counter=0;class Qf{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,kt.CopyDst|kt.Indirect|kt.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Qf._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])==null?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Qf._Counter=0;class Xc{constructor(){this.values={}}}class Bt{static get Statistics(){return{totalCreated:Bt.NumBindGroupsCreatedTotal,lastFrameCreated:Bt.NumBindGroupsCreatedLastFrame,lookupLastFrame:Bt.NumBindGroupsLookupLastFrame,noLookupLastFrame:Bt.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Bt._Cache=new Xc,Bt.NumBindGroupsCreatedTotal=0,Bt.NumBindGroupsCreatedLastFrame=0,Bt.NumBindGroupsLookupLastFrame=0,Bt.NumBindGroupsNoLookupLastFrame=0,Bt._NumBindGroupsCreatedCurrentFrame=0,Bt._NumBindGroupsLookupCurrentFrame=0,Bt._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Bt.NumBindGroupsCreatedLastFrame=Bt._NumBindGroupsCreatedCurrentFrame,Bt.NumBindGroupsLookupLastFrame=Bt._NumBindGroupsLookupCurrentFrame,Bt.NumBindGroupsNoLookupLastFrame=Bt._NumBindGroupsNoLookupCurrentFrame,Bt._NumBindGroupsCreatedCurrentFrame=0,Bt._NumBindGroupsLookupCurrentFrame=0,Bt._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var l,h,c,u,d,f;let s,r=Bt._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Bt._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const _ of e.shaderProcessingContext.bufferNames){const p=((l=t.buffers[_])==null?void 0:l.uniqueId)??0;let g=r.values[p];g||(g=new Xc,r.values[p]=g),r=g}for(const _ of e.shaderProcessingContext.samplerNames){const p=((h=i.samplers[_])==null?void 0:h.hashCode)??0;let g=r.values[p];g||(g=new Xc,r.values[p]=g),r=g}for(const _ of e.shaderProcessingContext.textureNames){const p=((u=(c=i.textures[_])==null?void 0:c.texture)==null?void 0:u.uniqueId)??0;let g=r.values[p];g||(g=new Xc,r.values[p]=g),r=g}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Bt._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),Bt.NumBindGroupsCreatedTotal++,Bt._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let _=0;_<e.shaderProcessingContext.bindGroupLayoutEntries.length;_++){const p=e.shaderProcessingContext.bindGroupLayoutEntries[_],g=e.shaderProcessingContext.bindGroupEntries[_];for(let T=0;T<p.length;T++){const S=e.shaderProcessingContext.bindGroupLayoutEntries[_][T],C=e.shaderProcessingContext.bindGroupLayoutEntryInfo[_][S.binding],v=C.nameInArrayOfTexture??C.name;if(S.sampler){const b=i.samplers[v];if(b){const A=b.sampler;if(!A){this._engine.dbgSanityChecks&&O.Error(`Trying to bind a null sampler! entry=${JSON.stringify(S)}, name=${v}, bindingInfo=${JSON.stringify(b,(P,L)=>P==="texture"?"<no dump>":L)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[T].resource=this._cacheSampler.getSampler(A,!1,b.hashCode,A.label)}else O.Error(`Sampler "${v}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(A,P)=>A==="texture"||A==="sampler"?"<no dump>":P)}`,50)}else if(S.texture||S.storageTexture){const b=i.textures[v];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){O.Error(`Trying to bind a null texture! entry=${JSON.stringify(S)}, bindingInfo=${JSON.stringify(b,(P,L)=>P==="texture"?"<no dump>":L)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const A=b.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!A||S.texture&&!A.view||S.storageTexture&&!A.viewForWriting)){O.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(S)}, name=${v}, bindingInfo=${JSON.stringify(b,(P,L)=>P==="texture"?"<no dump>":L)}, isReady=${(d=b.texture)==null?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[T].resource=S.storageTexture?A.viewForWriting:A.view}else O.Error(`Texture "${v}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(A,P)=>A==="texture"||A==="sampler"?"<no dump>":P)}`,50)}else if(S.externalTexture){const b=i.textures[v];if(b){if(this._engine.dbgSanityChecks&&b.texture===null){O.Error(`Trying to bind a null external texture! entry=${JSON.stringify(S)}, name=${v}, bindingInfo=${JSON.stringify(b,(P,L)=>P==="texture"?"<no dump>":L)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const A=b.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!A){O.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(S)}, name=${v}, bindingInfo=${JSON.stringify(b,(P,L)=>P==="texture"?"<no dump>":L)}, isReady=${(f=b.texture)==null?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}g[T].resource=this._device.importExternalTexture({source:A})}else O.Error(`Texture "${v}" could not be bound. entry=${JSON.stringify(S)}, materialContext=${JSON.stringify(i,(A,P)=>A==="texture"||A==="sampler"?"<no dump>":P)}`,50)}else if(S.buffer){const b=t.buffers[v];if(b){const A=b.underlyingResource;g[T].resource.buffer=A,g[T].resource.size=b.capacity}else O.Error(`Can't find buffer "${v}". entry=${JSON.stringify(S)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const x=o[_];s[_]=this._device.createBindGroup({layout:x,entries:g})}return s}}Bt.NumBindGroupsCreatedTotal=0;Bt.NumBindGroupsCreatedLastFrame=0;Bt.NumBindGroupsLookupLastFrame=0;Bt.NumBindGroupsNoLookupLastFrame=0;Bt._Cache=new Xc;Bt._NumBindGroupsCreatedCurrentFrame=0;Bt._NumBindGroupsLookupCurrentFrame=0;Bt._NumBindGroupsNoLookupCurrentFrame=0;const eP="clearQuadVertexShader",tP=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0),
vec2(1.0,1.0),
vec2(-1.0,-1.0),
vec2(1.0,-1.0)};
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
gl_Position=vec4(pos[gl_VertexID],depthValue,1.0);
#define CUSTOM_VERTEX_MAIN_END
}
`;W.ShadersStore[eP]=tP;const iP="clearQuadPixelShader",sP=`uniform vec4 color;void main() {gl_FragColor=color;}
`;W.ShadersStore[iP]=sP;class rP{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new fn(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,s,r=1){let n,o=null,l;const h=!!this._engine._currentRenderTarget;if(e)n=e;else{let g=0;this._keyTemp.length=0;for(let T=0;T<this._cacheRenderPipeline.colorFormats.length;++T)this._keyTemp[g++]=Un[this._cacheRenderPipeline.colorFormats[T]??""];const x=Un[this._depthTextureFormat??0];if(this._keyTemp[g]=(t?t.r+t.g*256+t.b*256*256+t.a*256*256*256:0)+(i?2**32:0)+(s?2**33:0)+(this._engine.useReverseDepthBuffer?2**34:0)+(h?2**35:0)+(r>1?2**36:0)+x*2**37,l=this._keyTemp.join("_"),o=this._bundleCache[l],o)return o;n=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:vt.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&vt.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const d=h?this._engine._ubInvertY:this._engine._ubDontInvertY,f=u.uniformBuffer.getBuffer(),_=f.uniqueId+"-"+d.uniqueId;let p=this._bindGroups[_];if(!p){const g=u.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({layout:g[0],entries:[]})),Lr._SimplifiedKnownBindings||p.push(this._device.createBindGroup({layout:g[1],entries:[]})),p.push(this._device.createBindGroup({layout:g[Lr._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:d.underlyingResource,size:d.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}n.setPipeline(c);for(let g=0;g<p.length;++g)n.setBindGroup(g,p[g]);return n.draw(4,1,0,0),e||(o=n.finish(),this._bundleCache[l]=o),o}}class Jm{constructor(e,t,i,s){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(s)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new Jm(this.x,this.y,this.w,this.h)}}class eg{constructor(e,t,i,s){this.x=e,this.y=t,this.w=i,this.h=s}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new eg(this.x,this.y,this.w,this.h)}}class lf{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new lf(this.ref)}}class tg{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new tg(this.color)}}class ig{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new ig(this.query)}}class sg{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new sg}}class rg{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){const e=new rg;return e.bundles=this.bundles,e}}class ng{constructor(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){const t=new rg;this._list[this._listLength++]=t,this._currentBundleList=t.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:vt.GetSample(i)})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();const e=new ng(this._device);e._list=new Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}}class DS{get querySet(){return this._querySet}constructor(e,t,i,s,r,n=!0,o){this._dstBuffers=[],this._engine=e,this._device=s,this._bufferManager=r,this._count=t,this._canUseMultipleBuffers=n,this._querySet=s.createQuerySet({label:o??"QuerySet",type:i,count:t}),this._queryBuffer=r.createRawBuffer(8*t,kt.QueryResolve|kt.CopySrc,void 0,"QueryBuffer"),n||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,kt.MapRead|kt.CopyDst,void 0,"QueryBufferNoMultipleBuffers"))}_getBuffer(e,t){if(!this._canUseMultipleBuffers&&this._dstBuffers.length===0)return null;const i=this._device.createCommandEncoder();let s;return this._dstBuffers.length===0?s=this._bufferManager.createRawBuffer(8*this._count,kt.MapRead|kt.CopyDst,void 0,"QueryBufferAdditionalBuffer"):(s=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),i.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),i.copyBufferToBuffer(this._queryBuffer,0,s,0,8*t),this._device.queue.submit([i.finish()]),s}async readValues(e=0,t=1){const i=this._getBuffer(e,t);if(i===null)return null;const s=this._engine.uniqueId;return i.mapAsync(Oo.Read).then(()=>{const r=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,r},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw r})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(Oo.Read).then(()=>{const s=new BigUint64Array(t.getMappedRange()),r=Number(s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(Oo.Read).then(()=>{const s=new BigUint64Array(t.getMappedRange()),r=Number(s[1]-s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}}class nP{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t,i){this._enabled=!1,this._gpuFrameTimeCounter=new wr,this._measureDurationState=0,this._engine=e,this._device=t,this._bufferManager=i}get enable(){return this._enabled}set enable(e){if(this._enabled!==e)if(this._enabled=e,this._measureDurationState=0,e)try{this._measureDuration=new aP(this._engine,this._device,this._bufferManager,2e3,"QuerySet_TimestampQuery")}catch(t){this._enabled=!1,O.Error(`Could not create a WebGPUDurationMeasure!
Error: `+t.message+`
Make sure timestamp query is supported and enabled in your browser.`);return}else this._measureDuration.dispose()}startFrame(e){this._enabled&&this._measureDurationState===0&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){this._measureDurationState===1&&(this._measureDurationState=2,this._measureDuration.stop(e).then(t=>{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class aP{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new DS(e,s,nf.Timestamp,t,i,!0,r)}start(e){var t;(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class oP{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet!==void 0;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){this._availableIndices.length===0&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length}getQueryResult(e){var t;return Number(((t=this._lastBuffer)==null?void 0:t[e])??-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer!==this._engine.frameId&&(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(e=>{this._lastBuffer=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new DS(this._engine,this._currentTotalIndices,nf.Occlusion,this._device,this._bufferManager,!1,"QuerySet_OcclusionQuery_count_"+this._currentTotalIndices),this._frameQuerySetIsDirty=this._engine.frameId}_delayQuerySetDispose(){const e=this._querySet;e&&setTimeout(()=>e.dispose,1e3)}dispose(){var e;(e=this._querySet)==null||e.dispose(),this._availableIndices.length=0}}class Er{async initTwgsl(e){if(!Er._Twgsl)return e=e||{},e={...Er._TWgslDefaultOptions,...e},e.twgsl?(Er._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await X.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Er._Twgsl=await self.twgsl(X.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Er._Twgsl.convertSpirV2WGSL(e,Er.DisableUniformityAnalysis||t);return Er.ShowWGSLShaderCode&&(O.Log(i),O.Log("***********************************************")),Er.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity);
`+i:i}}Er._TWgslDefaultOptions={jsPath:`${X._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${X._DefaultCdnUrl}/twgsl/twgsl.wasm`};Er.ShowWGSLShaderCode=!1;Er.DisableUniformityAnalysis=!1;Er._Twgsl=null;class lP{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===1&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}const hP="postprocessVertexShader",cP=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}
`;W.ShadersStoreWGSL[hP]=cP;const Yx={label:"TextureView_SwapChain_ResolveTarget",dimension:tn.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},$x={label:"TextureView_SwapChain",dimension:tn.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Dd="/* disable_uniformity_analysis */",uP=new xe;class Ze extends H{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return this._cacheSampler?this._cacheSampler.disabled:!1}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return O.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new zm:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Ze(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){if(super(null,t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,O.Log(`Babylon.js v${H.Version} - ${this.description} engine`),!navigator.gpu){O.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new JI,this._shaderProcessorWGSL=new w0}initAsync(e,t){var i;return this.uniqueId=Ze._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??((i=this._options)==null?void 0:i.glslangOptions)).then(s=>{var r;return this._glslang=s,this._tintWASM=Ze.UseTWGSL?new Er:null,this._tintWASM?this._tintWASM.initTwgsl(t??((r=this._options)==null?void 0:r.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options)):navigator.gpu.requestAdapter(this._options)}).then(s=>{var r;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(r=this._adapter.features)==null||r.forEach(l=>this._adapterSupportedExtensions.push(l)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(l=>{this._adapterInfo=l});const n=this._options.deviceDescriptor??{},o=(n==null?void 0:n.requiredFeatures)??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(o){const l=o,h=[];for(const c of l)this._adapterSupportedExtensions.indexOf(c)!==-1&&h.push(c);n.requiredFeatures=h}if(this._options.setMaximumLimits&&!n.requiredLimits){n.requiredLimits={};for(const l in this._adapterSupportedLimits)l==="minSubgroupSize"||l==="maxSubgroupSize"||(n.requiredLimits[l]=this._adapterSupportedLimits[l])}return n.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(n)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var n,o;this._device=s,this._deviceEnabledExtensions=[],(n=this._device.features)==null||n.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let r=-1;this._device.addEventListener("uncapturederror",l=>{++r<this.numMaxUncapturedErrors?O.Warn(`WebGPU uncaptured error (${r+1}): ${l.error} - ${l.error.message}`):r++===this.numMaxUncapturedErrors&&O.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)}),this._doNotHandleContextLost||(o=this._device.lost)==null||o.then(l=>{this._isDisposed||(this._contextWasLost=!0,O.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var p,g;const h=this.snapshotRenderingMode,c=this.snapshotRendering,u=this.disableCacheSamplers,d=this.disableCacheRenderPipelines,f=this.disableCacheBindGroups,_=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??((p=this._options)==null?void 0:p.glslangOptions),this._twgslOptions??((g=this._options)==null?void 0:g.twgslOptions)),this.snapshotRenderingMode=h,this.snapshotRendering=c,this.disableCacheSamplers=u,this.disableCacheRenderPipelines=d,this.disableCacheBindGroups=f,this.enableGPUTimingMeasurements=_,this._currentRenderPass=null}))})}).then(()=>{this._bufferManager=new of(this,this._device),this._textureHelper=new Y0(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new yo(this._device),this._cacheBindGroups=new Bt(this._device,this._cacheSampler,this),this._timestampQuery=new nP(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new oP(this,this._device,this._bufferManager):void 0,this._bundleList=new ng(this._device),this._snapshotRendering=new lP(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),kt.Uniform|kt.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),kt.Uniform|kt.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,O.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new y(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new fn(this._device,this._emptyVertexBuffer),this._depthCullingState=new J0(this._cacheRenderPipeline),this._stencilStateComposer=new Z0(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new rP(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(s=>{throw O.Error("A fatal error occurred during WebGPU creation/initialization."),s})}_initGlslang(e){return e=e||{},e={...Ze._GLSLslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?X.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(X.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage*2,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(Fn.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(Fn.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Fn.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(Fn.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(Fn.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Fn.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:typeof BigUint64Array<"u"&&this._deviceEnabledExtensions.indexOf(Fn.TimestampQuery)!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array<"u",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new Hd],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e);let t;if(this._options.antialias){const r={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tn.E2d,format:this._options.swapChainFormat,usage:ri.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(r),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:tn.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new xe(0,0,0,1),loadOp:Ki.Clear,storeOp:Mr.Store}]}else t=[{view:void 0,clearValue:new xe(0,0,0,1),loadOp:Ki.Clear,storeOp:Mr.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?N.Depth24PlusStencil8:N.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tn.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ri.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:tn.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Ki.Clear,depthStoreOp:Mr.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Ki.Clear:void 0,stencilStoreOp:this.isStencilEnable?Mr.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ri.RenderAttachment|ri.CopySrc,alphaMode:this.premultipliedAlpha?af.Premultiplied:af.Opaque})}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){fn.ResetCache(),Bt.ResetCache();const t=s=>{var r;for(const n of s){for(const o of n.meshes){const l=o.subMeshes;if(l)for(const h of l)h._drawWrappers=[]}for(const o of n.materials)(r=o._materialContext)==null||r.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const s of this._uniformBuffers)s.name.indexOf("leftOver")<0&&i.push(s);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - setSize -",e,t])),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0):!1}_getShaderProcessor(e){return e===Zt.WGSL?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e){return new Lr(e)}_currentPassIsMainPass(){return this._currentRenderTarget===null}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassWrapper(){return this._currentRenderTarget?this._rttRenderPassWrapper:this._mainRenderPassWrapper}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_mustUpdateViewport(){const e=this._viewportCached.x,t=this._viewportCached.y,i=this._viewportCached.z,s=this._viewportCached.w,r=this._viewportsCurrent.x!==e||this._viewportsCurrent.y!==t||this._viewportsCurrent.w!==i||this._viewportsCurrent.h!==s;return r&&(this._viewportsCurrent.x=this._viewportCached.x,this._viewportsCurrent.y=this._viewportCached.y,this._viewportsCurrent.w=this._viewportCached.z,this._viewportsCurrent.h=this._viewportCached.w),r}_applyViewport(e){const t=Math.floor(this._viewportCached.x),i=Math.floor(this._viewportCached.z),s=Math.floor(this._viewportCached.w);let r=Math.floor(this._viewportCached.y);this._currentRenderTarget||(r=this.getRenderHeight(!0)-r-s),e?e.addItem(new Jm(t,r,i,s)):this._getCurrentRenderPass().setViewport(t,r,i,s,0,1),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+this._currentPassIsMainPass()]))}_viewport(e,t,i,s){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s}_mustUpdateScissor(){const e=this._scissorCached.x,t=this._scissorCached.y,i=this._scissorCached.z,s=this._scissorCached.w,r=this._scissorsCurrent.x!==e||this._scissorsCurrent.y!==t||this._scissorsCurrent.w!==i||this._scissorsCurrent.h!==s;return r&&(this._scissorsCurrent.x=this._scissorCached.x,this._scissorsCurrent.y=this._scissorCached.y,this._scissorsCurrent.w=this._scissorCached.z,this._scissorsCurrent.h=this._scissorCached.w),r}_applyScissor(e){const t=this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y;e?e.addItem(new eg(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w)):this._getCurrentRenderPass().setScissorRect(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+this._currentPassIsMainPass()]))}_scissorIsActive(){return this._scissorCached.x!==0||this._scissorCached.y!==0||this._scissorCached.z!==0||this._scissorCached.w!==0}enableScissor(e,t,i,s){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=s}disableScissor(){this._scissorCached.x=this._scissorCached.y=this._scissorCached.z=this._scissorCached.w=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0}_mustUpdateStencilRef(){const e=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent;return e&&(this._stencilRefsCurrent=this._stencilStateComposer.funcRef),e}_applyStencilRef(e){e?e.addItem(new lf(this._stencilStateComposer.funcRef??0)):this._getCurrentRenderPass().setStencilReference(this._stencilStateComposer.funcRef??0)}_mustUpdateBlendColor(){const e=this._alphaState._blendConstants,t=e[0]!==this._blendColorsCurrent[0]||e[1]!==this._blendColorsCurrent[1]||e[2]!==this._blendColorsCurrent[2]||e[3]!==this._blendColorsCurrent[3];return t&&(this._blendColorsCurrent[0]=e[0],this._blendColorsCurrent[1]=e[1],this._blendColorsCurrent[2]=e[2],this._blendColorsCurrent[3]=e[3]),t}_applyBlendColor(e){e?e.addItem(new tg(this._alphaState._blendConstants.slice())):this._getCurrentRenderPass().setBlendConstant(this._alphaState._blendConstants)}_resetRenderPassStates(){this._viewportsCurrent.x=this._viewportsCurrent.y=this._viewportsCurrent.w=this._viewportsCurrent.h=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0,this._stencilRefsCurrent=-1,this._blendColorsCurrent[0]=this._blendColorsCurrent[1]=this._blendColorsCurrent[2]=this._blendColorsCurrent[3]=null}clear(e,t,i,s=!1){e&&e.a===void 0&&(e.a=1);const r=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - clear - backBuffer=",t," depth=",i," stencil=",s," scissor is active=",r])),this._currentRenderTarget?r?(this._currentRenderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,s),this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,i,s)):(this._currentRenderPass&&this._endCurrentRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,s)):((!this._currentRenderPass||!r)&&this._startMainRenderPass(!r,t?e:null,i,s),r&&(this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,i,s)))}_clearFullQuad(e,t,i){const s=this.compatibilityMode?this._getCurrentRenderPass():null;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(this._cacheRenderPipeline.mrtAttachments??[],this._cacheRenderPipeline.mrtTextureArray??[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?s.setStencilReference(this._clearStencilValue):this._bundleList.addItem(new lf(this._clearStencilValue));const r=this._clearQuad.clear(s,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(null):(this._bundleList.addBundle(r),this._applyStencilRef(this._bundleList),this._reportDrawCall())}createVertexBuffer(e,t,i){let s;return e instanceof Array?s=new Float32Array(e):e instanceof ArrayBuffer?s=new Uint8Array(e):s=e,this._bufferManager.createBuffer(s,kt.Vertex|kt.CopyDst,i)}createDynamicVertexBuffer(e,t){return this.createVertexBuffer(e,void 0,t)}createIndexBuffer(e,t,i){let s=!0,r;e instanceof Uint32Array||e instanceof Int32Array?r=e:e instanceof Uint16Array?(r=e,s=!1):e.length>65535?r=new Uint32Array(e):(r=new Uint16Array(e),s=!1);const n=this._bufferManager.createBuffer(r,kt.Index|kt.CopyDst,i);return n.is32Bits=s,n}updateDynamicIndexBuffer(e,t,i=0){const s=e;let r;e.is32Bits?r=t instanceof Uint32Array?t:new Uint32Array(t):r=t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(s,i,r)}updateDynamicVertexBuffer(e,t,i,s){const r=e;i===void 0&&(i=0);let n;s===void 0?(t instanceof Array?n=new Float32Array(t):t instanceof ArrayBuffer?n=new Uint8Array(t):n=t,s=n.byteLength):t instanceof Array?n=new Float32Array(t):t instanceof ArrayBuffer?n=new Uint8Array(t):n=t,this._bufferManager.setSubData(r,i,n,0,s)}_createBuffer(e,t,i){let s;e instanceof Array?s=new Float32Array(e):e instanceof ArrayBuffer?s=new Uint8Array(e):s=e;let r=0;return t&1&&(r|=kt.CopySrc),t&2&&(r|=kt.CopyDst),t&4&&(r|=kt.Uniform),t&8&&(r|=kt.Vertex),t&16&&(r|=kt.Index),t&32&&(r|=kt.Storage),this._bufferManager.createBuffer(s,r,i)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}bindBuffers(e,t,i,s){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=s??null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createUniformBuffer(e,t){let i;return e instanceof Array?i=new Float32Array(e):i=e,this._bufferManager.createBuffer(i,kt.Uniform|kt.CopyDst,t)}createDynamicUniformBuffer(e,t){return this.createUniformBuffer(e,t)}updateUniformBuffer(e,t,i,s){i===void 0&&(i=0);const r=e;let n;s===void 0?(t instanceof Float32Array?n=t:n=new Float32Array(t),s=n.byteLength):t instanceof Float32Array?n=t:n=new Float32Array(t),this._bufferManager.setSubData(r,i,n,0,s)}bindUniformBufferBase(e,t,i){this._currentDrawContext.setBuffer(i,e)}bindUniformBlock(){}createEffect(e,t,i,s,r,n,o,l,h,c=Zt.GLSL){const u=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,f=this._getGlobalDefines();let _=r??t.defines??"";f&&(_+=`
`+f);const p=u+"+"+d+"@"+_;if(this._compiledEffects[p]){const x=this._compiledEffects[p];return o&&x.isReady()&&o(x),x}const g=new xt(e,t,i,s,this,r,n,o,l,h,p,c);return this._compiledEffects[p]=g,g}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,i,s){return this._compileRawShaderToSpirV(s+(i?i+`
`:"")+e,t)}_getWGSLShader(e,t,i){return i?i="//"+i.split(`
`).join(`
//`)+`
`:i="",i+e}_createPipelineStageDescriptor(e,t,i,s,r){return this._tintWASM&&i===Zt.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,s),t=this._tintWASM.convertSpirV2WGSL(t,r)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,t,i){const s=e.indexOf(Dd)>=0,r=t.indexOf(Dd)>=0,n=i===Zt.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Zt.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(Dd)>=0,n=t.indexOf(Dd)>=0,o=`#version 450
`,l=s===Zt.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),h=s===Zt.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(l,h,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),c}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Do(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new qI(e,this)}createMaterialContext(){return new qf}createDrawContext(){return new Qf(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(O.Log(["defines",l]),O.Log(t),O.Log(i),O.Log("***********************************************")),h.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},s?h.stages=this._compileRawPipelineStageDescriptor(t,i,c):h.stages=this._compilePipelineStageDescriptor(t,i,l,c)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let r=0;r<t.length;r++){const n=t[r],o=s.shaderProcessingContext.availableAttributes[n];o!==void 0&&(i[r]=o)}return i}enableEffect(e){if(e){if(!Bi.IsWrapper(e))this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&O.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${e.name.vertex}, effect.name.fragment=${e.name.fragment}`,10);else if(!e.effect||e.effect===this._currentEffect&&e.materialContext===this._currentMaterialContext&&e.drawContext===this._currentDrawContext&&!this._forceEnableEffect){if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw O.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the effect property is empty!";return}else if(this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw O.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the materialContext property is empty!";this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!1,this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect)}}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}_deletePipelineContext(e){e&&e.dispose()}get needPOTTextures(){return!1}_createHardwareTexture(){return new Hd}_releaseTexture(e){const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return 5}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,t,i=!0,s=et.Unknown){const r={};t!==void 0&&typeof t=="object"?(r.generateMipMaps=t.generateMipMaps,r.type=t.type===void 0?0:t.type,r.samplingMode=t.samplingMode===void 0?3:t.samplingMode,r.format=t.format===void 0?5:t.format,r.samples=t.samples??1,r.creationFlags=t.creationFlags??0,r.useSRGBBuffer=t.useSRGBBuffer??!1,r.label=t.label):(r.generateMipMaps=t,r.type=0,r.samplingMode=3,r.format=5,r.samples=1,r.creationFlags=0,r.useSRGBBuffer=!1),(r.type===1&&!this._caps.textureFloatLinearFiltering||r.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(r.samplingMode=1),r.type===1&&!this._caps.textureFloat&&(r.type=0,O.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const n=new Tt(this,s),o=e.width||e,l=e.height||e,h=e.layers||0;return n.baseWidth=o,n.baseHeight=l,n.width=o,n.height=l,n.depth=h,n.isReady=!0,n.samples=r.samples,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,n.is2DArray=h>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,l,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,_,p){return this._createTextureBase(e,t,i,s,r,n,o,(g,x,T,S,C,v,b,A)=>{var L;const P=S;if(g.baseWidth=P.width,g.baseHeight=P.height,g.width=P.width,g.height=P.height,g.format=g.format!==-1?g.format:c??5,g.type=g.type!==-1?g.type:0,g._creationFlags=_??0,A(g.width,g.height,P,x,g,()=>{}),(L=g._hardwareTexture)!=null&&L.underlyingResource)!v&&!b&&this._generateMipmaps(g,this._uploadEncoder);else{const w=this._textureHelper.createGPUTextureForInternalTexture(g,P.width,P.height,void 0,_);vt.IsImageBitmap(P)&&(this._textureHelper.updateTexture(P,g,P.width,P.height,g.depth,w.format,0,0,C,!1,0,0),!v&&!b&&this._generateMipmaps(g,this._uploadEncoder))}T&&T.removePendingData(g),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>!1,l,h,c,u,d,f,p)}wrapWebGPUTexture(e){const t=new Hd(e),i=new Tt(this,et.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;e.generateMipMaps&&((t=e._hardwareTexture)!=null&&t.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){const n=i+ai.AutoSamplerSuffix;this._currentMaterialContext.setSampler(n,t)}}}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let r=0;r<i.length;r++)this._setTexture(-1,i[r],!0,!1,s+r.toString(),s)}_setTexture(e,t,i=!1,s=!1,r="",n){if(n=n??r,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(r,null),!1;if(t.video)t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let o=null;if(s?o=t.depthStencilTexture:t.isReady()?o=t.getInternalTexture():t.isCube?o=this.emptyCubeTexture:t.is3D?o=this.emptyTexture3D:t.is2DArray?o=this.emptyTexture2DArray:o=this.emptyTexture,o&&!o.isMultiview){if(o.isCube&&o._cachedCoordinatesMode!==t.coordinatesMode){o._cachedCoordinatesMode=t.coordinatesMode;const l=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=l,t.wrapV=l}o._cachedWrapU=t.wrapU,o._cachedWrapV=t.wrapV,o.is3D&&(o._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,o,t.anisotropicFilteringLevel)}this._setInternalTexture(r,o,n)}else this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t]));return!0}_setAnisotropicLevel(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))}_bindTexture(e,t,i){e!==void 0&&this._setInternalTexture(i,t)}generateMipmaps(e){this._generateMipmaps(e)}_generateMipmaps(e,t){t=t??this._renderEncoder;const i=e._hardwareTexture;if(!i)return;t===this._renderEncoder&&this._endCurrentRenderPass();const s=e._hardwareTexture.format,r=vt.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log("frame #"+this._count+" - generate mipmaps - width="+e.width+", height="+e.height+", isCube="+e.isCube+", command encoder="+(t===this._renderEncoder?"render":"copy"))),e.isCube?this._textureHelper.generateCubeMipmaps(i,s,r,t):this._textureHelper.generateMipmaps(i,s,r,0,t)}updateTextureData(e,t,i,s,r,n,o=0,l=0,h=!1){var d;let c=e._hardwareTexture;(d=e._hardwareTexture)!=null&&d.underlyingResource||(c=this._textureHelper.createGPUTextureForInternalTexture(e));const u=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(u,e,r,n,e.depth,c.format,o,l,e.invertY,!1,i,s),h&&this._generateMipmaps(e)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){var c;let l=e._hardwareTexture;(c=e._hardwareTexture)!=null&&c.underlyingResource||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,s));const h=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);this._textureHelper.updateTexture(h,e,i,s,e.depth,l.format,n,o,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){var f;const o=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),h=n?e.width:Math.pow(2,Math.max(o-s,0)),c=n?e.height:Math.pow(2,Math.max(l-s,0));let u=e._hardwareTexture;(f=e._hardwareTexture)!=null&&f.underlyingResource||(u=this._textureHelper.createGPUTextureForInternalTexture(e,h,c));const d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,h,c,e.depth,u.format,i,s,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){this._uploadDataToTextureDirectly(e,t,i,s)}_uploadImageToTexture(e,t,i=0,s=0){var h;let r=e._hardwareTexture;if((h=e._hardwareTexture)!=null&&h.underlyingResource||(r=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";const n=t,o=Math.ceil(e.width/(1<<s)),l=Math.ceil(e.height/(1<<s));this._textureHelper.updateTexture(n,e,o,l,e.depth,r.format,i,s,e.invertY,!1,0,0)}readPixels(e,t,i,s,r=!0,n=!0){const l=this._getCurrentRenderPassWrapper().colorAttachmentGPUTextures[0];if(!l)return Promise.resolve(new Uint8Array(0));const h=l.underlyingResource,c=l.format;return h?(n&&this.flushFramebuffer(),this._textureHelper.readPixels(h,e,t,i,s,c)):Promise.resolve(new Uint8Array(0))}beginFrame(){super.beginFrame()}endFrame(){if(this._endCurrentRenderPass(),this._snapshotRendering.endFrame(),this._timestampQuery.endFrame(this._renderEncoder),this._timestampIndex=0,this.flushFramebuffer(),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){const e=[];for(const t in be._UpdatedUbosInFrame)e.push(t+":"+be._UpdatedUbosInFrame[t]);O.Log(["frame #"+this._count+" - updated ubos -",e.join(", ")])}be._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,super.endFrame(),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&O.Log(["%c frame #"+this._count+" - end","background: #ffff00"]),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&O.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])))}flushFramebuffer(){this._endCurrentRenderPass(),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset()}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentPassIsMainPass()}_startRenderTargetRenderPass(e,t,i,s,r){var S,C,v,b,A;this._endCurrentRenderPass();const n=e,o=n._depthStencilTexture,l=o==null?void 0:o._hardwareTexture,h=l==null?void 0:l.underlyingResource,c=l==null?void 0:l.getMSAATexture(),u=h==null?void 0:h.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),d=c==null?void 0:c.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),f=l?vt.HasStencilAspect(l.format):!1,_=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const p=uP;i&&(p.r=i.r*255,p.g=i.g*255,p.b=i.b*255,p.a=i.a*255);const g=t&&i,x=t&&s,T=t&&r;if(n._attachments&&n.isMulti){(!this._mrtAttachments||this._mrtAttachments.length===0)&&(this._mrtAttachments=n._defaultAttachments);for(let P=0;P<this._mrtAttachments.length;++P){const L=this._mrtAttachments[P],w=n.textures[P],$=w==null?void 0:w._hardwareTexture,J=$==null?void 0:$.underlyingResource;if($&&J){const ne=$.getMSAATexture(P),oe=((S=n.layerIndices)==null?void 0:S[P])??0,re=((C=n.faceIndices)==null?void 0:C[P])??0,ce={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,format:$.format,baseArrayLayer:w.isCube?oe*6+re:oe},Se={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,format:$.format,baseArrayLayer:0},Ce=w.type===7||w.type===5,ae=J.createView(ce),ie=ne==null?void 0:ne.createView(Se);_.push({view:ie||ae,resolveTarget:ne?ae:void 0,clearValue:L!==0&&g?Ce?p:i:void 0,loadOp:L!==0&&g?Ki.Clear:Ki.Load,storeOp:Mr.Store})}}this._cacheRenderPipeline.setMRT(n.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{const P=n.texture;if(P){const L=P._hardwareTexture,w=L.underlyingResource,$=L.getMSAATexture(),J=w.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),ne=$==null?void 0:$.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),oe=P.type===7||P.type===5;_.push({view:ne||J,resolveTarget:$?J:void 0,clearValue:g?oe?p:i:void 0,loadOp:g?Ki.Clear:Ki.Load,storeOp:Mr.Store})}else _.push(null)}if((v=this._debugPushGroup)==null||v.call(this,"render target pass"+(e.label?" ("+e.label+")":""),1),this._rttRenderPassWrapper.renderPassDescriptor={label:(e.label??"RTT")+"RenderPass",colorAttachments:_,depthStencilAttachment:o&&h?{view:d||u,depthClearValue:x?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:x?Ki.Clear:Ki.Load,depthStoreOp:Mr.Store,stencilClearValue:n._depthStencilTextureWithStencil&&T?this._clearStencilValue:void 0,stencilLoadOp:f?n._depthStencilTextureWithStencil&&T?Ki.Clear:Ki.Load:void 0,stencilStoreOp:f?Mr.Store:void 0}:void 0,occlusionQuerySet:(b=this._occlusionQuery)!=null&&b.hasQueries?this._occlusionQuery.querySet:void 0},this._timestampQuery.startPass(this._rttRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){const P=n.texture;O.Log(["frame #"+this._count+" - render target begin pass - rtt name="+e.label+", internalTexture.uniqueId="+P.uniqueId+", width="+P.width+", height="+P.height+", setClearStates="+t,"renderPassDescriptor=",this._rttRenderPassWrapper.renderPassDescriptor])}(A=this._debugFlushPendingCommands)==null||A.call(this),this._resetRenderPassStates(),(!l||!vt.HasStencilAspect(l.format))&&(this._stencilStateComposer.enabled=!1)}_startMainRenderPass(e,t,i,s){var h,c,u;this._endCurrentRenderPass(),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const r=e&&t,n=e&&i,o=e&&s;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=r?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=r?Ki.Clear:Ki.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=n?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=n?Ki.Clear:Ki.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=o?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?o?Ki.Clear:Ki.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(h=this._occlusionQuery)!=null&&h.hasQueries?this._occlusionQuery.querySet:void 0;const l=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(l),this._options.antialias?(Yx.format=l.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=l.createView(Yx)):($x.format=l.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=l.createView($x)),this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height+", setClearStates="+e,"renderPassDescriptor=",this._mainRenderPassWrapper.renderPassDescriptor])),(c=this._debugPushGroup)==null||c.call(this,"main pass",0),this._timestampQuery.startPass(this._mainRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper),(u=this._debugFlushPendingCommands)==null||u.call(this),this._resetRenderPassStates(),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}_endCurrentRenderPass(){var t,i,s;if(!this._currentRenderPass)return 0;const e=this._currentPassIsMainPass()?2:1;return!this._snapshotRendering.endRenderPass(this._currentRenderPass)&&!this.compatibilityMode&&(this._bundleList.run(this._currentRenderPass),this._bundleList.reset()),this._currentRenderPass.end(),this._timestampQuery.endPass(this._timestampIndex,this._currentRenderTarget&&this._currentRenderTarget.gpuTimeInFrame?this._currentRenderTarget.gpuTimeInFrame:this.gpuTimeInFrameForMainPass),this._timestampIndex+=2,this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log("frame #"+this._count+" - "+(e===2?"main":"render target")+" end pass"+(e===1?" - internalTexture.uniqueId="+((i=(t=this._currentRenderTarget)==null?void 0:t.texture)==null?void 0:i.uniqueId):""))),(s=this._debugPopGroup)==null||s.call(this,0),this._currentRenderPass=null,e}bindFramebuffer(e,t=0,i,s,r,n=0,o=0){var h,c;const l=(h=e.texture)==null?void 0:h._hardwareTexture;this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass(),this._currentRenderTarget=e,this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=l,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?vt.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:Dt.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?o*6+t:o,baseMipLevel:n,arrayLayerCount:1,aspect:gn.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:Dt.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?o*6+t:o,baseMipLevel:0,arrayLayerCount:1,aspect:gn.All},this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log(["frame #"+this._count+" - bindFramebuffer - rtt name="+e.label+", internalTexture.uniqueId="+((c=e.texture)==null?void 0:c.uniqueId)+", face="+t+", lodLevel="+n+", layer="+o,"colorAttachmentViewDescriptor=",this._rttRenderPassWrapper.colorAttachmentViewDescriptor,"depthAttachmentViewDescriptor=",this._rttRenderPassWrapper.depthAttachmentViewDescriptor])),this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,n&&(i=i/Math.pow(2,n))),s||(s=e.height,n&&(s=s/Math.pow(2,n))),this._viewport(0,0,i,s)),this.wipeCaches()}unBindFramebuffer(e,t=!1,i){var r,n;const s=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=s,this._endCurrentRenderPass(),(r=e.texture)!=null&&r.generateMipMaps&&!t&&!e.isCube&&this._generateMipmaps(e.texture),this._currentRenderTarget=null,this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&O.Log("frame #"+this._count+" - unBindFramebuffer - rtt name="+e.label+", internalTexture.uniqueId=",(n=e.texture)==null?void 0:n.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._currentRenderPass||this._startMainRenderPass(!1),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){var i;const t=((i=e.colorAttachmentGPUTextures[0])==null?void 0:i.format)??null;this._cacheRenderPipeline.setColorFormat(t),this._colorFormat!==t&&(this._colorFormat=t)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}setState(e,t=0,i,s=!1,r,n,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=this.cullBackFaces??r??!0?1:2;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const h=s?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==h||i)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=n}_applyRenderPassChanges(e){const t=this._stencilStateComposer.enabled?this._mustUpdateStencilRef():!1,i=this._alphaState.alphaBlend?this._mustUpdateBlendColor():!1;this._mustUpdateViewport()&&this._applyViewport(e),this._mustUpdateScissor()&&this._applyScissor(e),t&&this._applyStencilRef(e),i&&this._applyBlendColor(e)}_draw(e,t,i,s,r){var g;const n=this._getCurrentRenderPass(),o=this._bundleList;this.applyStates();const l=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,ai.InternalsUBOName),l.uniformBuffer&&(l.uniformBuffer.update(),this.bindUniformBufferBase(l.uniformBuffer.getBuffer(),0,ai.LeftOvertUBOName)),this._snapshotRendering.play){this._reportDrawCall();return}!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);const h=!this.compatibilityMode&&this._currentDrawContext.fastBundle;let c=n;if(h||this._snapshotRendering.record){if(this._applyRenderPassChanges(o),!this._snapshotRendering.record){this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(s,r||1,i),o.addBundle(this._currentDrawContext.fastBundle),this._reportDrawCall();return}c=o.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),o.numDrawCalls++}let u=0;if(this._currentMaterialContext.hasFloatOrDepthTextures){let x=1;for(let T=0;T<l.shaderProcessingContext.textureNames.length;++T){const S=l.shaderProcessingContext.textureNames[T],C=(g=this._currentMaterialContext.textures[S])==null?void 0:g.texture,v=C&&C.format>=13&&C.format<=18;((C==null?void 0:C.type)===1&&!this._caps.textureFloatLinearFiltering||v)&&(u|=x),x=x<<1}}this._currentMaterialContext.textureState=u;const d=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,u),f=this._cacheBindGroups.getBindGroups(l,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(this.compatibilityMode?null:o),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,c=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:vt.GetSample(this.currentSampleCount)}))),c.setPipeline(d),this._currentIndexBuffer&&c.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?so.Uint32:so.Uint16,0);const _=this._cacheRenderPipeline.vertexBuffers;for(let x=0;x<_.length;x++){const T=_[x],S=T.effectiveBuffer;S&&c.setVertexBuffer(x,S.underlyingResource,T._validOffsetRange?0:T.byteOffset)}for(let x=0;x<f.length;x++)c.setBindGroup(x,f[x]);const p=!this.compatibilityMode&&!this._snapshotRendering.record;p&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(s,r||1,i),e===0?c.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):c.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):e===0?c.drawIndexed(s,r||1,i,0,0):c.draw(s,r||1,i,0),p&&(this._currentDrawContext.fastBundle=c.finish(),o.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,i,s=1){this._draw(0,e,t,i,s)}drawArraysType(e,t,i,s=1){this._currentIndexBuffer=null,this._draw(1,e,t,i,s)}dispose(){var e,t;this._isDisposed=!0,this._timestampQuery.dispose(),(e=this._mainTexture)==null||e.destroy(),(t=this._depthTexture)==null||t.destroy(),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._device.destroy(),super.dispose()}getRenderWidth(e=!1){var t;return!e&&this._currentRenderTarget?this._currentRenderTarget.width:((t=this._renderingCanvas)==null?void 0:t.width)??0}getRenderHeight(e=!1){var t;return!e&&this._currentRenderTarget?this._currentRenderTarget.height:((t=this._renderingCanvas)==null?void 0:t.height)??0}getError(){return 0}bindSamplers(){}_bindTextureDirectly(){return!1}areAllEffectsReady(){return!0}_executeWhenRenderingStateIsCompiled(e,t){t()}_isRenderingStateCompiled(){return!0}_getUnpackAlignement(){return 1}_unpackFlipY(){}_bindUnboundFramebuffer(){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"}_getSamplingParameters(){throw"_getSamplingParameters is not available in WebGPU"}getUniforms(){return[]}setIntArray(){return!1}setIntArray2(){return!1}setIntArray3(){return!1}setIntArray4(){return!1}setArray(){return!1}setArray2(){return!1}setArray3(){return!1}setArray4(){return!1}setMatrices(){return!1}setMatrix3x3(){return!1}setMatrix2x2(){return!1}setFloat(){return!1}setFloat2(){return!1}setFloat3(){return!1}setFloat4(){return!1}}Ze._GLSLslangDefaultOptions={jsPath:`${X._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${X._DefaultCdnUrl}/glslang/glslang.wasm`};Ze._InstanceId=0;Ze.UseTWGSL=!0;Ze.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a&&(a===0&&!this._alphaState.alphaBlend||a!==0&&this._alphaState.alphaBlend)){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0;break}e||(this.setDepthWrite(a===H.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(a===H.ALPHA_DISABLE)),this._alphaMode=a,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};Ze.prototype.setAlphaEquation=function(a){H.prototype.setAlphaEquation.call(this,a),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Zf{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(this._bindGroups.length===0){const s=this._bindGroupEntries.length>0;for(const r in e){const n=e[r],o=i[r],l=o.group,h=o.binding,c=n.type,u=n.object;let d=n.indexInGroupEntries,f=this._bindGroupEntries[l];switch(f||(f=this._bindGroupEntries[l]=[]),c){case Vt.Sampler:{const _=u;d!==void 0&&s?f[d].resource=this._cacheSampler.getSampler(_):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._cacheSampler.getSampler(_)}));break}case Vt.Texture:case Vt.TextureWithoutSampler:{const _=u,p=_._texture._hardwareTexture;d!==void 0&&s?(c===Vt.Texture&&(f[d++].resource=this._cacheSampler.getSampler(_._texture)),f[d].resource=p.view):(n.indexInGroupEntries=f.length,c===Vt.Texture&&f.push({binding:h-1,resource:this._cacheSampler.getSampler(_._texture)}),f.push({binding:h,resource:p.view}));break}case Vt.StorageTexture:{const _=u,p=_._texture._hardwareTexture;p.textureAdditionalUsages&ri.StorageBinding||O.Error(`computeDispatch: The texture (name=${_.name}, uniqueId=${_.uniqueId}) is not a storage texture!`,50),d!==void 0&&s?f[d].resource=p.viewForWriting:(n.indexInGroupEntries=f.length,f.push({binding:h,resource:p.viewForWriting}));break}case Vt.ExternalTexture:{const p=u.underlyingResource;d!==void 0&&s?f[d].resource=this._device.importExternalTexture({source:p}):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._device.importExternalTexture({source:p})}));break}case Vt.UniformBuffer:case Vt.StorageBuffer:case Vt.DataBuffer:{const _=c===Vt.DataBuffer?u:(c===Vt.UniformBuffer,u.getBuffer()),p=_.underlyingResource;d!==void 0&&s?(f[d].resource.buffer=p,f[d].resource.size=_.capacity):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:{buffer:p,offset:0,size:_.capacity}}));break}}}for(let r=0;r<this._bindGroupEntries.length;++r){const n=this._bindGroupEntries[r];if(!n){this._bindGroups[r]=void 0;continue}this._bindGroups[r]=this._device.createBindGroup({layout:t.getBindGroupLayout(r),entries:n})}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups}constructor(e,t){this._device=e,this._cacheSampler=t,this.uniqueId=Zf._Counter++,this._bindGroupEntries=[],this.clear()}clear(){this._bindGroups=[]}}Zf._Counter=0;class dP{get isAsync(){return!1}get isReady(){return!!this.stage}constructor(e){this._name="unnamed",this.engine=e}_getComputeShaderCode(){var e;return(e=this.sources)==null?void 0:e.compute}dispose(){}}const Kx={};Ze.prototype.createComputeContext=function(){return new Zf(this._device,this._cacheSampler)};Ze.prototype.createComputeEffect=function(a,e){const i=(a.computeElement||a.compute||a.computeToken||a.computeSource||a)+"@"+e.defines;if(this._compiledComputeEffects[i]){const r=this._compiledComputeEffects[i];return e.onCompiled&&r.isReady()&&e.onCompiled(r),r}const s=new Vl(a,e,this,i);return this._compiledComputeEffects[i]=s,s};Ze.prototype.createComputePipelineContext=function(){return new dP(this)};Ze.prototype.areAllComputeEffectsReady=function(){for(const a in this._compiledComputeEffects)if(!this._compiledComputeEffects[a].isReady())return!1;return!0};Ze.prototype.computeDispatch=function(a,e,t,i,s=1,r=1,n,o){this._endCurrentRenderPass();const l=a._pipelineContext,h=e;l.computePipeline||(l.computePipeline=this._device.createComputePipeline({layout:Ru.Auto,compute:l.stage})),o&&this._timestampQuery.startPass(Kx,this._timestampIndex);const c=this._renderEncoder.beginComputePass(Kx);c.setPipeline(l.computePipeline);const u=h.getBindGroups(t,l.computePipeline,n);for(let d=0;d<u.length;++d){const f=u[d];f&&c.setBindGroup(d,f)}i+s+r>0&&c.dispatchWorkgroups(i,s,r),c.end(),o&&(this._timestampQuery.endPass(this._timestampIndex,o),this._timestampIndex+=2)};Ze.prototype.releaseComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Ze.prototype._prepareComputePipelineContext=function(a,e,t,i,s){const r=a;this.dbgShowShaderCode&&(O.Log(i),O.Log(e)),r.sources={compute:e,rawCompute:t},r.stage=this._createComputePipelineStageDescriptor(e,i,s)};Ze.prototype._releaseComputeEffect=function(a){this._compiledComputeEffects[a._key]&&(delete this._compiledComputeEffects[a._key],this._deleteComputePipelineContext(a.getPipelineContext()))};Ze.prototype._rebuildComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Ze.prototype._deleteComputePipelineContext=function(a){a&&a.dispose()};Ze.prototype._createComputePipelineStageDescriptor=function(a,e,t){return e?e="//"+e.split(`
`).join(`
//`)+`
`:e="",{module:this._device.createShaderModule({code:e+a}),entryPoint:t}};Ze.prototype._createDepthStencilCubeTexture=function(a,e){const t=new Tt(this,e.generateStencil?et.DepthStencil:et.Depth);t.isCube=!0,t.label=e.label;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:e.generateStencil?13:14,...e};t.format=i.depthTextureFormat,this._setupDepthStencilTexture(t,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const s=t._hardwareTexture;return t.type=vt.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(t),t};Ze.prototype.createCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(a,e,t,!!i,s,r,n,o,l,h,c,u,null,(f,_)=>{const p=_,g=p[0].width,x=g;this._setCubeMapTextureParams(f,!i),f.format=n??-1;const T=this._textureHelper.createGPUTextureForInternalTexture(f,g,x);this._textureHelper.updateCubeTextures(p,T.underlyingResource,g,x,T.format,!1,!1,0,0),i||this._generateMipmaps(f,this._uploadEncoder),f.isReady=!0,f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),s&&s()},!!d)};Ze.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};Ze.prototype._debugPushGroup=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(a):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(a):this._pendingDebugCommands.push(["push",a]))};Ze.prototype._debugPopGroup=function(a){this._options.enableGPUDebugMarkers&&(a===0||a===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Ze.prototype._debugInsertMarker=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(a):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a]))};Ze.prototype._debugFlushPendingCommands=function(){for(let a=0;a<this._pendingDebugCommands.length;++a){const[e,t]=this._pendingDebugCommands[a];switch(e){case"push":this._debugPushGroup(t);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(t);break}}this._pendingDebugCommands.length=0};Ze.prototype.createDynamicTexture=function(a,e,t,i){const s=new Tt(this,et.Dynamic);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?pe.GetExponentOfTwo(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?pe.GetExponentOfTwo(e,this._caps.maxTextureSize):e),s.width=a,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),a&&e&&this._textureHelper.createGPUTextureForInternalTexture(s,a,e),s};Ze.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,r,n){var c;if(!a)return;const o=e.width,l=e.height;let h=a._hardwareTexture;(c=a._hardwareTexture)!=null&&c.underlyingResource||(h=this._textureHelper.createGPUTextureForInternalTexture(a,o,l)),this._textureHelper.updateTexture(e,a,o,l,a.depth,h.format,0,0,t,i,0,0,n),a.generateMipMaps&&this._generateMipmaps(a),a._dynamicTextureSource=e,a._premulAlpha=i,a.invertY=t||!1,a.isReady=!0};class fP extends MS{constructor(e){super(e)}}xt.prototype.setExternalTexture=function(a,e){this._engine.setExternalTexture(a,e)};Ze.prototype.createExternalTexture=function(a){return new fP(a)};Ze.prototype.setExternalTexture=function(a,e){if(!e){this._currentMaterialContext.setTexture(a,null);return}this._setInternalTexture(a,e)};Ze.prototype.unBindMultiColorAttachmentFramebuffer=function(a,e=!1,t){t&&t();const s=a._attachments.length;this._endCurrentRenderPass();for(let r=0;r<s;r++){const n=a.textures[r];n.generateMipMaps&&!e&&!n.isCube&&this._generateMipmaps(n)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)};Ze.prototype.createMultipleRenderTarget=function(a,e,t){let i=!1,s=!0,r=!1,n=!1,o=15,l=1;const h=0,c=3,u=!1,d=5,f=3553;let _=[],p=[],g=[],x=[],T=[],S=[],C=[],v=[],b=[];const A=this._createHardwareRenderTargetWrapper(!0,!1,a);e!==void 0&&(i=e.generateMipMaps===void 0?!1:e.generateMipMaps,s=e.generateDepthBuffer===void 0?!0:e.generateDepthBuffer,r=e.generateStencilBuffer===void 0?!1:e.generateStencilBuffer,n=e.generateDepthTexture===void 0?!1:e.generateDepthTexture,l=e.textureCount||1,o=e.depthTextureFormat??15,e.types&&(_=e.types),e.samplingModes&&(p=e.samplingModes),e.useSRGBBuffers&&(g=e.useSRGBBuffers),e.formats&&(x=e.formats),e.targetTypes&&(T=e.targetTypes),e.faceIndex&&(S=e.faceIndex),e.layerIndex&&(C=e.layerIndex),e.layerCounts&&(v=e.layerCounts),b=e.labels??b),A.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const P=a.width||a,L=a.height||a;let w=null;(s||r||n)&&(n||(s&&r?o=13:s?o=14:o=19),w=A.createDepthStencilTexture(0,!1,r,1,o,"MultipleRenderTargetDepthStencil"));const $=[],J=[],ne=[];A._generateDepthBuffer=s,A._generateStencilBuffer=r,A._attachments=J,A._defaultAttachments=ne;for(let oe=0;oe<l;oe++){let re=p[oe]||c,ce=_[oe]||h;const Se=x[oe]||d,Ce=(g[oe]||u)&&this._caps.supportSRGBBuffers,ae=T[oe]||f,ie=v[oe]??1;if((ce===1&&!this._caps.textureFloatLinearFiltering||ce===2&&!this._caps.textureHalfFloatLinearFiltering)&&(re=1),ce===1&&!this._caps.textureFloat&&(ce=0,O.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),J.push(oe+1),ne.push(t?oe+1:oe===0?1:0),ae===-1)continue;const F=new Tt(this,et.MultiRenderTarget);switch($[oe]=F,ae){case 34067:F.isCube=!0;break;case 32879:F.is3D=!0,F.baseDepth=F.depth=ie;break;case 35866:F.is2DArray=!0,F.baseDepth=F.depth=ie;break}F.baseWidth=P,F.baseHeight=L,F.width=P,F.height=L,F.isReady=!0,F.samples=1,F.generateMipMaps=i,F.samplingMode=re,F.type=ce,F._cachedWrapU=0,F._cachedWrapV=0,F._useSRGBBuffer=Ce,F.format=Se,F.label=b[oe],this._internalTexturesCache.push(F),this._textureHelper.createGPUTextureForInternalTexture(F)}return w&&(w.incrementReferences(),$[l]=w,this._internalTexturesCache.push(w)),A.setTextures($),A.setLayerAndFaceIndices(C,S),A};Ze.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,e){if(!a||!a.textures||a.textures[0].samples===e)return e;const t=a.textures.length;if(t===0)return 1;e=Math.min(e,this.getCaps().maxMSAASamples);for(let s=0;s<t;++s){const n=a.textures[s]._hardwareTexture;n==null||n.releaseMSAATexture()}const i=a._depthStencilTexture===a.textures[t-1];for(let s=0;s<t;++s){const r=a.textures[s];this._textureHelper.createMSAATexture(r,e,!1,s===t-1&&i?0:s),r.samples=e}return a._depthStencilTexture&&!i&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,e),a._depthStencilTexture.samples=e),e};Ze.prototype.bindAttachments=function(a){a.length===0||!this._currentRenderTarget||(this._mrtAttachments=a,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(a))};Ze.prototype.buildTextureLayout=function(a){const e=[];for(let t=0;t<a.length;t++)a[t]?e.push(t+1):e.push(0);return e};Ze.prototype.restoreSingleAttachment=function(){};Ze.prototype.restoreSingleAttachmentForRenderTarget=function(){};Ze.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter};Ze.prototype.captureGPUFrameTime=function(a){this._timestampQuery.enable=a&&!!this._caps.timerQuery};Ze.prototype.createQuery=function(){return this._occlusionQuery.createQuery()};Ze.prototype.deleteQuery=function(a){return this._occlusionQuery.deleteQuery(a),this};Ze.prototype.isQueryResultAvailable=function(a){return this._occlusionQuery.isQueryResultAvailable(a)};Ze.prototype.getQueryResult=function(a){return this._occlusionQuery.getQueryResult(a)};Ze.prototype.beginOcclusionQuery=function(a,e){var t;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery(e))return(t=this._currentRenderPass)==null||t.beginOcclusionQuery(e),!0}else return this._bundleList.addItem(new ig(e)),!0;return!1};Ze.prototype.endOcclusionQuery=function(){var a;return this.compatibilityMode?(a=this._currentRenderPass)==null||a.endOcclusionQuery():this._bundleList.addItem(new sg),this};Ze.prototype.createRawTexture=function(a,e,t,i,s,r,n,o=null,l=0,h=0,c=!1){const u=new Tt(this,et.Raw);return u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=n,u.invertY=r,u._compression=o,u.type=l,u._creationFlags=h,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(u,e,t,void 0,h),this.updateRawTexture(u,a,i,r,o,l,c),this._internalTexturesCache.push(u),u};Ze.prototype.updateRawTexture=function(a,e,t,i,s=null,r=0,n=!1){if(a){if(this._doNotHandleContextLost||(a._bufferView=e,a.invertY=i,a._compression=s,a._useSRGBBuffer=n),e){const o=a._hardwareTexture;t===4&&(e=Ju(e,a.width,a.height,r));const h=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(h,a,a.width,a.height,a.depth,o.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0}};Ze.prototype.createRawCubeTexture=function(a,e,t,i,s,r,n,o=null){const l=new Tt(this,et.CubeRaw);return i===1&&!this._caps.textureFloatLinearFiltering?(s=!1,n=1,O.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):i===2&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,n=1,O.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):i===1&&!this._caps.textureFloatRender?(s=!1,O.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):i===2&&!this._caps.colorBufferFloat&&(s=!1,O.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")),l.isCube=!0,l._originalFormat=t,l.format=t===4?5:t,l.type=i,l.generateMipMaps=s,l.width=e,l.height=e,l.samplingMode=n,this._doNotHandleContextLost||(l._bufferViewArray=a),l.invertY=r,l._compression=o,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),a&&this.updateRawCubeTexture(l,a,t,i,r,o),l.isReady=!0,l};Ze.prototype.updateRawCubeTexture=function(a,e,t,i,s,r=null){a._bufferViewArray=e,a.invertY=s,a._compression=r;const n=a._hardwareTexture,o=t===4,l=[];for(let h=0;h<e.length;++h){let c=e[h];o&&(c=Ju(e[h],a.width,a.height,i)),l.push(new Uint8Array(c.buffer,c.byteOffset,c.byteLength))}this._textureHelper.updateCubeTextures(l,n.underlyingResource,a.width,a.height,n.format,s,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder),a.isReady=!0};Ze.prototype.createRawCubeTextureFromUrl=function(a,e,t,i,s,r,n,o,l=null,h=null,c=3,u=!1){const d=this.createRawCubeTexture(null,t,i,s,!r,u,c,null);e==null||e.addPendingData(d),d.url=a,this._internalTexturesCache.push(d);const f=(p,g)=>{e==null||e.removePendingData(d),h&&p&&h(p.status+" "+p.statusText,g)},_=p=>{const g=d.width,x=n(p);if(!x)return;const T=[0,2,4,1,3,5];if(o){const S=i===4,C=o(x),v=d._hardwareTexture,b=[0,1,2,3,4,5];for(let A=0;A<C.length;A++){const P=g>>A,L=[];for(let w=0;w<6;w++){let $=C[A][b[w]];S&&($=Ju($,P,P,s)),L.push(new Uint8Array($.buffer,$.byteOffset,$.byteLength))}this._textureHelper.updateCubeTextures(L,v.underlyingResource,P,P,v.format,u,!1,0,0)}}else{const S=[];for(let C=0;C<6;C++)S.push(x[T[C]]);this.updateRawCubeTexture(d,S,i,s,u)}d.isReady=!0,e==null||e.removePendingData(d),l&&l()};return this._loadFile(a,p=>{_(p)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};Ze.prototype.createRawTexture3D=function(a,e,t,i,s,r,n,o,l=null,h=0,c=0){const u=et.Raw3D,d=new Tt(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=o,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,c),this.updateRawTexture3D(d,a,s,n,l,h),this._internalTexturesCache.push(d),d};Ze.prototype.updateRawTexture3D=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=Ju(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};Ze.prototype.createRawTexture2DArray=function(a,e,t,i,s,r,n,o,l=null,h=0,c=0){const u=et.Raw2DArray,d=new Tt(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,c),this.updateRawTexture2DArray(d,a,s,n,l,h),this._internalTexturesCache.push(d),d};Ze.prototype.updateRawTexture2DArray=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=Ju(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function Ju(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n<e;n++)for(let o=0;o<t;o++){const l=(o*e+n)*3,h=(o*e+n)*4;s[h+0]=a[l+0],s[h+1]=a[l+1],s[h+2]=a[l+2],s[h+3]=r}return s}Ze.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,h=0){const c=a._hardwareTexture;return n&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,e,t,c.format,i,s,r,o)};Ze.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class _P extends Pm{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new zm)}}Ze.prototype._createHardwareRenderTargetWrapper=function(a,e,t){const i=new _P(a,e,t,this);return this._renderTargetWrapperCache.push(i),i};Ze.prototype.createRenderTargetTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!1,a),i={};e!==void 0&&typeof e=="object"?(i.generateMipMaps=e.generateMipMaps,i.generateDepthBuffer=e.generateDepthBuffer===void 0?!0:e.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&e.generateStencilBuffer,i.samplingMode=e.samplingMode===void 0?3:e.samplingMode,i.creationFlags=e.creationFlags??0,i.noColorAttachment=!!e.noColorAttachment,i.samples=e.samples,i.label=e.label):(i.generateMipMaps=e,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.samplingMode=3,i.creationFlags=0,i.noColorAttachment=!1);const s=i.noColorAttachment?null:this._createInternalTexture(a,e,!0,et.RenderTarget);return t.label=i.label??"RenderTargetWrapper",t._samples=i.samples??1,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=!!i.generateStencilBuffer,t.setTextures(s),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,!1,t._generateStencilBuffer,t.samples,i.generateStencilBuffer?13:14,i.label?i.label+"-DepthStencil":void 0),s&&(e!==void 0&&typeof e=="object"&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,i.creationFlags),e!==void 0&&typeof e=="object"&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1)),t};Ze.prototype._createDepthStencilTexture=function(a,e){const t=new Tt(this,e.generateStencil?et.DepthStencil:et.Depth);t.label=e.label;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:e.generateStencil?13:14,...e};t.format=i.depthTextureFormat,this._setupDepthStencilTexture(t,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const s=t._hardwareTexture;return t.type=vt.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(t),t};Ze.prototype._setupDepthStencilTexture=function(a,e,t,i,s,r=1){const n=e.width||e,o=e.height||e,l=e.layers||0;a.baseWidth=n,a.baseHeight=o,a.width=n,a.height=o,a.is2DArray=l>0,a.depth=l,a.isReady=!0,a.samples=r,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};Ze.prototype.updateRenderTargetTextureSampleCount=function(a,e){return!a||!a.texture||a.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(a.texture,e),a._depthStencilTexture&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,e),a._depthStencilTexture.samples=e),a._samples=e,a.texture.samples=e),e};Ze.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,t.label=i.label??"RenderTargetWrapper",t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const s=new Tt(this,et.RenderTarget);return s.width=a,s.height=a,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=i.samples,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,i.samplingMode===void 0||i.samplingMode===2||i.samplingMode===2||i.samplingMode===3||i.samplingMode===3||i.samplingMode===5||i.samplingMode===6||i.samplingMode===7||i.samplingMode===11,t._generateStencilBuffer,t.samples),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1),t};xt.prototype.setTextureSampler=function(a,e){this._engine.setTextureSampler(a,e)};Ze.prototype.setTextureSampler=function(a,e){var t;(t=this._currentMaterialContext)==null||t.setSampler(a,e)};xt.prototype.setStorageBuffer=function(a,e){this._engine.setStorageBuffer(a,e)};Ze.prototype.createStorageBuffer=function(a,e,t){return this._createBuffer(a,e|32,t)};Ze.prototype.updateStorageBuffer=function(a,e,t,i){const s=a;t===void 0&&(t=0);let r;i===void 0?(e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,i=r.byteLength):e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,this._bufferManager.setSubData(s,t,r,0,i)};Ze.prototype.readFromStorageBuffer=function(a,e,t,i,s){t=t||a.capacity;const r=this._bufferManager.createRawBuffer(t,kt.MapRead|kt.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(a.underlyingResource,e??0,r,0,t),new Promise((n,o)=>{const l=()=>{r.mapAsync(Oo.Read,0,t).then(()=>{const h=r.getMappedRange(0,t);let c=i;if(c===void 0)c=new Uint8Array(t),c.set(new Uint8Array(h));else{const u=c.constructor;c=new u(c.buffer),c.set(new u(h))}r.unmap(),this._bufferManager.releaseBuffer(r),n(c)},h=>{this.isDisposed?n(new Uint8Array):o(h)})};s?(this.flushFramebuffer(),l()):this.onEndFrameObservable.addOnce(()=>{l()})})};Ze.prototype.setStorageBuffer=function(a,e){var t;(t=this._currentDrawContext)==null||t.setBuffer(a,(e==null?void 0:e.getBuffer())??null)};function pP(a){return!!(a&&a.underlyingResource!==void 0)}Ze.prototype.updateVideoTexture=function(a,e,t){var s;if(!a||a._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=a._hardwareTexture;(s=a._hardwareTexture)!=null&&s.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(a)),pP(e)?(this._textureHelper.copyVideoToTexture(e,a,i.format,!t),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0):e&&this.createImageBitmap(e).then(r=>{this._textureHelper.updateTexture(r,a,a.width,a.height,a.depth,i.format,0,0,!t,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0}).catch(()=>{a.isReady=!0})};class Xo extends st{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=D.Identity(),this._projectionMatrix=D.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=m.Zero()),m.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=m.Zero()),m.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=m.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=m.Cross(this.direction,Bs.Y),t=m.Cross(e,this.direction);return m.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=m.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=D.Identity()),D.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=U.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),m.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(m.Dot(t,m.Up()))===1&&(t.z=1e-13);const s=U.Vector3[1];return i.addToRef(t,s),D.LookAtLHToRef(i,s,m.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}E([bs()],Xo.prototype,"position",null);E([bs()],Xo.prototype,"direction",null);E([I()],Xo.prototype,"shadowMinZ",null);E([I()],Xo.prototype,"shadowMaxZ",null);Ct.AddNodeConstructor("Light_Type_1",(a,e)=>()=>new Hr(a,m.Zero(),e));class Hr extends Xo{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 st.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&&D.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=m.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let u=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let f=0;f<i.length;f++){const _=i[f];if(!_)continue;const g=_.getBoundingInfo().boundingBox;for(let x=0;x<g.vectorsWorld.length;x++)m.TransformCoordinatesToRef(g.vectorsWorld[x],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>d&&(d=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=d)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;D.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?l:o,h?o:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}E([I()],Hr.prototype,"shadowFrustumSize",null);E([I()],Hr.prototype,"shadowOrthoScale",null);E([I()],Hr.prototype,"autoUpdateExtends",void 0);E([I()],Hr.prototype,"autoCalcShadowZBounds",void 0);E([I("orthoLeft")],Hr.prototype,"_orthoLeft",void 0);E([I("orthoRight")],Hr.prototype,"_orthoRight",void 0);E([I("orthoTop")],Hr.prototype,"_orthoTop",void 0);E([I("orthoBottom")],Hr.prototype,"_orthoBottom",void 0);function mP(a,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=pa("",{slice:.5,diameter:e.diameter,segments:e.segments},t),s=dS("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);s.rotation.x=-Math.PI/2,s.parent=i;const r=z.MergeMeshes([s,i],!0);return r.name=a,r}z.CreateHemisphere=(a,e,t,i)=>mP(a,{segments:e,diameter:t},i);Ct.AddNodeConstructor("Light_Type_2",(a,e)=>()=>new hr(a,m.Zero(),m.Zero(),0,0,e));class hr extends Xo{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()&&(hr._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):hr._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=D.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=m.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=m.Zero(),this._projectionTextureViewLightMatrix=D.Zero(),this._projectionTextureProjectionLightMatrix=D.Zero(),this._projectionTextureScalingMatrix=D.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 st.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,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;D.PerspectiveFovLHToRef(r,1,l?o:n,l?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),D.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;D.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 k){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;D.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=m.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=m.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=m.Normalize(this.transformedDirection):i=m.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())}}E([I()],hr.prototype,"angle",null);E([I()],hr.prototype,"innerAngle",null);E([I()],hr.prototype,"shadowAngleScale",null);E([I()],hr.prototype,"exponent",void 0);E([I()],hr.prototype,"projectionTextureLightNear",null);E([I()],hr.prototype,"projectionTextureLightFar",null);E([I()],hr.prototype,"projectionTextureUpDirection",null);E([ht("projectedLightTexture")],hr.prototype,"_projectionTexture",void 0);const gP="kernelBlurVaryingDeclaration",xP="varying vec2 sampleCoord{X};";W.IncludesShadersStore[gP]=xP;const TP="packingFunctions",EP=`vec4 pack(float depth)
{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;W.IncludesShadersStore[TP]=EP;const SP="kernelBlurFragment",CP=`#ifdef DOF
factor=sampleCoC(sampleCoord{X}); 
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
#endif
`;W.IncludesShadersStore[SP]=CP;const vP="kernelBlurFragment2",bP=`#ifdef DOF
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;W.IncludesShadersStore[vP]=bP;const AP="kernelBlurPixelShader",yP=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;
#ifdef DOF
uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float computedWeight=0.0;
#ifdef PACKEDFLOAT
float blend=0.;
#else
vec4 blend=vec4(0.);
#endif
#ifdef DOF
float sumOfWeights=CENTER_WEIGHT; 
float factor=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
#else
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
gl_FragColor=pack(blend);
#else
gl_FragColor=blend;
#endif
#ifdef DOF
gl_FragColor/=sumOfWeights;
#endif
}`;W.ShadersStore[AP]=yP;const RP="kernelBlurVertex",IP="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";W.IncludesShadersStore[RP]=IP;const PP="kernelBlurVertexShader",MP=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
sampleCenter=(position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[PP]=MP;class ts extends De{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=k.BILINEAR_SAMPLINGMODE,o,l,h=0,c="",u=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,l,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=c,this.direction=t,this.onApplyObservable.add(f=>{this._outputTexture?f.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):f.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let g=0;g<i;g++){const x=g/(i-1),T=this._gaussianWeight(x*2-1);r[g]=g-s,n[g]=T,o+=T}for(let g=0;g<n.length;g++)n[g]/=o;const l=[],h=[],c=[];for(let g=0;g<=s;g+=2){const x=Math.min(g+1,Math.floor(s));if(g===x)c.push({o:r[g],w:n[g]});else{const S=x===s,C=n[g]+n[x]*(S?.5:1),v=r[g]+1/(1+n[g]/n[x]);v===0?(c.push({o:r[g],w:n[g]}),c.push({o:r[g+1],w:n[g+1]})):(c.push({o:v,w:C}),c.push({o:-v,w:C}))}}for(let g=0;g<c.length;g++)h[g]=c[g].o,l[g]=c[g].w;r=h,n=l;const u=this.getEngine().getCaps().maxVaryingVectors,d=Math.max(u,0)-1;let f=Math.min(r.length,d),_="";_+=this._staticDefines,this._staticDefines.indexOf("DOF")!=-1&&(_+=`#define CENTER_WEIGHT ${this._glslFloat(n[f-1])}
`,f--);for(let g=0;g<f;g++)_+=`#define KERNEL_OFFSET${g} ${this._glslFloat(r[g])}
`,_+=`#define KERNEL_WEIGHT${g} ${this._glslFloat(n[g])}
`;let p=0;for(let g=d;g<r.length;g++)_+=`#define KERNEL_DEP_OFFSET${p} ${this._glslFloat(r[g])}
`,_+=`#define KERNEL_DEP_WEIGHT${p} ${this._glslFloat(n[g])}
`,p++;this.packedFloat&&(_+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(_,null,null,{varyingCount:f,depCount:p},e,t)}_nearestBestKernel(e){const t=Math.round(e);for(const i of[t,t-1,t+1,t-2,t+2])if(i%2!==0&&Math.floor(i/2)%2===0&&i>0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,s=-(e*e/(2*t*t));return 1/i*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return _e.Parse(()=>new ts(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}E([I("kernel")],ts.prototype,"_kernel",void 0);E([I("packedFloat")],ts.prototype,"_packedFloat",void 0);E([hm()],ts.prototype,"direction",void 0);V("BABYLON.BlurPostProcess",ts);class Jf extends oi{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=k.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Ks(0,1,0,1),this._transformMatrix=D.Zero(),this._mirrorMatrix=D.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,i=this.getScene(),!i)return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});const l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var c;(c=l._debugPushGroup)==null||c.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var c;(c=l._debugPopGroup)==null||c.call(l,1)});let h;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),D.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),h=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=m.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=h})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new ts("horizontal blur",new Z(1,0),this._blurKernelX,this._blurRatio,null,k.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,this._blurRatio===1&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new ts("vertical blur",new Z(0,1),this._blurKernelY,this._blurRatio,null,k.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=this._blurRatio!==1,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Jf(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var t;super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(t=this._sceneUBO)==null||t.dispose()}}k._CreateMirror=(a,e,t,i)=>new Jf(a,e,t,i);class Hi extends Et{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(D.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach(r=>s+=r),new Hi(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new Hi(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,l=5,h=!1,c=null,u=!1,d=.8,f=0,_,p){var g;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new G,this.boundingBoxPosition=m.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new D,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=D.Identity(),this._createPolynomials=u,this.coordinatesMode=k.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=c,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=d,this._lodOffset=f,!(!e&&!r)&&this.updateURL(e,c,n,h,o,i,(g=this.getScene())==null?void 0:g.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,l=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const h=e.lastIndexOf("."),c=t||(h>-1?e.substring(h).toLowerCase():""),u=c.indexOf(".dds")===0,d=c.indexOf(".env")===0,f=c.indexOf(".basis")===0;if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),l)this._files=l;else if(!f&&!d&&!u&&!n&&(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let _=0;_<n.length;_++)this._files.push(e+n[_]);this._extensions=n}o?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=r):this._loadTexture(i,r)}delayLoad(e){this.delayLoadState===4&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var r,n;if(e.updateFlag===this._textureMatrix.updateFlag||(e.isIdentity()!==this._textureMatrix.isIdentity()&&((r=this.getScene())==null||r.markAllMaterialsAsDirty(1,o=>o.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!((n=this.getScene())!=null&&n.useRightHandedSystem)))return;const t=U.Vector3[0],i=U.Quaternion[0],s=U.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,D.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(e=this.getScene())!=null&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var o;const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{var l;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),(l=this.getScene())==null||l.markAllMaterialsAsDirty(1)),e&&e()},n=(l,h)=>{this._loadingError=!0,this._errorObject={message:l,exception:h},t&&t(l,h),k.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?X.SetImmediate(()=>r()):this._texture.onLoadedObservable.add(()=>r()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(o=this._texture)==null||o.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=_e.Parse(()=>{let r=!1;return e.prefiltered&&(r=e.prefiltered),new Hi(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=m.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=m.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r<e.animations.length;r++){const n=e.animations[r],o=Si("BABYLON.Animation");o&&s.animations.push(o.Parse(n))}return s}clone(){let e=0;const t=_e.Clone(()=>{const i=new Hi(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}E([I()],Hi.prototype,"url",void 0);E([bs()],Hi.prototype,"boundingBoxPosition",void 0);E([bs()],Hi.prototype,"boundingBoxSize",null);E([I("rotationY")],Hi.prototype,"rotationY",null);E([I("files")],Hi.prototype,"_files",void 0);E([I("forcedExtension")],Hi.prototype,"_forcedExtension",void 0);E([I("extensions")],Hi.prototype,"_extensions",void 0);E([um("textureMatrix")],Hi.prototype,"_textureMatrix",void 0);E([um("textureMatrixRefraction")],Hi.prototype,"_textureMatrixRefraction",void 0);k._CubeTextureParser=Hi.Parse;V("BABYLON.CubeTexture",Hi);const DP="backgroundFragmentDeclaration",OP=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
uniform vec4 vPrimaryColorShadow;
#endif
uniform float shadowLevel;uniform float alpha;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#endif
#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
uniform vec3 vBackgroundCenter;
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 vReflectionControl;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
uniform mat4 view;
#endif
#ifdef PROJECTED_GROUND
uniform vec2 projectedGroundInfos;
#endif
`;W.IncludesShadersStore[DP]=OP;const NP="backgroundUboDeclaration",FP=`layout(std140,column_major) uniform;uniform Material
{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};
#include<sceneUboDeclaration>
`;W.IncludesShadersStore[NP]=FP;const wP="backgroundPixelShader",LP=`#ifdef TEXTURELODSUPPORT
#extension GL_EXT_shader_texture_lod : enable
#endif
precision highp float;
#include<__decl__backgroundFragment>
#include<helperFunctions>
varying vec3 vPositionW;
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif 
#ifdef MAINUV2 
varying vec2 vMainUV2; 
#endif 
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef DIFFUSE
#if DIFFUSEDIRECTUV==1
#define vDiffuseUV vMainUV1
#elif DIFFUSEDIRECTUV==2
#define vDiffuseUV vMainUV2
#else
varying vec2 vDiffuseUV;
#endif
uniform sampler2D diffuseSampler;
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE;
#endif
#ifndef SHADOWONLY
#define SHADOWONLY;
#endif
#include<imageProcessingDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<imageProcessingFunctions>
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<logDepthDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#ifdef REFLECTIONFRESNEL
#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#ifdef PROJECTED_GROUND
float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }
vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)<r*r) ? t : 1e6;}
float sphereIntersect(vec3 ro,vec3 rd,float ra) {float b=dot(ro,rd);float c=dot(ro,ro)-ra*ra;float h=b*b-c;if(h<0.0) { return -1.0; }
h=sqrt(h);return-b+h;}
vec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersect(eyePosition,camDir,radius);vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersect(eyePosition,p,radius);vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;}
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=vec3(0.0,1.0,0.0);
#endif
float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;
#include<lightFragment>[0..maxSimultaneousLights]
#ifdef SHADOWINUSE
globalShadow/=shadowLightCount;
#else
globalShadow=1.0;
#endif
#ifndef BACKMAT_SHADOWONLY
vec4 reflectionColor=vec4(1.,1.,1.,1.);
#ifdef REFLECTION
#ifdef PROJECTED_GROUND
vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=reflectionVector;
#else
vec2 reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
#ifdef REFLECTIONBLUR
float reflectionLOD=vReflectionInfos.y;
#ifdef TEXTURELODSUPPORT
reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#else
float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
reflectionSpecularMid,
lodReflectionNormalizedDoubled
);} else {reflectionColor=mix(
reflectionSpecularMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#else
vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef GAMMAREFLECTION
reflectionColor.rgb=toLinearSpace(reflectionColor.rgb);
#endif
#ifdef REFLECTIONBGR
reflectionColor.rgb=reflectionColor.bgr;
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#endif
vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;
#ifdef DIFFUSE
vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);
#ifdef GAMMADIFFUSE
diffuseMap.rgb=toLinearSpace(diffuseMap.rgb);
#endif
diffuseMap.rgb*=vDiffuseInfos.y;
#ifdef DIFFUSEHASALPHA
finalAlpha*=diffuseMap.a;
#endif
diffuseColor=diffuseMap.rgb;
#endif
#ifdef REFLECTIONFRESNEL
vec3 colorBase=diffuseColor;
#else
vec3 colorBase=reflectionColor.rgb*diffuseColor;
#endif
colorBase=max(colorBase,0.0);
#ifdef USERGBCOLOR
vec3 finalColor=colorBase;
#else
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);
#else
vec3 mainColor=vPrimaryColor.rgb;
#endif
vec3 finalColor=colorBase*mainColor;
#endif
#ifdef REFLECTIONFRESNEL
vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;
#ifdef REFLECTIONFALLOFF
float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;
#endif
finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));
#endif
#ifdef OPACITYFRESNEL
float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;
#endif
#ifdef SHADOWINUSE
finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);
#endif
vec4 color=vec4(finalColor,finalAlpha);
#else
vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);
#endif
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
#if !defined(SKIPFINALCOLORCLAMP)
color.rgb=clamp(color.rgb,0.,30.0);
#endif
#else
color=applyImageProcessing(color);
#endif
#ifdef PREMULTIPLYALPHA
color.rgb*=color.a;
#endif
#ifdef NOISE
color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);
#endif
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}
`;W.ShadersStore[wP]=LP;const BP="backgroundVertexDeclaration",UP=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
`;W.IncludesShadersStore[BP]=UP;const VP="backgroundVertexShader",kP=`precision highp float;
#include<__decl__backgroundVertex>
#include<helperFunctions>
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif
#ifdef MAINUV2
varying vec2 vMainUV2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
varying vec2 vDiffuseUV;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=position;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}
#else
gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#endif
vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normal);
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));
#ifdef EQUIRECTANGULAR_RELFECTION_FOV
mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}
#endif
#endif
#ifndef UV1
vec2 uv=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uv;
#endif
#ifdef MAINUV2
vMainUV2=uv2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
if (vDiffuseInfos.x==0.)
{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}
else
{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#ifdef VERTEXCOLOR
vColor=color;
#endif
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`;W.ShadersStore[VP]=kP;class GP extends Vs{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class ot extends vc{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t=t*2,this.reflectionReflectance0=ot.StandardReflectance0*t,this.reflectionReflectance90=ot.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=ot.StandardReflectance0+(1-ot.StandardReflectance0)*t,this.reflectionReflectance90=ot.StandardReflectance90+(1-ot.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=q.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=m.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new Wi(16),this._reflectionControls=we.Zero(),this._white=q.White(),this._primaryShadowColor=q.Black(),this._primaryHighlightColor=q.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!(this._diffuseTexture&&this._diffuseTexture.isRenderTarget||this._reflectionTexture&&this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new GP);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(qu(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,Pf(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&ue.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;qt(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const l=this._reflectionTexture;if(l&&ue.ReflectionTextureEnabled){if(!l.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=l.gammaSpace,n.RGBDREFLECTION=l.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=l.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,l.coordinatesMode===k.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=l.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!l.invertZ:l.invertZ,l.coordinatesMode){case k.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case k.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case k.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case k.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case k.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case k.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case k.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case k.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case k.CUBIC_MODE:case k.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),yf(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Rf(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),If(e,n,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(y.NormalKind)&&(e.createNormals(!0),O.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const l=new zo;n.FOG&&l.addFallback(0,"FOG"),n.POINTSIZE&&l.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&l.addFallback(0,"MULTIVIEW"),Cm(n,l,this._maxSimultaneousLights);const h=[y.PositionKind];n.NORMAL&&h.push(y.NormalKind),n.UV1&&h.push(y.UVKind),n.UV2&&h.push(y.UV2Kind),Sm(h,e,n,l),Af(h,n);const c=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];sn(c);const u=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];lt&&(lt.PrepareUniforms(c,n),lt.PrepareSamplers(u,n)),Mf({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const f=n.toString(),_=r.getEngine().createEffect("background",{attributes:h,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(_,n,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){this._primaryColorShadowLevel===0&&this._primaryColorHighlightLevel===0||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),Ku(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync||i._drawWrapper._forceRebindOnNextCall)&&(s.texturesEnabled&&(this._diffuseTexture&&ue.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gt(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&ue.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",l.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&ue.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&ue.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",l._lodTextureMid||l),this._uniformBuffer.setTexture("reflectionSamplerLow",l._lodTextureLow||l),this._uniformBuffer.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)):this._uniformBuffer.setTexture("reflectionSampler",l),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),Gr(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&ju(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Go(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&ao(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!(super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return _e.Clone(()=>new ot(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return _e.Parse(()=>new ot(e.name,t),e,t,i)}}ot.StandardReflectance0=.05;ot.StandardReflectance90=.5;E([li()],ot.prototype,"_primaryColor",void 0);E([te("_markAllSubMeshesAsLightsDirty")],ot.prototype,"primaryColor",void 0);E([li()],ot.prototype,"__perceptualColor",void 0);E([I()],ot.prototype,"_primaryColorShadowLevel",void 0);E([I()],ot.prototype,"_primaryColorHighlightLevel",void 0);E([te("_markAllSubMeshesAsLightsDirty")],ot.prototype,"primaryColorHighlightLevel",null);E([ht()],ot.prototype,"_reflectionTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionTexture",void 0);E([I()],ot.prototype,"_reflectionBlur",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionBlur",void 0);E([ht()],ot.prototype,"_diffuseTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"diffuseTexture",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"shadowLights",void 0);E([I()],ot.prototype,"_shadowLevel",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"shadowLevel",void 0);E([bs()],ot.prototype,"_sceneCenter",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"sceneCenter",void 0);E([I()],ot.prototype,"_opacityFresnel",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"opacityFresnel",void 0);E([I()],ot.prototype,"_reflectionFresnel",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionFresnel",void 0);E([I()],ot.prototype,"_reflectionFalloffDistance",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionFalloffDistance",void 0);E([I()],ot.prototype,"_reflectionAmount",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionAmount",void 0);E([I()],ot.prototype,"_reflectionReflectance0",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionReflectance0",void 0);E([I()],ot.prototype,"_reflectionReflectance90",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"reflectionReflectance90",void 0);E([I()],ot.prototype,"_useRGBColor",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"useRGBColor",void 0);E([I()],ot.prototype,"_enableNoise",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"enableNoise",void 0);E([I()],ot.prototype,"_maxSimultaneousLights",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ot.prototype,"maxSimultaneousLights",void 0);E([I()],ot.prototype,"_shadowOnly",void 0);E([te("_markAllSubMeshesAsLightsDirty")],ot.prototype,"shadowOnly",void 0);E([dE()],ot.prototype,"_imageProcessingConfiguration",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ot.prototype,"enableGroundProjection",void 0);E([I()],ot.prototype,"projectedGroundRadius",void 0);E([I()],ot.prototype,"projectedGroundHeight",void 0);V("BABYLON.BackgroundMaterial",ot);class Uo{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new q(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new q(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:m.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(i,s)=>{this.onErrorObservable.notifyObservers({message:i,exception:s})},this._options={...Uo._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new G,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new xe(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof Et){this._scene.environmentTexture=this._options.environmentTexture;return}const e=Hi.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new z("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||this._scene.meshes.length===1)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends(n=>n!==this._ground&&n!==this._rootMesh&&n!==this._skybox),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof $t&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const n=r.length();n>e&&(e=n*2,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=Im("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new ot("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof Et){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new k(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){const t=k.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Jf("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,k.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Ks(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let s=0;s<this._scene.meshes.length;s++){const r=this._scene.meshes[s];r!==this._ground&&r!==this._skybox&&r!==this._rootMesh&&this._groundMirror.renderList.push(r)}const i=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new xe(i.r,i.g,i.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel}_setupMirrorInGroundMaterial(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)}_setupSkybox(e){(!this._skybox||this._skybox.isDisposed())&&(this._skybox=Ym("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:z.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add(()=>{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new ot("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof Et){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new Hi(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=k.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Uo._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";Uo._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";Uo._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class js extends Ke{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=k.CLAMP_ADDRESSMODE,this._texture.wrapV=k.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=k.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=k.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=js.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new G,this.onLoadObservable=new G,s=this.getScene(),e=e||"textureDome",i.resolution=Math.abs(i.resolution)|0||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=i.autoPlay===void 0?!0:!!i.autoPlay,i.loop=i.loop===void 0?!0:!!i.loop,i.size=Math.abs(i.size)||(s.activeCamera?s.activeCamera.maxZ*.48:1e3),i.useDirectMapping===void 0?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,i.faceForward===void 0&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=pa(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:z.BACKSIDE},s);const n=this._material=new ot(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=pa("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:z.BACKSIDE},s),this._halfDomeMask.rotate(Bs.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&s.activeCamera){const l=s.activeCamera,h=m.Forward(),c=m.TransformNormal(h,l.getViewMatrix());c.normalize(),this.rotation.y=Math.acos(m.Dot(h,c))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case js.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case js.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const t=this._halfDome?0:.5,i=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(s=>{let r=s.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=t:this._texture.uOffset=i});break}case js.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(t=>{let i=t.isRightCamera;this._crossEye&&(i=!i),this._texture.vOffset=i?.5:0});break}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}js.MODE_MONOSCOPIC=0;js.MODE_TOPBOTTOM=1;js.MODE_SIDEBYSIDE=2;class ag extends js{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new k(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(s,r)=>{this.onLoadErrorObservable.notifyObservers(s||"Unknown error occured"),this.onError&&this.onError(s,r)})}}ag.MODE_MONOSCOPIC=js.MODE_MONOSCOPIC;ag.MODE_TOPBOTTOM=js.MODE_TOPBOTTOM;ag.MODE_SIDEBYSIDE=js.MODE_SIDEBYSIDE;const zP="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==";let WP=0;const og=a=>{if(!a.environmentBRDFTexture){const e=a.useDelayedTextureLoading;a.useDelayedTextureLoading=!1;const t=a._blockEntityCollection;a._blockEntityCollection=!1;const i=k.CreateFromBase64String(zP,"EnvironmentBRDFTexture"+WP++,a,!0,!1,k.BILINEAR_SAMPLINGMODE);a._blockEntityCollection=t;const s=a.getEngine().getLoadedTexturesCache(),r=s.indexOf(i.getInternalTexture());r!==-1&&s.splice(r,1),i.isRGBD=!0,i.wrapU=k.CLAMP_ADDRESSMODE,i.wrapV=k.CLAMP_ADDRESSMODE,a.environmentBRDFTexture=i,a.useDelayedTextureLoading=e,yx.ExpandRGBDTexture(i);const n=a.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=a.onBeforeRenderObservable.add(()=>{i.isReady()&&(a.onBeforeRenderObservable.remove(o),yx.ExpandRGBDTexture(i))})});a.onDisposeObservable.add(()=>{a.getEngine().onContextRestoredObservable.remove(n)})}return a.environmentBRDFTexture};class HP extends Vs{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class ws extends Zs{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new HP,t),this._useEnergyConservation=ws.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=ws.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=ws.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=ws.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=ws.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=ws.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=ws.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=ws.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}ws.DEFAULT_USE_ENERGY_CONSERVATION=!0;ws.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;ws.DEFAULT_USE_SPHERICAL_HARMONICS=!0;ws.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;E([I(),te("_markAllSubMeshesAsMiscDirty")],ws.prototype,"useEnergyConservation",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ws.prototype,"useSmithVisibilityHeightCorrelated",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ws.prototype,"useSphericalHarmonics",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ws.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const XP="pbrFragmentDeclaration",YP=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;
#ifdef ALBEDO
uniform vec2 vAlbedoInfos;
#endif
#ifdef AMBIENT
uniform vec4 vAmbientInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#ifdef REALTIME_FILTERING
uniform vec2 vReflectionFilteringInfo;
#endif
uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; 
#endif
#endif
#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; 
#endif
#ifdef CLEARCOAT
uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT
uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#endif
#ifdef IRIDESCENCE
uniform vec4 vIridescenceParams;
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
uniform vec3 vAnisotropy;
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
uniform vec4 vSheenColor;
#ifdef SHEEN_ROUGHNESS
uniform float vSheenRoughness;
#endif
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#ifdef REALTIME_FILTERING
uniform vec2 vRefractionFilteringInfo;
#endif
#ifdef SS_DISPERSION
uniform float dispersion;
#endif
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;
#endif
#ifdef PREPASS
#ifdef SS_SCATTERING
uniform float scatteringDiffusionProfile;
#endif
#endif
#if DEBUGMODE>0
uniform vec2 vDebugMode;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#define ADDITIONAL_FRAGMENT_DECLARATION
`;W.IncludesShadersStore[XP]=YP;const $P="pbrUboDeclaration",KP=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;W.IncludesShadersStore[$P]=KP;const jP="pbrFragmentExtraDeclaration",qP=`varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
`;W.IncludesShadersStore[jP]=qP;const QP="samplerFragmentAlternateDeclaration",ZP=`#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
#endif
`;W.IncludesShadersStore[QP]=ZP;const JP="pbrFragmentSamplersDeclaration",eM=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)
uniform sampler2D clearCoatRoughnessSampler;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)
uniform sampler2D sheenRoughnessSampler;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform samplerCube irradianceSampler;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform sampler2D irradianceSampler;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#endif
#ifdef ENVIRONMENTBRDF
uniform sampler2D environmentBrdfSampler;
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
#define sampleRefraction(s,c) textureCube(s,c)
uniform samplerCube refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;
#endif
#else
#define sampleRefraction(s,c) texture2D(s,c)
uniform sampler2D refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#endif
`;W.IncludesShadersStore[JP]=eM;const tM="subSurfaceScatteringFunctions",iM=`bool testLightingForSSS(float diffusionProfile)
{return diffusionProfile<1.;}`;W.IncludesShadersStore[tM]=iM;const sM="importanceSampling",rM=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { 
float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;W.IncludesShadersStore[sM]=rM;const nM="pbrHelperFunctions",aM=`#define MINIMUMVARIANCE 0.0005
float convertRoughnessToAverageSlope(float roughness)
{return square(roughness)+MINIMUMVARIANCE;}
float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}
vec2 getAARoughnessFactors(vec3 normalVector) {
#ifdef SPECULARAA
vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2(0.);
#endif
}
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_LEGACY
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}
#else
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}
#endif
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)
vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}
vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}
vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}
vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);return clearCoatAbsorption;}
#endif
#ifdef MICROSURFACEAUTOMATIC
float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)
{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}
#endif
`;W.IncludesShadersStore[nM]=aM;const oM="harmonicsFunctions",lM=`#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00
+ vSphericalL1_1*(normal.y)
+ vSphericalL10*(normal.z)
+ vSphericalL11*(normal.x)
+ vSphericalL2_2*(normal.y*normal.x)
+ vSphericalL2_1*(normal.y*normal.z)
+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+ vSphericalL21*(normal.z*normal.x)
+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}
#else
vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}
#endif
#endif
`;W.IncludesShadersStore[oM]=lM;const hM="pbrDirectLightingSetupFunctions",cM=`struct preLightingInfo
{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;
#ifdef IRIDESCENCE
float iridescenceIntensity;
#endif
};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));
#endif
return result;}`;W.IncludesShadersStore[hM]=cM;const uM="pbrDirectLightingFalloffFunctions",dM=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)
{return max(0.,1.0-length(lightOffset)/range);}
float computeDistanceLightFalloff_Physical(float lightDistanceSquared)
{return 1.0/maxEps(lightDistanceSquared);}
float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)
{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}
float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)
{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)
{falloff=max(0.,pow(cosAngle,exponent));}
return falloff;}
float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)
{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; 
float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}
float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)
{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}
float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;W.IncludesShadersStore[uM]=dM;const fM="pbrBRDFFunctions",_M=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}
#endif
#ifdef ENVIRONMENTBRDF
vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup.rgb=fromRGBD(brdfLookup.rgba);
#endif
return brdfLookup.rgb;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;}
#endif
/* NOT USED
#if defined(SHEEN) && defined(SHEEN_SOFTER)
float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)
{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}
#endif
*/
#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
/**
* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.
* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table
*/
vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}
#endif
vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
#ifdef CLEARCOAT
vec3 getR0RemappedForClearCoat(vec3 f0) {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturate(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);
#endif
}
#endif
#ifdef IRIDESCENCE
const mat3 XYZ_TO_REC709=mat3(
3.2404542,-0.9692660, 0.0556434,
-1.5371385, 1.8760108,-0.2040259,
-0.4985314, 0.0415560, 1.0572252
);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}
vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}
float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}
vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}
vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}
float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); 
vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)
{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}
return max(I,vec3(0.0));}
#endif
float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)
{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}
#ifdef SHEEN
float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)
{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}
#endif
#ifdef ANISOTROPIC
float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}
#endif
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {
#ifdef MOBILE
float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);
#else
float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);
#endif
}
#else
float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)
{
#ifdef MOBILE
return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)
{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}
#endif
#ifdef ANISOTROPIC
float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}
#endif
#ifdef CLEARCOAT
float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }
#endif
#ifdef SHEEN
float visibility_Ashikhmin(float NdotL,float NdotV)
{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}
/* NOT USED
#ifdef SHEEN_SOFTER
float l(float x,float alphaG)
{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}
float lambdaSheen(float cosTheta,float alphaG)
{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}
float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)
{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}
#endif
*/
#endif
float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}
#ifdef SS_TRANSLUCENCY
vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}
float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}
#endif
`;W.IncludesShadersStore[fM]=_M;const pM="hdrFilteringFunctions",mM=`#ifdef NUM_SAMPLES
#if NUM_SAMPLES>0
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
float radicalInverse_VdC(uint bits) 
{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; }
vec2 hammersley(uint i,uint N)
{return vec2(float(i)/float(N),radicalInverse_VdC(i));}
#else
float vanDerCorpus(int n,int base)
{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)
{if(n>0)
{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}
return result;}
vec2 hammersley(int i,int N)
{return vec2(float(i)/float(N),vanDerCorpus(i,2));}
#endif
float log4(float x) {return log2(x)/2.;}
const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;
#define inline
vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c;}}
result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}
#define inline
vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; 
if (alphaG==0.) {
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.;
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}}
#endif
#endif
`;W.IncludesShadersStore[pM]=mM;const gM="pbrDirectLightingFunctions",xM=`#define CLEARCOATREFLECTANCE90 1.0
struct lightingInfo
{vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef CLEARCOAT
vec4 clearCoat;
#endif
#ifdef SHEEN
vec3 sheen;
#endif
};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;
#else
return roughness;
#endif
}
vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}
vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}
#ifdef SS_TRANSLUCENCY
vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}
#endif
#ifdef SPECULARTERM
vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef ANISOTROPIC
vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef CLEARCOAT
vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);}
vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}
#endif
#ifdef SHEEN
vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER
float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);
#else */
float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */
float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}
#endif
`;W.IncludesShadersStore[gM]=xM;const TM="pbrIBLFunctions",EM=`#if defined(REFLECTION) || defined(SS_REFRACTION)
float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}
float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);}
#endif
#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
#define UNPACK_LOD(x) (1.0-x)*255.0
float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}
#endif
`;W.IncludesShadersStore[TM]=EM;const SM="pbrBlockAlbedoOpacity",CM=`struct albedoOpacityOutParams
{vec3 surfaceAlbedo;float alpha;};
#define pbr_inline
void albedoOpacityBlock(
in vec4 vAlbedoColor,
#ifdef ALBEDO
in vec4 albedoTexture,
in vec2 albedoInfos,
#endif
#ifdef OPACITY
in vec4 opacityMap,
in vec2 vOpacityInfos,
#endif
#ifdef DETAIL
in vec4 detailColor,
in vec4 vDetailInfos,
#endif
#ifdef DECAL
in vec4 decalColor,
in vec4 vDecalInfos,
#endif
out albedoOpacityOutParams outParams
)
{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpace(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifndef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
surfaceAlbedo*=vColor.rgb;
#endif
#ifdef DETAIL
float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; 
#endif
#ifdef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO
#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST 
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;}
`;W.IncludesShadersStore[SM]=CM;const vM="pbrBlockReflectivity",bM=`struct reflectivityOutParams
{float microSurface;float roughness;vec3 surfaceReflectivityColor;
#ifdef METALLICWORKFLOW
vec3 surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
vec3 ambientOcclusionColor;
#endif
#if DEBUGMODE>0
#ifdef METALLICWORKFLOW
vec2 metallicRoughness;
#ifdef REFLECTIVITY
vec4 surfaceMetallicColorMap;
#endif
#ifndef FROSTBITE_REFLECTANCE
vec3 metallicF0;
#endif
#else
#ifdef REFLECTIVITY
vec4 surfaceReflectivityColorMap;
#endif
#endif
#endif
};
#define pbr_inline
void reflectivityBlock(
in vec4 vReflectivityColor,
#ifdef METALLICWORKFLOW
in vec3 surfaceAlbedo,
in vec4 metallicReflectanceFactors,
#endif
#ifdef REFLECTIVITY
in vec3 reflectivityInfos,
in vec4 surfaceMetallicOrReflectivityColorMap,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
in vec3 ambientOcclusionColorIn,
#endif
#ifdef MICROSURFACEMAP
in vec4 microSurfaceTexel,
#endif
#ifdef DETAIL
in vec4 detailColor,
in vec4 vDetailInfos,
#endif
out reflectivityOutParams outParams
)
{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec2 metallicRoughness=surfaceReflectivityColor.rg;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#if DEBUGMODE>0
outParams.metallicRoughness=metallicRoughness;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;
#ifdef FROSTBITE_REFLECTANCE
outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);
#else
vec3 metallicF0=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=metallicF0;
#endif
outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);
#endif
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
#endif
microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;}
`;W.IncludesShadersStore[vM]=bM;const AM="pbrBlockAmbientOcclusion",yM=`struct ambientOcclusionOutParams
{vec3 ambientOcclusionColor;
#if DEBUGMODE>0 && defined(AMBIENT)
vec3 ambientOcclusionColorMap;
#endif
};
#define pbr_inline
void ambientOcclusionBlock(
#ifdef AMBIENT
in vec3 ambientOcclusionColorMap_,
in vec4 vAmbientInfos,
#endif
out ambientOcclusionOutParams outParams
)
{vec3 ambientOcclusionColor=vec3(1.,1.,1.);
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;}
`;W.IncludesShadersStore[AM]=yM;const RM="pbrBlockAlphaFresnel",IM=`#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{float alpha;};
#define pbr_inline
void alphaFresnelBlock(
in vec3 normalW,
in vec3 viewDirectionW,
in float alpha,
in float microSurface,
out alphaFresnelOutParams outParams
)
{float opacityPerceptual=alpha;
#ifdef LINEARALPHAFRESNEL
float opacity0=opacityPerceptual;
#else
float opacity0=opacityPerceptual*opacityPerceptual;
#endif
float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE)
discard;
#ifndef ALPHABLEND
outParams.alpha=1.0;
#endif
#endif
}
#endif
#endif
`;W.IncludesShadersStore[RM]=IM;const PM="pbrBlockAnisotropic",MM=`#ifdef ANISOTROPIC
struct anisotropicOutParams
{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;
#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)
vec3 anisotropyMapData;
#endif
};
#define pbr_inline
void anisotropicBlock(
in vec3 vAnisotropy,
in float roughness,
#ifdef ANISOTROPIC_TEXTURE
in vec3 anisotropyMapData,
#endif
in mat3 TBN,
in vec3 normalW,
in vec3 viewDirectionW,
out anisotropicOutParams outParams
)
{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
anisotropy*=anisotropyMapData.b;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;
#ifdef ANISOTROPIC_LEGACY
anisotropyDirection.rg*=anisotropyMapData.rg;
#else
anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);
#endif
#endif
mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);}
#endif
`;W.IncludesShadersStore[PM]=MM;const DM="pbrBlockReflection",OM=`#ifdef REFLECTION
struct reflectionOutParams
{vec4 environmentRadiance;vec3 environmentIrradiance;
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords;
#else
vec2 reflectionCoords;
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
vec3 irradianceVector;
#endif
#endif
#endif
};
#define pbr_inline
void createReflectionCoords(
in vec3 vPositionW,
in vec3 normalW,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REFLECTIONMAP_3D
out vec3 reflectionCoords
#else
out vec2 reflectionCoords
#endif
)
{
#ifdef ANISOTROPIC
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
}
#define pbr_inline
#define inline
void sampleReflectionTexture(
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
const vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
const vec2 reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out vec4 environmentRadiance
)
{
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA
float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);
#else
float requestedReflectionLOD=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#endif
#else
float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);} else {environmentRadiance=mix(
environmentMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif
environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}
#define pbr_inline
#define inline
void reflectionBlock(
in vec3 vPositionW,
in vec3 normalW,
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
#else
in sampler2D reflectionSampler,
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
in vec3 vEnvironmentIrradiance,
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
in mat4 reflectionMatrix,
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
in samplerCube irradianceSampler,
#else
in sampler2D irradianceSampler,
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out reflectionOutParams outParams
)
{vec4 environmentRadiance=vec4(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.);
#else
vec2 reflectionCoords=vec2(0.);
#endif
createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
reflectionCoords
);sampleReflectionTexture(
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
#ifdef REFLECTIONMAP_3D
reflectionSampler,
reflectionCoords,
#else
reflectionSampler,
reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentRadiance
);vec3 environmentIrradiance=vec3(0.,0.,0.);
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#ifdef ANISOTROPIC
vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;
#else
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;}
#endif
`;W.IncludesShadersStore[DM]=OM;const NM="pbrBlockSheen",FM=`#ifdef SHEEN
struct sheenOutParams
{float sheenIntensity;vec3 sheenColor;float sheenRoughness;
#ifdef SHEEN_LINKWITHALBEDO
vec3 surfaceAlbedo;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
float sheenAlbedoScaling;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 finalSheenRadianceScaled;
#endif
#if DEBUGMODE>0
#ifdef SHEEN_TEXTURE
vec4 sheenMapData;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 sheenEnvironmentReflectance;
#endif
#endif
};
#define pbr_inline
#define inline
void sheenBlock(
in vec4 vSheenColor,
#ifdef SHEEN_ROUGHNESS
in float vSheenRoughness,
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
in vec4 sheenMapRoughnessData,
#endif
#endif
in float roughness,
#ifdef SHEEN_TEXTURE
in vec4 sheenMapData,
in float sheenMapLevel,
#endif
in float reflectance,
#ifdef SHEEN_LINKWITHALBEDO
in vec3 baseColor,
in vec3 surfaceAlbedo,
#endif
#ifdef ENVIRONMENTBRDF
in float NdotV,
in vec3 environmentBrdf,
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
in vec2 AARoughnessFactors,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
in vec4 vLightingIntensity,
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
in vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
in vec2 reflectionCoords,
#endif
in float NdotVUnclamped,
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
in float seo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
in float eho,
#endif
#endif
out sheenOutParams outParams
)
{float sheenIntensity=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
vec3 sheenColor=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor.rgb*=toLinearSpace(sheenMapData.rgb);
#else
sheenColor.rgb*=sheenMapData.rgb;
#endif
sheenColor.rgb*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
float sheenRoughness=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL
sheenRoughness*=sheenMapData.a;
#else
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#endif
#else
float sheenRoughness=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif
#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif
sheenColor*=sheenIntensity;
#endif
#ifdef ENVIRONMENTBRDF
/*#ifdef SHEEN_SOFTER
vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));
#else*/
#ifdef SHEEN_ROUGHNESS
vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);
#else
vec3 environmentSheenBrdf=environmentBrdf;
#endif
/*#endif*/
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA
sheenAlphaG+=AARoughnessFactors.y;
#endif
vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(
sheenAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
sheenRoughness,
#endif
reflectionSampler,
reflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentSheenRadiance
);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif
outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;}
#endif
`;W.IncludesShadersStore[NM]=FM;const wM="pbrBlockClearcoat",LM=`struct clearcoatOutParams
{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;
#ifdef REFLECTION
vec3 finalClearCoatRadianceScaled;
#endif
#ifdef CLEARCOAT_TINT
vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
vec3 energyConservationFactorClearCoat;
#endif
#if DEBUGMODE>0
#ifdef CLEARCOAT_BUMP
mat3 TBNClearCoat;
#endif
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData;
#endif
#ifdef REFLECTION
vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;
#endif
float clearCoatNdotV;
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
#define inline
void clearcoatBlock(
in vec3 vPositionW,
in vec3 geometricNormalW,
in vec3 viewDirectionW,
in vec2 vClearCoatParams,
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
in vec4 clearCoatMapRoughnessData,
#endif
in vec3 specularEnvironmentR0,
#ifdef CLEARCOAT_TEXTURE
in vec2 clearCoatMapData,
#endif
#ifdef CLEARCOAT_TINT
in vec4 vClearCoatTintParams,
in float clearCoatColorAtDistance,
in vec4 vClearCoatRefractionParams,
#ifdef CLEARCOAT_TINT_TEXTURE
in vec4 clearCoatTintMapData,
#endif
#endif
#ifdef CLEARCOAT_BUMP
in vec2 vClearCoatBumpInfos,
in vec4 clearCoatBumpMapData,
in vec2 vClearCoatBumpUV,
#if defined(TANGENT) && defined(NORMAL)
in mat3 vTBN,
#else
in vec2 vClearCoatTangentSpaceParams,
#endif
#ifdef OBJECTSPACE_NORMALMAP
in mat4 normalMatrix,
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
in vec3 faceNormal,
#endif
#ifdef REFLECTION
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
in vec4 vLightingIntensity,
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
#else
in sampler2D reflectionSampler,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
in float ambientMonochrome,
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
in float frontFacingMultiplier,
#endif
out clearcoatOutParams outParams
)
{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL
clearCoatRoughness*=clearCoatMapData.y;
#else
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
#endif
outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;
#endif
#ifdef CLEARCOAT_REMAP_F0
vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
vec3 specularEnvironmentR0Updated=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
float clearCoatNormalScale=1.0;
#else
float clearCoatNormalScale=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBNClearCoat=vTBN;
#else
vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT
vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif
#if defined(REFLECTION)
float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA
clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 clearCoatReflectionCoords=clearCoatReflectionVector;
#else
vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
sampleReflectionTexture(
clearCoatAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
clearCoatNdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
clearCoatRoughness,
#endif
reflectionSampler,
clearCoatReflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentClearCoatRadiance
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else
vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)
outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif
float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
}
#endif
`;W.IncludesShadersStore[wM]=LM;const BM="pbrBlockIridescence",UM=`struct iridescenceOutParams
{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};
#ifdef IRIDESCENCE
#define pbr_inline
#define inline
void iridescenceBlock(
in vec4 vIridescenceParams,
in float viewAngle,
in vec3 specularEnvironmentR0,
#ifdef IRIDESCENCE_TEXTURE
in vec2 iridescenceMapData,
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
in vec2 iridescenceThicknessMapData,
#endif
#ifdef CLEARCOAT
in float NdotVUnclamped,
#ifdef CLEARCOAT_TEXTURE
in vec2 clearCoatMapData,
#endif
#endif
out iridescenceOutParams outParams
)
{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;
#ifdef IRIDESCENCE_TEXTURE
iridescenceIntensity*=iridescenceMapData.x;
#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE
iridescenceThicknessWeight=iridescenceMapData.g;
#endif
#endif
#if defined(IRIDESCENCE_THICKNESS_TEXTURE)
iridescenceThicknessWeight=iridescenceThicknessMapData.g;
#endif
float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; 
#ifdef CLEARCOAT
float clearCoatIntensity=vClearCoatParams.x;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#endif
topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));
#endif
vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;}
#endif
`;W.IncludesShadersStore[BM]=UM;const VM="pbrBlockSubSurface",kM=`struct subSurfaceOutParams
{vec3 specularEnvironmentReflectance;
#ifdef SS_REFRACTION
vec3 finalRefraction;vec3 surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
float alpha;
#endif
#ifdef REFLECTION
float refractionFactorForIrradiance;
#endif
#endif
#ifdef SS_TRANSLUCENCY
vec3 transmittance;float translucencyIntensity;
#ifdef REFLECTION
vec3 refractionIrradiance;
#endif
#endif
#if DEBUGMODE>0
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction;vec3 refractionTransmittance;
#endif
#endif
};
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#define pbr_inline
#define inline
vec4 sampleEnvironmentRefraction(
in float ior
,in float thickness
,in float refractionLOD
,in vec3 normalW
,in vec3 vPositionW
,in vec3 viewDirectionW
,in mat4 view
,in vec4 vRefractionInfos
,in mat4 refractionMatrix
,in vec4 vRefractionMicrosurfaceInfos
,in float alphaG
#ifdef SS_REFRACTIONMAP_3D
,in samplerCube refractionSampler
#ifndef LODBASEDMICROSFURACE
,in samplerCube refractionSamplerLow
,in samplerCube refractionSamplerHigh
#endif
#else
,in sampler2D refractionSampler
#ifndef LODBASEDMICROSFURACE
,in sampler2D refractionSamplerLow
,in sampler2D refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,in vec2 vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,in vec3 refractionPosition
,in vec3 refractionSize
#endif
) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef ANISOTROPIC
vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);
#else
vec3 refractionVector=refract(-viewDirectionW,normalW,ior);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif
#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
#endif
vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;
#endif
#ifdef LODBASEDMICROSFURACE
refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA
float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);
#else
float requestedRefractionLOD=refractionLOD;
#endif
#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)
environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(
sampleRefraction(refractionSamplerHigh,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);} else {environmentRefraction=mix(
environmentRefractionMid,
sampleRefraction(refractionSamplerLow,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);}
#endif
#ifdef SS_RGBDREFRACTION
environmentRefraction.rgb=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);
#endif
return environmentRefraction;}
#endif
#define pbr_inline
#define inline
void subSurfaceBlock(
in vec3 vSubSurfaceIntensity,
in vec2 vThicknessParam,
in vec4 vTintColor,
in vec3 normalW,
in vec3 specularEnvironmentReflectance,
#ifdef SS_THICKNESSANDMASK_TEXTURE
in vec4 thicknessMap,
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
in vec4 refractionIntensityMap,
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
in vec4 translucencyIntensityMap,
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
in mat4 reflectionMatrix,
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
in vec3 irradianceVector_,
#endif
#if defined(REALTIME_FILTERING)
in samplerCube reflectionSampler,
in vec2 vReflectionFilteringInfo,
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
in samplerCube irradianceSampler,
#else
in sampler2D irradianceSampler,
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
in vec3 surfaceAlbedo,
#endif
#ifdef SS_REFRACTION
in vec3 vPositionW,
in vec3 viewDirectionW,
in mat4 view,
in vec4 vRefractionInfos,
in mat4 refractionMatrix,
in vec4 vRefractionMicrosurfaceInfos,
in vec4 vLightingIntensity,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
in float alpha,
#endif
#ifdef SS_LODINREFRACTIONALPHA
in float NdotVUnclamped,
#endif
#ifdef SS_LINEARSPECULARREFRACTION
in float roughness,
#endif
in float alphaG,
#ifdef SS_REFRACTIONMAP_3D
in samplerCube refractionSampler,
#ifndef LODBASEDMICROSFURACE
in samplerCube refractionSamplerLow,
in samplerCube refractionSamplerHigh,
#endif
#else
in sampler2D refractionSampler,
#ifndef LODBASEDMICROSFURACE
in sampler2D refractionSamplerLow,
in sampler2D refractionSamplerHigh,
#endif
#endif
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REALTIME_FILTERING
in vec2 vRefractionFilteringInfo,
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
in vec3 refractionPosition,
in vec3 refractionSize,
#endif
#ifdef SS_DISPERSION
in float dispersion,
#endif
#endif
#ifdef SS_TRANSLUCENCY
in vec3 vDiffusionDistance,
#endif
out subSurfaceOutParams outParams
)
{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;
#ifdef SS_REFRACTION
float refractionIntensity=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
float translucencyIntensity=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#if defined(SS_USE_GLTF_TEXTURES)
float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#ifdef SS_MASK_FROM_THICKNESS_TEXTURE
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)
#if defined(SS_USE_GLTF_TEXTURES)
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
float thickness=vThicknessParam.y;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
translucencyIntensity*=translucencyIntensityMap.b;
#endif
#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef SS_HAS_THICKNESS
float ior=vRefractionInfos.y;
#else
float ior=vRefractionMicrosurfaceInfos.w;
#endif
#ifdef SS_LODINREFRACTIONALPHA
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
float refraction_ior=vRefractionInfos.y;
#ifdef SS_DISPERSION
float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];
#endif
vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#else
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition
,refractionSize
#endif
);
#ifdef SS_DISPERSION
environmentRefraction[i]=envSample[i];}
#else
environmentRefraction=envSample;
#endif
environmentRefraction.rgb*=vRefractionInfos.x;
#endif
#ifdef SS_REFRACTION
vec3 refractionTransmittance=vec3(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;
#else
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT
environmentRefraction.rgb*=surfaceAlbedo.rgb;
#endif
outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);
#ifdef REFLECTION
outParams.refractionFactorForIrradiance=(1.-refractionIntensity);
#endif
#ifdef UNUSED_MULTIPLEBOUNCES
vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
#endif
refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif
#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
vec3 irradianceVector=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);
#else
vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec3 irradianceCoords=irradianceVector;
#else
vec2 irradianceCoords=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);
#ifdef RGBDREFLECTION
refractionIrradiance.rgb=fromRGBD(refractionIrradiance);
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);
#endif
#else
vec4 refractionIrradiance=vec4(0.);
#endif
refractionIrradiance.rgb*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT
refractionIrradiance.rgb*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance.rgb;
#endif
}
#endif
`;W.IncludesShadersStore[VM]=kM;const GM="pbrBlockNormalGeometric",zM=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#endif
vec3 geometricNormalW=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;
#endif
`;W.IncludesShadersStore[GM]=zM;const WM="pbrBlockNormalFinal",HM=`#if defined(FORCENORMALFORWARD) && defined(NORMAL)
vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
`;W.IncludesShadersStore[WM]=HM;const XM="pbrBlockLightmapInit",YM=`#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor.rgb=toLinearSpace(lightmapColor.rgb);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
`;W.IncludesShadersStore[XM]=YM;const $M="pbrBlockGeometryInfo",KM=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA
alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)
vec3 environmentBrdf=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
float ambientMonochrome=aoOut.ambientOcclusionColor.r;
#else
float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);
#endif
float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;W.IncludesShadersStore[$M]=KM;const jM="pbrBlockReflectance0",qM=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);
#else 
vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);
#endif
#ifdef ALPHAFRESNEL
float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;W.IncludesShadersStore[jM]=qM;const QM="pbrBlockReflectance",ZM=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);
#ifdef RADIANCEOCCLUSION
specularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
specularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else
vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));
#endif
#ifdef CLEARCOAT
specularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
specularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;W.IncludesShadersStore[QM]=ZM;const JM="pbrBlockDirectLighting",eD=`vec3 diffuseBase=vec3(0.,0.,0.);
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
#ifdef CLEARCOAT
vec3 clearCoatBase=vec3(0.,0.,0.);
#endif
#ifdef SHEEN
vec3 sheenBase=vec3(0.,0.,0.);
#endif
preLightingInfo preInfo;lightingInfo info;float shadow=1.; 
float aggShadow=0.;float numLights=0.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
vec3 absorption=vec3(0.);
#endif
`;W.IncludesShadersStore[JM]=eD;const tD="pbrBlockFinalLitComponents",iD=`aggShadow=aggShadow/numLights;
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif
#ifdef REFLECTION
vec3 finalIrradiance=reflectionOut.environmentIrradiance;
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef REFLECTION
vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef SHEEN
vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef CLEARCOAT
vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef ALPHABLEND
float luminanceOverAlpha=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;W.IncludesShadersStore[tD]=iD;const sD="pbrBlockFinalUnlitComponents",rD=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;
#ifdef EMISSIVE
vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpace(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*= vEmissiveInfos.y;
#endif
finalEmissive*=vLightingIntensity.y;
#ifdef AMBIENT
vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);
#else
vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;W.IncludesShadersStore[sD]=rD;const nD="pbrBlockFinalColorComposition",aD=`vec4 finalColor=vec4(
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalAmbient +
finalDiffuse,
alpha);
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor.rgb*=lightmapColor.rgb;
#else
finalColor.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
finalColor.rgb+=finalEmissive;
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,0.0);
`;W.IncludesShadersStore[nD]=aD;const oD="pbrBlockImageProcessing",lD=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
#if !defined(SKIPFINALCOLORCLAMP)
finalColor.rgb=clamp(finalColor.rgb,0.,30.0);
#endif
#else
finalColor=applyImageProcessing(finalColor);
#endif
finalColor.a*=visibility;
#ifdef PREMULTIPLYALPHA
finalColor.rgb*=finalColor.a;
#endif
`;W.IncludesShadersStore[oD]=lD;const hD="pbrDebug",cD=`#if DEBUGMODE>0
if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {
#if DEBUGMODE==1
gl_FragColor.rgb=vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==2 && defined(NORMAL)
gl_FragColor.rgb=vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==5
gl_FragColor.rgb=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==6 && defined(MAINUV1)
gl_FragColor.rgb=vec3(vMainUV1,0.0);
#elif DEBUGMODE==7 && defined(MAINUV2)
gl_FragColor.rgb=vec3(vMainUV2,0.0);
#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==10 && defined(CLEARCOAT)
gl_FragColor.rgb=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==11 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==12 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==13 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==20 && defined(ALBEDO)
gl_FragColor.rgb=albedoTexture.rgb;
#ifndef GAMMAALBEDO
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==21 && defined(AMBIENT)
gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE==22 && defined(OPACITY)
gl_FragColor.rgb=opacityMap.rgb;
#elif DEBUGMODE==23 && defined(EMISSIVE)
gl_FragColor.rgb=emissiveColorTex.rgb;
#ifndef GAMMAEMISSIVE
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==24 && defined(LIGHTMAP)
gl_FragColor.rgb=lightmapColor.rgb;
#ifndef GAMMALIGHTMAP
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
gl_FragColor.rgb=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;
#elif DEBUGMODE==32 && defined(BUMP)
gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;
#elif DEBUGMODE==40 && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==41 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)
gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==50
gl_FragColor.rgb=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==51 && defined(SPECULARTERM)
gl_FragColor.rgb=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==52 && defined(CLEARCOAT)
gl_FragColor.rgb=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==53 && defined(SHEEN)
gl_FragColor.rgb=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==54 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==60
gl_FragColor.rgb=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==61
gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);
#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.metallicF0;
#elif DEBUGMODE==63
gl_FragColor.rgb=vec3(roughness);
#elif DEBUGMODE==64
gl_FragColor.rgb=vec3(alphaG);
#elif DEBUGMODE==65
gl_FragColor.rgb=vec3(NdotV);
#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==67 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE==68 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
gl_FragColor.rgb=subSurfaceOut.transmittance;
#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.refractionTransmittance;
#elif DEBUGMODE==72
gl_FragColor.rgb=vec3(microSurface);
#elif DEBUGMODE==73
gl_FragColor.rgb=vAlbedoColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=vReflectivityColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==75
gl_FragColor.rgb=vEmissiveColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)
gl_FragColor.rgb=vec3(seo);
#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
gl_FragColor.rgb=vec3(eho);
#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)
gl_FragColor.rgb=vec3(energyConservationFactor);
#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=specularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)
gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==86 && defined(ALPHABLEND)
gl_FragColor.rgb=vec3(luminanceOverAlpha);
#elif DEBUGMODE==87
gl_FragColor.rgb=vec3(alpha);
#elif DEBUGMODE==88 && defined(ALBEDO)
gl_FragColor.rgb=vec3(albedoTexture.a);
#else
float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);
#endif
gl_FragColor.rgb*=vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);
#endif
gl_FragColor.a=1.0;
#ifdef PREPASS
gl_FragData[0]=toLinearSpace(gl_FragColor); 
gl_FragData[1]=vec4(0.,0.,0.,0.); 
#endif
#ifdef DEBUGMODE_FORCERETURN
return;
#endif
}
#endif
`;W.IncludesShadersStore[hD]=cD;const uD="pbrPixelShader",dD=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#extension GL_OES_standard_derivatives : enable
#endif
#ifdef LODBASEDMICROSFURACE
#extension GL_EXT_shader_texture_lod : enable
#endif
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
precision highp float;
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<__decl__pbrFragment>
#include<pbrFragmentExtraDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockIridescence>
#include<pbrBlockSubSurface>
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>
albedoOpacityOutParams albedoOpacityOut;
#ifdef ALBEDO
vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#endif
#ifdef DECAL
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#endif
albedoOpacityBlock(
vAlbedoColor,
#ifdef ALBEDO
albedoTexture,
vAlbedoInfos,
#endif
#ifdef OPACITY
opacityMap,
vOpacityInfos,
#endif
#ifdef DETAIL
detailColor,
vDetailInfos,
#endif
#ifdef DECAL
decalColor,
vDecalInfos,
#endif
albedoOpacityOut
);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
ambientOcclusionOutParams aoOut;
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;
#endif
ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
vAmbientInfos,
#endif
aoOut
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
vec3 diffuseBase=vec3(1.,1.,1.);
#else
vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;
#if defined(REFLECTIVITY)
vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;
#endif
#endif
#if defined(MICROSURFACEMAP)
vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;
#endif
#ifdef METALLICWORKFLOW
vec4 metallicReflectanceFactors=vMetallicReflectanceFactors;
#ifdef REFLECTANCE
vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);
#endif
metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;
#endif
#ifdef METALLIC_REFLECTANCE
vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;
#endif
metallicReflectanceFactors*=metallicReflectanceFactorsMap.a;
#endif
#endif
reflectivityBlock(
vReflectivityColor,
#ifdef METALLICWORKFLOW
surfaceAlbedo,
metallicReflectanceFactors,
#endif
#ifdef REFLECTIVITY
vReflectivityInfos,
surfaceMetallicOrReflectivityColorMap,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor,
#endif
#ifdef MICROSURFACEMAP
microSurfaceTexel,
#endif
#ifdef DETAIL
detailColor,
vDetailInfos,
#endif
reflectivityOut
);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif
#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface,
alphaFresnelOut
);alpha=alphaFresnelOut.alpha;
#endif
#endif
#include<pbrBlockGeometryInfo>
#ifdef ANISOTROPIC
anisotropicOutParams anisotropicOut;
#ifdef ANISOTROPIC_TEXTURE
vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;
#endif
anisotropicBlock(
vAnisotropy,
roughness,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW,
anisotropicOut
);
#endif
#ifdef REFLECTION
reflectionOutParams reflectionOut;
#ifndef USE_CUSTOM_REFLECTION
reflectionBlock(
vPositionW,
normalW,
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
reflectionSampler,
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
vEnvironmentIrradiance,
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
reflectionMatrix,
#endif
#endif
#ifdef USEIRRADIANCEMAP
irradianceSampler,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
reflectionOut
);
#else
#define CUSTOM_REFLECTION
#endif
#endif
#include<pbrBlockReflectance0>
#ifdef SHEEN
sheenOutParams sheenOut;
#ifdef SHEEN_TEXTURE
vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;
#endif
sheenBlock(
vSheenColor,
#ifdef SHEEN_ROUGHNESS
vSheenRoughness,
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
sheenMapRoughnessData,
#endif
#endif
roughness,
#ifdef SHEEN_TEXTURE
sheenMapData,
vSheenInfos.y,
#endif
reflectance,
#ifdef SHEEN_LINKWITHALBEDO
baseColor,
surfaceAlbedo,
#endif
#ifdef ENVIRONMENTBRDF
NdotV,
environmentBrdf,
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
AARoughnessFactors,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
vLightingIntensity,
reflectionSampler,
reflectionOut.reflectionCoords,
NdotVUnclamped,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
seo,
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
eho,
#endif
#endif
sheenOut
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;
#endif
#endif
#ifdef IRIDESCENCE
iridescenceOutParams iridescenceOut;
#ifdef IRIDESCENCE_TEXTURE
vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;
#endif
iridescenceBlock(
vIridescenceParams,
NdotV,
specularEnvironmentR0,
#ifdef IRIDESCENCE_TEXTURE
iridescenceMapData,
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
iridescenceThicknessMapData,
#endif
#ifdef CLEARCOAT
NdotVUnclamped,
#ifdef CLEARCOAT_TEXTURE
clearCoatMapData,
#endif
#endif
iridescenceOut
);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;
#endif
clearcoatOutParams clearcoatOut;
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);
#endif
clearcoatBlock(
vPositionW,
geometricNormalW,
viewDirectionW,
vClearCoatParams,
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatMapRoughnessData,
#endif
specularEnvironmentR0,
#ifdef CLEARCOAT_TEXTURE
clearCoatMapData,
#endif
#ifdef CLEARCOAT_TINT
vClearCoatTintParams,
clearCoatColorAtDistance,
vClearCoatRefractionParams,
#ifdef CLEARCOAT_TINT_TEXTURE
clearCoatTintMapData,
#endif
#endif
#ifdef CLEARCOAT_BUMP
vClearCoatBumpInfos,
clearCoatBumpMapData,
vClearCoatBumpUV,
#if defined(TANGENT) && defined(NORMAL)
vTBN,
#else
vClearCoatTangentSpaceParams,
#endif
#ifdef OBJECTSPACE_NORMALMAP
normalMatrix,
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
faceNormal,
#endif
#ifdef REFLECTION
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
vLightingIntensity,
reflectionSampler,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
ambientMonochrome,
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
(gl_FrontFacing ? 1. : -1.),
#endif
clearcoatOut
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif
#include<pbrBlockReflectance>
subSurfaceOutParams subSurfaceOut;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);
#endif
subSurfaceBlock(
vSubSurfaceIntensity,
vThicknessParam,
vTintColor,
normalW,
specularEnvironmentReflectance,
#ifdef SS_THICKNESSANDMASK_TEXTURE
thicknessMap,
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
refractionIntensityMap,
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
translucencyIntensityMap,
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
reflectionMatrix,
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
reflectionOut.irradianceVector,
#endif
#if defined(REALTIME_FILTERING)
reflectionSampler,
vReflectionFilteringInfo,
#endif
#endif
#ifdef USEIRRADIANCEMAP
irradianceSampler,
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
surfaceAlbedo,
#endif
#ifdef SS_REFRACTION
vPositionW,
viewDirectionW,
view,
vRefractionInfos,
refractionMatrix,
vRefractionMicrosurfaceInfos,
vLightingIntensity,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha,
#endif
#ifdef SS_LODINREFRACTIONALPHA
NdotVUnclamped,
#endif
#ifdef SS_LINEARSPECULARREFRACTION
roughness,
#endif
alphaG,
refractionSampler,
#ifndef LODBASEDMICROSFURACE
refractionSamplerLow,
refractionSamplerHigh,
#endif
#ifdef ANISOTROPIC
anisotropicOut,
#endif
#ifdef REALTIME_FILTERING
vRefractionFilteringInfo,
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
vRefractionPosition,
vRefractionSize,
#endif
#ifdef SS_DISPERSION
dispersion,
#endif
#endif
#ifdef SS_TRANSLUCENCY
vDiffusionDistance,
#endif
subSurfaceOut
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;
#endif
#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]
#include<pbrBlockFinalLitComponents>
#endif 
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
vec3 sqAlbedo=sqrt(surfaceAlbedo); 
#endif
#ifdef PREPASS_IRRADIANCE
vec3 irradiance=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); 
irradiance/=sqAlbedo;
#else
gl_FragData[0]=finalColor; 
float scatteringDiffusionProfile=255.;
#endif
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); 
#else
gl_FragData[0]=vec4(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); 
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); 
#endif
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); 
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`;W.ShadersStore[uD]=dD;const fD="pbrVertexDeclaration",_D=`uniform mat4 view;uniform mat4 viewProjection;
#ifdef ALBEDO
uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#ifdef REFLECTIVITY 
uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;
#endif
#ifdef METALLIC_REFLECTANCE
uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;
#endif
#ifdef REFLECTANCE
uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;
#endif
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#ifdef IRIDESCENCE
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
#endif
#ifdef NORMAL
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;W.IncludesShadersStore[fD]=_D;const pD="pbrVertexShader",mD=`precision highp float;
#include<__decl__pbrVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#endif
varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);
#include<prePassVertex>
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vClipSpacePosition=gl_Position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#include<uvVariableDeclaration>[2..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#endif
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[pD]=mD;class gD extends Vs{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class ds extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new gD,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=ds._DefaultIndexOfRefraction,this.indexOfRefraction=ds._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=q.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const s=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ue.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&ue.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&ue.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((i=this._textureRoughness)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.ClearCoatTextureEnabled?qt(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&ue.ClearCoatTextureEnabled?qt(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&ue.ClearCoatBumpTextureEnabled?qt(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===ds._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&ue.ClearCoatTintTextureEnabled?(qt(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,s){var u,d,f,_;if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,h=this._material._invertNormalMapY,c=r.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!n||!e.isSync){c&&ue.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Gt(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&ue.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",((u=this._texture)==null?void 0:u.coordinatesIndex)??0,((d=this._texture)==null?void 0:d.level)??0,((f=this._textureRoughness)==null?void 0:f.coordinatesIndex)??0,((_=this._textureRoughness)==null?void 0:_.level)??0),this._texture&&Gt(this._texture,e,"clearCoat"),this._textureRoughness&&!c&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Gt(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&ue.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Gt(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,h?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,h?-1:1)),this._tintTexture&&ue.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Gt(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const p=1-this._indexOfRefraction,g=1+this._indexOfRefraction,x=Math.pow(-p/g,2),T=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",x,T,p,g),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&ue.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!c&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ue.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&ue.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&ue.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,s,r;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(s=this._bumpTexture)==null||s.dispose(),(r=this._tintTexture)==null||r.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}ds._DefaultIndexOfRefraction=1.5;E([I(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"isEnabled",void 0);E([I()],ds.prototype,"intensity",void 0);E([I()],ds.prototype,"roughness",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"indexOfRefraction",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"texture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"useRoughnessFromMainTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"textureRoughness",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"remapF0OnInterfaceChange",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"bumpTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"isTintEnabled",void 0);E([li()],ds.prototype,"tintColor",void 0);E([I()],ds.prototype,"tintColorAtDistance",void 0);E([I()],ds.prototype,"tintThickness",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ds.prototype,"tintTexture",void 0);class xD extends Vs{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class zs extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new xD,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=zs._DefaultMinimumThickness,this.maximumThickness=zs._DefaultMaximumThickness,this.indexOfRefraction=zs._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&ue.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=this._texture!==null&&this._texture._texture===((i=this._thicknessTexture)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.IridescenceTextureEnabled?qt(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&ue.IridescenceTextureEnabled?qt(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,s){var l,h,c,u;if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=r.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;(!e.useUbo||!n||!e.isSync)&&(o&&ue.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Gt(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&ue.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",((l=this._texture)==null?void 0:l.coordinatesIndex)??0,((h=this._texture)==null?void 0:h.level)??0,((c=this._thicknessTexture)==null?void 0:c.coordinatesIndex)??0,((u=this._thicknessTexture)==null?void 0:u.level)??0),this._texture&&Gt(this._texture,e,"iridescence"),this._thicknessTexture&&!o&&!r.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Gt(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&ue.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!o&&!r.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&ue.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}zs._DefaultMinimumThickness=100;zs._DefaultMaximumThickness=400;zs._DefaultIndexOfRefraction=1.3;E([I(),te("_markAllSubMeshesAsTexturesDirty")],zs.prototype,"isEnabled",void 0);E([I()],zs.prototype,"intensity",void 0);E([I()],zs.prototype,"minimumThickness",void 0);E([I()],zs.prototype,"maximumThickness",void 0);E([I()],zs.prototype,"indexOfRefraction",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],zs.prototype,"texture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],zs.prototype,"thicknessTexture",void 0);class TD extends Vs{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Rc extends Zs{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new TD,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Z(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&ue.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(y.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.AnisotropicTextureEnabled?qt(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&ue.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Gt(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&ue.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}}E([I(),te("_markAllSubMeshesAsTexturesDirty")],Rc.prototype,"isEnabled",void 0);E([I()],Rc.prototype,"intensity",void 0);E([hm()],Rc.prototype,"direction",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Rc.prototype,"texture",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],Rc.prototype,"legacy",void 0);class ED extends Vs{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class Kn extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new ED,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=q.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ue.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=this._texture!==null&&this._texture._texture===((i=this._textureRoughness)==null?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ue.SheenTextureEnabled?(qt(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&ue.SheenTextureEnabled?qt(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){var l,h,c,u;if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=r.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!e.useUbo||!n||!e.isSync)&&(o&&ue.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Gt(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&ue.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",((l=this._texture)==null?void 0:l.coordinatesIndex)??0,((h=this._texture)==null?void 0:h.level)??0,((c=this._textureRoughness)==null?void 0:c.coordinatesIndex)??0,((u=this._textureRoughness)==null?void 0:u.level)??0),this._texture&&Gt(this._texture,e,"sheen"),this._textureRoughness&&!o&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Gt(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&ue.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!o&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ue.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}E([I(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"isEnabled",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"linkSheenWithAlbedo",void 0);E([I()],Kn.prototype,"intensity",void 0);E([li()],Kn.prototype,"color",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"texture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"useRoughnessFromMainTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"roughness",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"textureRoughness",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Kn.prototype,"albedoScaling",void 0);class SD extends Vs{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Ci extends Zs{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new SD,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=q.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=q.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&ue.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&ue.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,s=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,r=(i||!this._refractionIntensityTexture)&&(s||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&ue.ThicknessTextureEnabled&&qt(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&ue.RefractionIntensityTextureEnabled&&!r&&qt(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&ue.TranslucencyIntensityTextureEnabled&&!r&&qt(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&r,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&r,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&r,this._isRefractionEnabled&&t.texturesEnabled){const n=this._getRefractionTexture(t);n&&ue.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=n.isCube,e.SS_GAMMAREFRACTION=n.gammaSpace,e.SS_RGBDREFRACTION=n.isRGBD,e.SS_LINEARSPECULARREFRACTION=n.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,e.SS_LODINREFRACTIONALPHA=n.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=n.isCube&&n.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(U.Vector3[0]);const r=Math.max(Math.abs(U.Vector3[0].x),Math.abs(U.Vector3[0].y),Math.abs(U.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,l=r.LODBASEDMICROSFURACE,h=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&ue.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Gt(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&ue.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Gt(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&ue.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Gt(this._translucencyIntensityTexture,e,"translucencyIntensity")),h&&ue.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",h.getRefractionTextureMatrix());let c=1;h.isCube||h.depth&&(c=h.depth);const u=h.getSize().width,d=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",h.level,1/d,c,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",u,h.lodGenerationScale,h.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",u,ge.Log2(u)),h.boundingBoxSize){const f=h;e.updateVector3("vRefractionPosition",f.boundingBoxPosition),e.updateVector3("vRefractionSize",f.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&ue.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&ue.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&ue.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),h&&ue.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",h):(e.setTexture("refractionSampler",h._lodTextureMid||h),e.setTexture("refractionSamplerLow",h._lodTextureLow||h),e.setTexture("refractionSamplerHigh",h._lodTextureHigh||h))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){ue.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e}hasRenderTargetTextures(){return!!(ue.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"}]}}}E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"isRefractionEnabled",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"isTranslucencyEnabled",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"isDispersionEnabled",void 0);E([I(),te("_markScenePrePassDirty")],Ci.prototype,"isScatteringEnabled",void 0);E([I()],Ci.prototype,"_scatteringDiffusionProfileIndex",void 0);E([I()],Ci.prototype,"refractionIntensity",void 0);E([I()],Ci.prototype,"translucencyIntensity",void 0);E([I()],Ci.prototype,"useAlbedoToTintRefraction",void 0);E([I()],Ci.prototype,"useAlbedoToTintTranslucency",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"thicknessTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"refractionTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"indexOfRefraction",void 0);E([I()],Ci.prototype,"_volumeIndexOfRefraction",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"volumeIndexOfRefraction",null);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"invertRefractionY",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"linkRefractionWithTransparency",void 0);E([I()],Ci.prototype,"minimumThickness",void 0);E([I()],Ci.prototype,"maximumThickness",void 0);E([I()],Ci.prototype,"useThicknessAsDepth",void 0);E([li()],Ci.prototype,"tintColor",void 0);E([I()],Ci.prototype,"tintColorAtDistance",void 0);E([I()],Ci.prototype,"dispersion",void 0);E([li()],Ci.prototype,"diffusionDistance",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"useMaskFromThicknessTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"refractionIntensityTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"translucencyIntensityTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Ci.prototype,"useGltfStyleTextures",void 0);const hl={effect:null,subMesh:null};class jx extends Vs{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class At extends vc{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new we(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=At.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=q.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new q(0,0,0),this._albedoColor=new q(1,1,1),this._reflectivityColor=new q(1,1,1),this._reflectionColor=new q(1,1,1),this._emissiveColor=new q(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=At.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Wi(16),this._globalAmbientColor=new q(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new ws(this),this.clearCoat=new ds(this),this.iridescence=new zs(this),this.anisotropy=new Rc(this),this.sheen=new Kn(this),this.subSurface=new Ci(this),this.detailMap=new ho(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ue.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=og(this.getScene()),this.prePassConfiguration=new Jd}get hasRenderTargetTextures(){return ue.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===At.PBRMATERIAL_OPAQUE||this._transparencyMode===At.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._forceAlphaTest?!0:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===At.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==At.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Es.GetDefineNames,this._eventInfo),t.materialDefines=new jx(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&ue.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&ue.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&ue.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const f=this._getReflectionTexture();if(f&&ue.ReflectionTextureEnabled){if(!f.isReadyOrNotBlocking())return!1;if(f.irradianceTexture){if(!f.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!f.sphericalPolynomial&&((d=f.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&ue.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&ue.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(ue.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&ue.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&ue.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(y.NormalKind)&&(e.createNormals(!0),O.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const l=t.effect,h=r._areLightsDisposed;let c=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(c)if(this._onEffectCreatedObservable&&(hl.effect=c,hl.subMesh=t,this._onEffectCreatedObservable.notifyObservers(hl)),this.allowShaderHotSwapping&&l&&!c.isReady()){if(c=l,r.markAsUnprocessed(),u=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(c,r,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!u,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const h=this.getScene().getEngine(),c=new zo;let u=0;t.USESPHERICALINVERTEX&&c.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&c.addFallback(u,"FOG"),t.SPECULARAA&&c.addFallback(u,"SPECULARAA"),t.POINTSIZE&&c.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&c.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&c.addFallback(u,"PARALLAX"),t.PARALLAX_RHS&&c.addFallback(u,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&c.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&c.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&c.addFallback(u++,"TANGENT"),t.BUMP&&c.addFallback(u++,"BUMP"),u=Cm(t,c,this._maxSimultaneousLights,u++),t.SPECULARTERM&&c.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&c.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&c.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&c.addFallback(u++,"LIGHTMAP"),t.NORMAL&&c.addFallback(u++,"NORMAL"),t.AMBIENT&&c.addFallback(u++,"AMBIENT"),t.EMISSIVE&&c.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&c.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&c.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const d=[y.PositionKind];t.NORMAL&&d.push(y.NormalKind),t.TANGENT&&d.push(y.TangentKind);for(let v=1;v<=6;++v)t["UV"+v]&&d.push(`uv${v===1?"":v}`);t.VERTEXCOLOR&&d.push(y.ColorKind),Sm(d,e,t,c),Af(d,t),xm(d,e,t),Tm(d,e,t);let f="pbr";const _=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],x={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=_,this._eventInfo.attributes=d,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=x,this._callbackPluginEventGeneric(Es.PrepareEffect,this._eventInfo),Jd.AddUniforms(_),sn(_),lt&&(lt.PrepareUniforms(_,t),lt.PrepareSamplers(p,t)),Mf({uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const T={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,_,g,p,t,d,T));const S=t.toString(),C=h.createEffect(f,{attributes:d,uniformsNames:_,uniformBuffersNames:g,samplers:p,defines:S,fallbacks:c,onCompiled:i,onError:s,indexParameters:x,processFinalCode:T.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},h);return this._eventInfo.customCode=void 0,C}_prepareDefines(e,t,i=null,s=null,r=!1){var h;const n=this.getScene(),o=n.getEngine();qu(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Pf(n,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(bm(n,t,this.canRenderToMRT&&!l),kE(n,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let c=1;c<=6;++c)t["MAINUV"+c]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&ue.DiffuseTextureEnabled?(qt(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&ue.AmbientTextureEnabled?(qt(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&ue.OpacityTextureEnabled?(qt(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const c=this._getReflectionTexture();if(c&&ue.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=c.gammaSpace,t.RGBDREFLECTION=c.isRGBD,t.LODINREFLECTIONALPHA=c.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=c.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=c.coordinatesMode===k.INVCUBIC_MODE,t.REFLECTIONMAP_3D=c.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!c.invertZ:c.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,c.coordinatesMode){case k.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case k.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case k.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case k.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case k.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case k.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case k.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case k.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case k.CUBIC_MODE:case k.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!c.boundingBoxSize;break}c.coordinatesMode!==k.SKYBOX_MODE&&(c.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):c.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&ue.LightmapTextureEnabled?(qt(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&ue.EmissiveTextureEnabled?(qt(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,ue.SpecularTextureEnabled){if(this._metallicTexture?(qt(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(qt(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){const u=this._metallicReflectanceTexture!==null&&this._metallicReflectanceTexture._texture===((h=this._reflectanceTexture)==null?void 0:h._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!u,this._metallicReflectanceTexture?(qt(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!u&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(qt(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?qt(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&ue.BumpTextureEnabled&&!this._disableBumpMap?(qt(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&ue.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&ue.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===At.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===At.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(yf(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(y.NormalKind),t.DEBUGMODE=this._debugMode),Rf(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),If(e,t,!0,!0,!0,this._transparencyMode!==At.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Es.GetDefineNames,this._eventInfo);const r=new jx(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(hl.effect=n,hl.subMesh=null,this._onEffectCreatedObservable.notifyObservers(hl)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var u,d,f;const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=this._mustRebind(s,n,i,t.visibility);Ku(t,this._activeEffect,this.prePassConfiguration);let h=null;const c=this._uniformBuffer;if(l){if(this.bindViewProjection(n),h=this._getReflectionTexture(),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&ue.DiffuseTextureEnabled&&(c.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Gt(this._albedoTexture,c,"albedo")),this._ambientTexture&&ue.AmbientTextureEnabled&&(c.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Gt(this._ambientTexture,c,"ambient")),this._opacityTexture&&ue.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gt(this._opacityTexture,c,"opacity")),h&&ue.ReflectionTextureEnabled){if(c.updateMatrix("reflectionMatrix",h.getReflectionTextureMatrix()),c.updateFloat2("vReflectionInfos",h.level,0),h.boundingBoxSize){const _=h;c.updateVector3("vReflectionPosition",_.boundingBoxPosition),c.updateVector3("vReflectionSize",_.boundingBoxSize)}if(this.realTimeFiltering){const _=h.getSize().width;c.updateFloat2("vReflectionFilteringInfo",_,ge.Log2(_))}if(!r.USEIRRADIANCEMAP){const _=h.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&_)if(r.SPHERICAL_HARMONICS){const p=_.preScaledHarmonics;c.updateVector3("vSphericalL00",p.l00),c.updateVector3("vSphericalL1_1",p.l1_1),c.updateVector3("vSphericalL10",p.l10),c.updateVector3("vSphericalL11",p.l11),c.updateVector3("vSphericalL2_2",p.l2_2),c.updateVector3("vSphericalL2_1",p.l2_1),c.updateVector3("vSphericalL20",p.l20),c.updateVector3("vSphericalL21",p.l21),c.updateVector3("vSphericalL22",p.l22)}else c.updateFloat3("vSphericalX",_.x.x,_.x.y,_.x.z),c.updateFloat3("vSphericalY",_.y.x,_.y.y,_.y.z),c.updateFloat3("vSphericalZ",_.z.x,_.z.y,_.z.z),c.updateFloat3("vSphericalXX_ZZ",_.xx.x-_.zz.x,_.xx.y-_.zz.y,_.xx.z-_.zz.z),c.updateFloat3("vSphericalYY_ZZ",_.yy.x-_.zz.x,_.yy.y-_.zz.y,_.yy.z-_.zz.z),c.updateFloat3("vSphericalZZ",_.zz.x,_.zz.y,_.zz.z),c.updateFloat3("vSphericalXY",_.xy.x,_.xy.y,_.xy.z),c.updateFloat3("vSphericalYZ",_.yz.x,_.yz.y,_.yz.z),c.updateFloat3("vSphericalZX",_.zx.x,_.zx.y,_.zx.z)}c.updateFloat3("vReflectionMicrosurfaceInfos",h.getSize().width,h.lodGenerationScale,h.lodGenerationOffset)}this._emissiveTexture&&ue.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gt(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&ue.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gt(this._lightmapTexture,c,"lightmap")),ue.SpecularTextureEnabled&&(this._metallicTexture?(c.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Gt(this._metallicTexture,c,"reflectivity")):this._reflectivityTexture&&(c.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Gt(this._reflectivityTexture,c,"reflectivity")),this._metallicReflectanceTexture&&(c.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Gt(this._metallicReflectanceTexture,c,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(c.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Gt(this._reflectanceTexture,c,"reflectance")),this._microSurfaceTexture&&(c.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Gt(this._microSurfaceTexture,c,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&ue.BumpTextureEnabled&&!this._disableBumpMap&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Gt(this._bumpTexture,c,"bump"),s._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){gt.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,gt.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,c.updateColor4("vReflectivityColor",gt.Color3[0],1);const _=((u=this.subSurface)==null?void 0:u._indexOfRefraction)??1.5,p=1,g=Math.pow((_-p)/(_+p),2);this._metallicReflectanceColor.scaleToRef(g*this._metallicF0Factor,gt.Color3[0]);const x=this._metallicF0Factor;c.updateColor4("vMetallicReflectanceFactors",gt.Color3[0],x)}else c.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);c.updateColor3("vEmissiveColor",ue.EmissiveTextureEnabled?this._emissiveColor:q.BlackReadOnly),c.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&((d=this.subSurface)!=null&&d._linkRefractionWithTransparency)?c.updateColor4("vAlbedoColor",this._albedoColor,1):c.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,c.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor),c.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&ue.DiffuseTextureEnabled&&c.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&ue.AmbientTextureEnabled&&c.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ue.OpacityTextureEnabled&&c.setTexture("opacitySampler",this._opacityTexture),h&&ue.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?c.setTexture("reflectionSampler",h):(c.setTexture("reflectionSampler",h._lodTextureMid||h),c.setTexture("reflectionSamplerLow",h._lodTextureLow||h),c.setTexture("reflectionSamplerHigh",h._lodTextureHigh||h)),r.USEIRRADIANCEMAP&&c.setTexture("irradianceSampler",h.irradianceTexture)),r.ENVIRONMENTBRDF&&c.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&ue.EmissiveTextureEnabled&&c.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ue.LightmapTextureEnabled&&c.setTexture("lightmapSampler",this._lightmapTexture),ue.SpecularTextureEnabled&&(this._metallicTexture?c.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&c.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&c.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&c.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&c.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&ue.BumpTextureEnabled&&!this._disableBumpMap&&c.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Gr(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&ju(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Ee.FOGMODE_NONE||h||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Go(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&Sa(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(n,r.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),ao(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,s,r,n,o,l,h,c,u,d,f,_;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(r=this._opacityTexture)==null||r.dispose(),(n=this._reflectionTexture)==null||n.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._metallicTexture)==null||l.dispose(),(h=this._reflectivityTexture)==null||h.dispose(),(c=this._bumpTexture)==null||c.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(d=this._metallicReflectanceTexture)==null||d.dispose(),(f=this._reflectanceTexture)==null||f.dispose(),(_=this._microSurfaceTexture)==null||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}At.PBRMATERIAL_OPAQUE=ee.MATERIAL_OPAQUE;At.PBRMATERIAL_ALPHATEST=ee.MATERIAL_ALPHATEST;At.PBRMATERIAL_ALPHABLEND=ee.MATERIAL_ALPHABLEND;At.PBRMATERIAL_ALPHATESTANDBLEND=ee.MATERIAL_ALPHATESTANDBLEND;At.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;At.LIGHTFALLOFF_PHYSICAL=0;At.LIGHTFALLOFF_GLTF=1;At.LIGHTFALLOFF_STANDARD=2;E([dE()],At.prototype,"_imageProcessingConfiguration",void 0);E([te("_markAllSubMeshesAsMiscDirty")],At.prototype,"debugMode",void 0);class ye extends At{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===At.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=At.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=At.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===At.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=At.LIGHTFALLOFF_GLTF:this._lightFalloff=At.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=ye.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=q.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new q(0,0,0),this.albedoColor=new q(1,1,1),this.reflectivityColor=new q(1,1,1),this.reflectionColor=new q(1,1,1),this.emissiveColor=new q(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=og(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=_e.Clone(()=>new ye(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=_e.Parse(()=>new ye(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ee._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ye.PBRMATERIAL_OPAQUE=At.PBRMATERIAL_OPAQUE;ye.PBRMATERIAL_ALPHATEST=At.PBRMATERIAL_ALPHATEST;ye.PBRMATERIAL_ALPHABLEND=At.PBRMATERIAL_ALPHABLEND;ye.PBRMATERIAL_ALPHATESTANDBLEND=At.PBRMATERIAL_ALPHATESTANDBLEND;ye.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=At.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"directIntensity",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"emissiveIntensity",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"environmentIntensity",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"specularIntensity",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"disableBumpMap",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"albedoTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"ambientTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"ambientTextureStrength",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);E([ht(),te("_markAllSubMeshesAsTexturesAndMiscDirty")],ye.prototype,"opacityTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"reflectionTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"emissiveTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"reflectivityTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"metallicTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"metallic",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"roughness",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"metallicF0Factor",void 0);E([li(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"metallicReflectanceColor",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"metallicReflectanceTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"reflectanceTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"microSurfaceTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"bumpTexture",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty",null)],ye.prototype,"lightmapTexture",void 0);E([li("ambient"),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"ambientColor",void 0);E([li("albedo"),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"albedoColor",void 0);E([li("reflectivity"),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"reflectivityColor",void 0);E([li("reflection"),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"reflectionColor",void 0);E([li("emissive"),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"emissiveColor",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"microSurface",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useLightmapAsShadowmap",void 0);E([I(),te("_markAllSubMeshesAsTexturesAndMiscDirty")],ye.prototype,"useAlphaFromAlbedoTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesAndMiscDirty")],ye.prototype,"forceAlphaTest",void 0);E([I(),te("_markAllSubMeshesAsTexturesAndMiscDirty")],ye.prototype,"alphaCutOff",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useSpecularOverAlpha",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useRoughnessFromMetallicTextureGreen",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useMetallnessFromMetallicTextureBlue",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useAmbientInGrayScale",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);E([I()],ye.prototype,"usePhysicalLightFalloff",null);E([I()],ye.prototype,"useGLTFLightFalloff",null);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useRadianceOverAlpha",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useObjectSpaceNormalMap",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useParallax",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useParallaxOcclusion",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"parallaxScaleBias",void 0);E([I(),te("_markAllSubMeshesAsLightsDirty")],ye.prototype,"disableLighting",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"forceIrradianceInFragment",void 0);E([I(),te("_markAllSubMeshesAsLightsDirty")],ye.prototype,"maxSimultaneousLights",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"invertNormalMapX",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"invertNormalMapY",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"twoSidedLighting",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useAlphaFresnel",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useLinearAlphaFresnel",void 0);E([te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"environmentBRDFTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"forceNormalForward",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"enableSpecularAntiAliasing",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useHorizonOcclusion",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],ye.prototype,"useRadianceOcclusion",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ye.prototype,"unlit",void 0);E([I(),te("_markAllSubMeshesAsMiscDirty")],ye.prototype,"applyDecalMapAfterDetailMap",void 0);V("BABYLON.PBRMaterial",ye);const CD=542327876,qx=131072,Qx=512,Zx=4,Jx=64,eT=131072;function e_(a){return a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)}function vD(a){return String.fromCharCode(a&255,a>>8&255,a>>16&255,a>>24&255)}const tT=e_("DXT1"),iT=e_("DXT3"),sT=e_("DXT5"),U_=e_("DX10"),rT=113,nT=116,aT=2,oT=10,bD=88,V_=31,AD=0,yD=1,lT=2,hT=3,k_=4,cT=7,G_=20,uT=21,RD=22,ID=23,PD=24,MD=25,DD=26,OD=28,ND=32;class Lt{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,V_),i=new Int32Array(e.buffer,e.byteOffset,V_+4);let s=1;t[lT]&qx&&(s=Math.max(1,t[cT]));const r=t[uT],n=r===U_?i[ND]:0;let o=0;switch(r){case rT:o=2;break;case nT:o=1;break;case U_:if(n===oT){o=2;break}if(n===aT){o=1;break}}return{width:t[k_],height:t[hT],mipmapCount:s,isFourCC:(t[G_]&Zx)===Zx,isRGB:(t[G_]&Jx)===Jx,isLuminance:(t[G_]&eT)===eT,isCube:(t[OD]&Qx)===Qx,isCompressed:r===tT||r===iT||r===sT,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=(u+c*e)*4;o[h]=Mn(l[d]),o[h+1]=Mn(l[d+1]),o[h+2]=Mn(l[d+2]),Lt.StoreLODInAlphaChannel?o[h+3]=n:o[h+3]=Mn(l[d+3]),h+=4}return o}static _GetHalfFloatRGBAArrayBuffer(e,t,i,s,r,n){if(Lt.StoreLODInAlphaChannel){const o=new Uint16Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=(u+c*e)*4;o[h]=l[d],o[h+1]=l[d+1],o[h+2]=l[d+2],o[h+3]=Ln(n),h+=4}return o}return new Uint16Array(r,i,s)}static _GetFloatRGBAArrayBuffer(e,t,i,s,r,n){if(Lt.StoreLODInAlphaChannel){const o=new Float32Array(s),l=new Float32Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=(u+c*e)*4;o[h]=l[d],o[h+1]=l[d+1],o[h+2]=l[d+2],o[h+3]=n,h+=4}return o}return new Float32Array(r,i,s)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Uint16Array(s),l=new Float32Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++)o[h]=Ln(l[h]),o[h+1]=Ln(l[h+1]),o[h+2]=Ln(l[h+2]),Lt.StoreLODInAlphaChannel?o[h+3]=Ln(n):o[h+3]=Ln(l[h+3]),h+=4;return o}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,s,r,n){const o=new Uint8Array(s),l=new Float32Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=(u+c*e)*4;o[h]=ge.Clamp(l[d])*255,o[h+1]=ge.Clamp(l[d+1])*255,o[h+2]=ge.Clamp(l[d+2])*255,Lt.StoreLODInAlphaChannel?o[h+3]=n:o[h+3]=ge.Clamp(l[d+3])*255,h+=4}return o}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,s,r,n){const o=new Uint8Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=(u+c*e)*4;o[h]=ge.Clamp(Mn(l[d]))*255,o[h+1]=ge.Clamp(Mn(l[d+1]))*255,o[h+2]=ge.Clamp(Mn(l[d+2]))*255,Lt.StoreLODInAlphaChannel?o[h+3]=n:o[h+3]=ge.Clamp(Mn(l[d+3]))*255,h+=4}return o}static _GetRGBAArrayBuffer(e,t,i,s,r,n,o,l,h){const c=new Uint8Array(s),u=new Uint8Array(r,i);let d=0;for(let f=0;f<t;f++)for(let _=0;_<e;_++){const p=(_+f*e)*4;c[d]=u[p+n],c[d+1]=u[p+o],c[d+2]=u[p+l],c[d+3]=u[p+h],d+=4}return c}static _ExtractLongWordOrder(e){return e===0||e===255||e===-16777216?0:1+Lt._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,l){const h=new Uint8Array(s),c=new Uint8Array(r,i);let u=0;for(let d=0;d<t;d++)for(let f=0;f<e;f++){const _=(f+d*e)*3;h[u]=c[_+n],h[u+1]=c[_+o],h[u+2]=c[_+l],u+=3}return h}static _GetLuminanceArrayBuffer(e,t,i,s,r){const n=new Uint8Array(s),o=new Uint8Array(r,i);let l=0;for(let h=0;h<t;h++)for(let c=0;c<e;c++){const u=c+h*e;n[l]=o[u],l++}return n}static UploadDDSLevels(e,t,i,s,r,n,o=-1,l,h=!0){let c=null;s.sphericalPolynomial&&(c=[]);const u=!!e.getCaps().s3tc;t.generateMipMaps=r;const d=new Int32Array(i.buffer,i.byteOffset,V_);let f,_,p,g=0,x,T,S,C,v=0,b=1;if(d[AD]!==CD){O.Error("Invalid magic number in DDS header");return}if(!s.isFourCC&&!s.isRGB&&!s.isLuminance){O.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(s.isCompressed&&!u){O.Error("Compressed textures are not supported on this platform.");return}let A=d[RD];x=d[yD]+4;let P=!1;if(s.isFourCC)switch(f=d[uT],f){case tT:b=8,v=33777;break;case iT:b=16,v=33778;break;case sT:b=16,v=33779;break;case rT:P=!0,A=64;break;case nT:P=!0,A=128;break;case U_:{x+=5*4;let re=!1;switch(s.dxgiFormat){case oT:P=!0,A=64,re=!0;break;case aT:P=!0,A=128,re=!0;break;case bD:s.isRGB=!0,s.isFourCC=!1,A=32,re=!0;break}if(re)break}default:O.Error(["Unsupported FourCC code:",vD(f)]);return}const L=Lt._ExtractLongWordOrder(d[ID]),w=Lt._ExtractLongWordOrder(d[PD]),$=Lt._ExtractLongWordOrder(d[MD]),J=Lt._ExtractLongWordOrder(d[DD]);P&&(v=e._getRGBABufferInternalSizedFormat(s.textureType)),S=1,d[lT]&qx&&r!==!1&&(S=Math.max(1,d[cT]));const ne=l||0,oe=e.getCaps();for(let re=ne;re<n;re++){for(_=d[k_],p=d[hT],C=0;C<S;++C){if(o===-1||o===C){const ce=o===-1?C:0;if(!s.isCompressed&&s.isFourCC){t.format=5,g=_*p*4;let Se=null;if(e._badOS||e._badDesktopOS||!oe.textureHalfFloat&&!oe.textureFloat)A===128?(Se=Lt._GetFloatAsUIntRGBAArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,ce),c&&ce==0&&c.push(Lt._GetFloatRGBAArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,ce))):A===64&&(Se=Lt._GetHalfFloatAsUIntRGBAArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,ce),c&&ce==0&&c.push(Lt._GetHalfFloatAsFloatRGBAArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,ce))),t.type=0;else{const Ce=oe.textureFloat&&(h&&oe.textureFloatLinearFiltering||!h),ae=oe.textureHalfFloat&&(h&&oe.textureHalfFloatLinearFiltering||!h),ie=(A===128||A===64&&!ae)&&Ce?1:(A===64||A===128&&!Ce)&&ae?2:0;let F,j=null;switch(A){case 128:{switch(ie){case 1:F=Lt._GetFloatRGBAArrayBuffer,j=null;break;case 2:F=Lt._GetFloatAsHalfFloatRGBAArrayBuffer,j=Lt._GetFloatRGBAArrayBuffer;break;case 0:F=Lt._GetFloatAsUIntRGBAArrayBuffer,j=Lt._GetFloatRGBAArrayBuffer;break}break}default:{switch(ie){case 1:F=Lt._GetHalfFloatAsFloatRGBAArrayBuffer,j=null;break;case 2:F=Lt._GetHalfFloatRGBAArrayBuffer,j=Lt._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:F=Lt._GetHalfFloatAsUIntRGBAArrayBuffer,j=Lt._GetHalfFloatAsFloatRGBAArrayBuffer;break}break}}t.type=ie,Se=F(_,p,i.byteOffset+x,g,i.buffer,ce),c&&ce==0&&c.push(j?j(_,p,i.byteOffset+x,g,i.buffer,ce):Se)}Se&&e._uploadDataToTextureDirectly(t,Se,re,ce)}else if(s.isRGB)t.type=0,A===24?(t.format=4,g=_*p*3,T=Lt._GetRGBArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,L,w,$),e._uploadDataToTextureDirectly(t,T,re,ce)):(t.format=5,g=_*p*4,T=Lt._GetRGBAArrayBuffer(_,p,i.byteOffset+x,g,i.buffer,L,w,$,J),e._uploadDataToTextureDirectly(t,T,re,ce));else if(s.isLuminance){const Se=e._getUnpackAlignement(),Ce=_;g=Math.floor((_+Se-1)/Se)*Se*(p-1)+Ce,T=Lt._GetLuminanceArrayBuffer(_,p,i.byteOffset+x,g,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,T,re,ce)}else g=Math.max(4,_)/4*Math.max(4,p)/4*b,T=new Uint8Array(i.buffer,i.byteOffset+x,g),t.type=0,e._uploadCompressedDataToTextureDirectly(t,v,_,p,T,re,ce)}x+=A?_*p*(A/8):g,_*=.5,p*=.5,_=Math.max(1,_),p=Math.max(1,p)}if(l!==void 0)break}c&&c.length>0?s.sphericalPolynomial=yc.ConvertCubeMapToSphericalPolynomial({size:d[k_],right:c[0],left:c[1],up:c[2],down:c[3],front:c[4],back:c[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}Lt.StoreLODInAlphaChannel=!1;pe.prototype.createPrefilteredCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!0){const h=c=>{if(!c){s&&s(null);return}const u=c.texture;if(l?c.info.sphericalPolynomial&&(u._sphericalPolynomial=c.info.sphericalPolynomial):u._sphericalPolynomial=new ma,u._source=et.CubePrefiltered,this.getCaps().textureLOD){s&&s(u);return}const d=3,f=this._gl,_=c.width;if(!_)return;const p=[];for(let g=0;g<d;g++){const T=1-g/(d-1),S=i,C=ge.Log2(_)*t+i,v=S+(C-S)*T,b=Math.round(Math.min(Math.max(v,0),C)),A=new Tt(this,et.Temp);if(A.type=u.type,A.format=u.format,A.width=Math.pow(2,Math.max(ge.Log2(_)-b,0)),A.height=A.width,A.isCube=!0,A._cachedWrapU=0,A._cachedWrapV=0,this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,A,!0),A.samplingMode=2,f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MAG_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MIN_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),c.isDDS){const L=c.info,w=c.data;this._unpackFlipY(L.isCompressed),Lt.UploadDDSLevels(this,A,w,L,!0,6,b)}else O.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null);const P=new Et(e);P._isCube=!0,P._texture=A,A.isReady=!0,p.push(P)}u._lodTextureHigh=p[2],u._lodTextureMid=p[1],u._lodTextureLow=p[0],s&&s(u)};return this.createCubeTexture(a,e,null,!1,h,r,n,o,l,t,i)};class FD{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,l=1e3;if(Array.isArray(e))for(let h=0;h<e.length;h++){const c=e[h];n=Lt.GetDDSInfo(c),t.width=n.width,t.height=n.height,o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),Lt.UploadDDSLevels(r,t,c,n,o,6,-1,h),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t):l=n.mipmapCount-1}else{const h=e;n=Lt.GetDDSInfo(h),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new ma),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),Lt.UploadDDSLevels(r,t,h,n,o,6),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t,!1):l=n.mipmapCount-1}r._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=Lt.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1===1;i(s.width,s.height,r,s.isFourCC,()=>{Lt.UploadDDSLevels(t.getEngine(),t,e,s,r,1)})}}H._TextureLoaders.push(new FD);class wD{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=AS(e);if(n){t.width=n.width,t.height=n.width;try{RS(t,n),FI(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},o=>{r==null||r("Can not upload environment levels",o)})}catch(o){r==null||r("Can not upload environment file",o)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}H._TextureLoaders.push(new wD);class Br{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Br.IsValid(e)){this.isInvalid=!0,O.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),n=s.getUint32(0,!0)===67305985;if(this.glType=s.getUint32(1*i,n),this.glTypeSize=s.getUint32(2*i,n),this.glFormat=s.getUint32(3*i,n),this.glInternalFormat=s.getUint32(4*i,n),this.glBaseInternalFormat=s.getUint32(5*i,n),this.pixelWidth=s.getUint32(6*i,n),this.pixelHeight=s.getUint32(7*i,n),this.pixelDepth=s.getUint32(8*i,n),this.numberOfArrayElements=s.getUint32(9*i,n),this.numberOfFaces=s.getUint32(10*i,n),this.numberOfMipmapLevels=s.getUint32(11*i,n),this.bytesOfKeyValueData=s.getUint32(12*i,n),this.glType!==0){O.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){O.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){O.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){O.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=Br.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case Br.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break}}_upload2DCompressedLevels(e,t){let i=Br.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let o=0;o<n;o++){const l=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let h=0;h<this.numberOfFaces;h++){const c=new Uint8Array(this.data.buffer,this.data.byteOffset+i,l);e.getEngine()._uploadCompressedDataToTextureDirectly(e,e.format,s,r,c,h,o),i+=l,i+=3-(l+3)%4}s=Math.max(1,s*.5),r=Math.max(1,r*.5)}}static IsValid(e){if(e.byteLength>=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}Br.HEADER_LEN=12+13*4;Br.COMPRESSED_2D=0;Br.COMPRESSED_3D=1;Br.TEX_2D=2;Br.TEX_3D=3;class LD{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(const e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{const s=this._pendingActions.shift();s?this._execute(e,s):e.idle=!0})})}}class ed extends LD{constructor(e,t,i=ed.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){const t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,(i,s)=>{t(i,()=>{s(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(n=>{n.terminate()});const r=this._workerInfos.indexOf(e);r!==-1&&this._workerInfos.splice(r,1)},this._options.idleTimeElapsedBeforeRelease))})})}}ed.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var dT;(function(a){a[a.ETC1S=0]="ETC1S",a[a.UASTC4x4=1]="UASTC4x4"})(dT||(dT={}));var eu;(function(a){a[a.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",a[a.BC7_RGBA=1]="BC7_RGBA",a[a.BC3_RGBA=2]="BC3_RGBA",a[a.BC1_RGB=3]="BC1_RGB",a[a.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",a[a.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",a[a.ETC2_RGBA=6]="ETC2_RGBA",a[a.ETC1_RGB=7]="ETC1_RGB",a[a.RGBA32=8]="RGBA32",a[a.R8=9]="R8",a[a.RG8=10]="RG8"})(eu||(eu={}));var fp;(function(a){a[a.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",a[a.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",a[a.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",a[a.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",a[a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",a[a.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",a[a.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",a[a.RGBA8Format=32856]="RGBA8Format",a[a.R8Format=33321]="R8Format",a[a.RG8Format=33323]="RG8Format"})(fp||(fp={}));function hf(a,e){const t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;a&&(a.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=a.wasmUASTCToASTC),a.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=a.wasmUASTCToBC7),a.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=a.wasmUASTCToRGBA_UNORM),a.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=a.wasmUASTCToRGBA_SRGB),a.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=a.wasmUASTCToR8_UNORM),a.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=a.wasmUASTCToRG8_UNORM),a.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=a.jsMSCTranscoder),a.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=a.wasmMSCTranscoder),a.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=a.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function BD(a){typeof a>"u"&&typeof KTX2DECODER<"u"&&(a=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;i&&(i.jsDecoderModule&&typeof a>"u"&&(importScripts(i.jsDecoderModule),a=KTX2DECODER),hf(i)),t.data.wasmBinaries&&hf(void 0,{...t.data.wasmBinaries,jsDecoderModule:a}),e=new a.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{a.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{const s=[];for(let r=0;r<i.mipmaps.length;++r){const n=i.mipmaps[r];n&&n.data&&s.push(n.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:i},s)}).catch(i=>{postMessage({action:"decoded",success:!1,msg:i})});break}}}function UD(a,e,t){return new Promise((i,s)=>{const r=o=>{a.removeEventListener("error",r),a.removeEventListener("message",n),s(o)},n=o=>{o.data.action==="init"&&(a.removeEventListener("error",r),a.removeEventListener("message",n),i(a))};a.addEventListener("error",r),a.addEventListener("message",n),a.postMessage({action:"init",urls:t,wasmBinaries:e})})}class VD{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[eu.BC1_RGB,eu.BC3_RGBA],yes:{transcodeFormat:eu.RGBA32,engineFormat:fp.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Wt{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Wt._WorkerPoolPromise||Wt._DecoderModulePromise)return;const t={jsDecoderModule:X.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:X.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:X.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:X.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:X.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?Wt._WorkerPoolPromise=new Promise(i=>{const s=`${hf}(${BD})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new ed(e,()=>UD(new Worker(r),void 0,t)))}):typeof Wt._KTX2DecoderModule>"u"?Wt._DecoderModulePromise=X.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(Wt._KTX2DecoderModule=KTX2DECODER,Wt._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Wt._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,hf(t,Wt._KTX2DecoderModule),new Wt._KTX2DecoderModule.KTX2Decoder)):(Wt._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Wt._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Wt._DecoderModulePromise=Promise.resolve(new Wt._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=Wt.DefaultNumWorkers){var i;if(this._engine=e,typeof t=="object"&&t.workerPool)Wt._WorkerPoolPromise=Promise.resolve(t.workerPool);else{typeof t=="object"?Wt._KTX2DecoderModule=(i=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:i.jsDecoderModule:typeof KTX2DECODER<"u"&&(Wt._KTX2DecoderModule=KTX2DECODER);const s=typeof t=="number"?t:t.numWorkers??Wt.DefaultNumWorkers;Wt._Initialize(s)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(Wt._WorkerPoolPromise)return Wt._WorkerPoolPromise.then(n=>new Promise((o,l)=>{n.push((h,c)=>{const u=_=>{h.removeEventListener("error",u),h.removeEventListener("message",d),l(_),c()},d=_=>{if(_.data.action==="decoded"){if(h.removeEventListener("error",u),h.removeEventListener("message",d),!_.data.success)l({message:_.data.msg});else try{this._createTexture(_.data.decodedData,t,i),o()}catch(p){l({message:p})}c()}};h.addEventListener("error",u),h.addEventListener("message",d),h.postMessage({action:"setDefaultDecoderOptions",options:Wt.DefaultDecoderOptions._getKTX2DecoderOptions()});const f=new Uint8Array(e.byteLength);f.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),h.postMessage({action:"decode",data:f,caps:r,options:i},[f.buffer])})}));if(Wt._DecoderModulePromise)return Wt._DecoderModulePromise.then(n=>(Wt.DefaultDecoderOptions.isDirty&&(Wt._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=Wt.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,l)=>{n.decode(e,s).then(h=>{this._createTexture(h,t),o()}).catch(h=>{l({message:h})})})));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let n=0;n<e.mipmaps.length;++n){const o=e.mipmaps[n];if(!o||!o.data)throw new Error("KTX2 container - could not transcode one of the image");r?(t.width=o.width,t.height=o.height,this._engine._uploadDataToTextureDirectly(t,o.data,0,n,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,o.width,o.height,o.data,0,n)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}}Wt.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};Wt.DefaultNumWorkers=Wt.GetDefaultNumWorkers();Wt.DefaultDecoderOptions=new VD;function kD(a){switch(a){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}class GD{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||t==="image/ktx"||t==="image/ktx2"}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Br(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Br.IsValid(e)){t._invertVScale=!t.invertY;const r=new Br(e,1),n=kD(r.glInternalFormat);n?(t.format=n,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else Wt.IsValid(e)?new Wt(t.getEngine())._uploadAsync(e,t,s).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},n=>{O.Warn(`Failed to load KTX2 texture data: ${n.message}`),i(0,0,!1,!1,()=>{},!0)}):(O.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}H._TextureLoaders.unshift(new GD);class Iu extends qs{constructor(e,t,i){super(e,m.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=Q.Identity(),this._referencedPosition=new m,this._trackingState=pl.NOT_TRACKING,this.onXRCameraInitializedObservable=new G,this.onBeforeCameraTeleport=new G,this.onAfterCameraTeleport=new G,this.onTrackingStateChanged=new G,this.compensateOnFirstFrame=!0,this._rotate180=new Q(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new Q,this.cameraRigMode=ve.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add(()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()})}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Vr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Vr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,Q.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=U.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),Q.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(pl.NOT_TRACKING);return}const t=e.emulatedPosition?pl.TRACKING_LOST:pl.TRACKING;if(this._setTrackingState(t),(this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ)&&this._updateDepthNearFar(),e.transform){const i=e.transform.orientation;if(e.transform.orientation.x===void 0)return;const s=e.transform.position;this._referencedPosition.set(s.x,s.y,s.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(i.x,i.y,i.z,i.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((i,s)=>{var c;const r=this.rigCameras[s];!r.isLeftCamera&&!r.isRightCamera&&(i.eye==="right"?r._isRightCamera=!0:i.eye==="left"&&(r._isLeftCamera=!0));const n=this.getScene().customRenderTargets;for(let u=0;u<n.length;u++){const d=n[u];r.customRenderTargets.indexOf(d)===-1&&r.customRenderTargets.push(d)}const o=i.transform.position,l=i.transform.orientation;r.parent=this.parent,r.position.set(o.x,o.y,o.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),r.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),D.FromFloat32ArrayToRefScaled(i.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),s===0&&this._projectionMatrix.copyFrom(r._projectionMatrix);const h=this._xrSessionManager.getRenderTargetTextureForView(i);this._renderingMultiview=((c=h==null?void 0:h._texture)==null?void 0:c.isMultiview)||!1,this._renderingMultiview?s==0&&(this._xrSessionManager.trySetViewportForView(this.viewport,i),this.outputRenderTarget=h):(this._xrSessionManager.trySetViewportForView(r.viewport,i),r.outputRenderTarget=h||this._xrSessionManager.getRenderTargetTextureForView(i)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.length<e;){const t=new Ai("XR-RigCamera: "+this.rigCameras.length,m.Zero(),this.getScene());t.minZ=.1,t.rotationQuaternion=new Q,t.updateUpVectorFromRotation=!0,t.isRigCamera=!0,t.rigParent=this,t.freezeProjectionMatrix(),this.rigCameras.push(t)}for(;this.rigCameras.length>e;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=U.Matrix[0],t=U.Matrix[1],i=U.Matrix[2];D.ComposeToRef(Iu._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),D.ComposeToRef(Iu._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}Iu._ScaleReadOnly=m.One();class lg{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new G,this.onStateChangedObservable=new G,this.state=qi.NOT_IN_XR,this.sessionManager=new Yf(e),this.camera=new Iu("webxr",e,this.sessionManager),this.featuresManager=new fi(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new lg(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(qi.NOT_IN_XR),t.dispose(),i})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),(e=this._spectatorCamera)==null||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){var r,n,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(qi.ENTERING_XR),t!=="viewer"&&t!=="local"&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),e==="immersive-ar"&&t!=="unbounded"&&O.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(dt.LAYERS)){const h=await i.initializeXRLayerAsync(this.sessionManager.session);l.baseLayer=h}return this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!((n=(r=this._nonVRCamera)==null?void 0:r.inputs)!=null&&n.attachedToElement),(o=this._nonVRCamera)==null||o.detachControl(),this._scene.activeCamera=this.camera,e!=="immersive-ar"?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==qi.EXITING_XR&&this._setState(qi.EXITING_XR),this.camera.rigCameras.forEach(h=>{h.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),e!=="immersive-ar"&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(qi.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(qi.IN_XR)}),this.sessionManager}catch(l){throw O.Log(l),O.Log(l.message),this._setState(qi.NOT_IN_XR),l}}exitXRAsync(){return this.state!==qi.IN_XR?Promise.resolve():(this._setState(qi.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const i=1/(e!=null&&e.fps?e.fps:1e3)*1e3,s=e!=null&&e.preferredCameraIndex?e==null?void 0:e.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[s].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[s].absoluteRotation))};if(this._spectatorMode){if(s>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const n=()=>{this.state===qi.IN_XR?(this._spectatorCamera=new bc("webxr-spectator",m.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new Q,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===qi.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(n),n()}else this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Ar{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new G,this.onButtonStateChangedObservable=new G}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return this._axesIndices.length!==0}isButton(){return this._buttonIndex!==-1}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const s=e.buttons[this._buttonIndex];if(!s)return;this._currentValue!==s.value&&(this.changes.value={current:s.value,previous:this._currentValue},t=!0,this._currentValue=s.value),this._touched!==s.touched&&(this.changes.touched={current:s.touched,previous:this._touched},t=!0,this._touched=s.touched),this._pressed!==s.pressed&&(this.changes.pressed={current:s.pressed,previous:this._pressed},t=!0,this._pressed=s.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Ar.BUTTON_TYPE="button";Ar.SQUEEZE_TYPE="squeeze";Ar.THUMBSTICK_TYPE="thumbstick";Ar.TOUCHPAD_TYPE="touchpad";Ar.TRIGGER_TYPE="trigger";class Ic{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=o=>{if(!o)return;const l=this.layout.components[o],h=l.type,c=l.gamepadIndices.button,u=[];l.gamepadIndices.xAxis!==void 0&&l.gamepadIndices.yAxis!==void 0&&u.push(l.gamepadIndices.xAxis,l.gamepadIndices.yAxis),this.components[o]=new Ar(o,h,c,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new G,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(t=>this.components[t]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?O.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,s)=>{const r=n=>{e?this._getGenericParentMesh(n):this._setRootMesh(n),this._processLoadedModel(n),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const n=this._controllerCache.filter(o=>o.filename===t.filename&&o.path===t.path);if(n[0]){n[0].meshes.forEach(o=>o.setEnabled(!0)),r(n[0].meshes);return}}je.ImportMesh("",t.path,t.filename,this.scene,n=>{this._controllerCache&&this._controllerCache.push({...t,meshes:n}),r(n)},null,(n,o)=>{O.Log(o),O.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(o)})})}updateFromXRFrame(e){this.getComponentIds().forEach(t=>this.getComponent(t).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(i=>i.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(i=>i.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?t*.5+.5:t;Q.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),m.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new z(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=Q.FromEulerAngles(0,Math.PI,0)}}class Pu extends Ic{constructor(e,t,i){super(e,zD[i],t,i),this.profileId=Pu.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new z(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=Q.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Pu.ProfileId="generic-trigger";const zD={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class WD extends Ic{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=je.IsPluginForExtensionAvailable(".glb");return e||O.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=this.layout.components[t];this._buttonMeshMapping[t]={mainMesh:this._getChildByName(this.rootMesh,i.rootNodeName),states:{}},Object.keys(i.visualResponses).forEach(s=>{const r=i.visualResponses[s];if(r.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{const n=i.type===Ar.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,n)},i.type===Ar.TOUCHPAD_TYPE&&!this._touchDots[s]){const o=pa(s+"dot",{diameter:.0015,segments:8},this.scene);o.material=new de(s+"mat",this.scene),o.material.diffuseColor=q.Red(),o.parent=this._buttonMeshMapping[t].states[s].valueMesh||null,o.isVisible=!1,this._touchDots[s]=o}}})})}_setRootMesh(e){this.rootMesh=new z(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i<e.length;i++){const s=e[i];s.isPickable=!1,s.parent||(t=s)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(Bs.Y,Math.PI,pt.WORLD)}_updateModel(e){this.disableAnimation||this.getComponentIds().forEach(t=>{const i=this.getComponent(t);if(!i.hasChanges)return;const s=this._buttonMeshMapping[t],r=this.layout.components[t];Object.keys(r.visualResponses).forEach(n=>{const o=r.visualResponses[n];let l=i.value;if(o.componentProperty==="xAxis"?l=i.axes.x:o.componentProperty==="yAxis"&&(l=i.axes.y),o.valueNodeProperty==="transform")this._lerpTransform(s.states[n],l,o.componentProperty!=="button");else{const h=s.states[n].valueMesh;h&&(h.isVisible=i.touched||i.pressed),this._touchDots[n]&&(this._touchDots[n].isVisible=i.touched||i.pressed)}})})}}const z_=[];class hs{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];if(i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):s.push("oculus-touch-v2");break}const r=s.indexOf("windows-mixed-reality");if(r!==-1&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const n=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return n.call(this,s,e,t).catch(()=>o.call(this,s,e,t))}else return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=X.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){z_.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),z_.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(s=>{for(let r=0;r<e.length;++r)if(e[r]&&s[e[r]])return e[r];throw new Error(`neither controller ${e[0]} nor all fallbacks were found in the repository,`)}).then(s=>(this._ProfileLoadingPromises[s]||(this._ProfileLoadingPromises[s]=X.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${s}/profile.json`,!1).then(r=>JSON.parse(r))),this._ProfileLoadingPromises[s])).then(s=>new WD(i,t,s,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:z_))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;s<e.length;++s){if(!e[s])continue;const r=this.FindFallbackWithProfileId(e[s]);for(let n=0;n<r.length;++n){const o=this._AvailableControllers[r[n]];if(o)return Promise.resolve(o(t,i))}}throw new Error("no controller requested was found in the available controllers list")}}hs._AvailableControllers={};hs._Fallbacks={};hs._ProfileLoadingPromises={};hs.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist";hs.PrioritizeOnlineRepository=!0;hs.UseOnlineRepository=!0;hs.DisableControllerCache=!0;hs.RegisterController(Pu.ProfileId,(a,e)=>new Pu(e,a.gamepad,a.handedness));hs.DefaultFallbacks();let HD=0;class XD{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new m,this._disposed=!1,this.onDisposeObservable=new G,this.onMeshLoadedObservable=new G,this.onMotionControllerInitObservable=new G,this._uniqueId=`controller-${HD++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new ut(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new Q,this.inputSource.gripSpace&&(this.grip=new ut(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new Q),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&hs.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(s=>{this.motionController=s,this.onMotionControllerInitObservable.notifyObservers(s),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(r=>{var n;r&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(o=>o.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&((n=this.motionController)==null||n.dispose())})},()=>{X.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;m.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const n=r.transform.position;this.pointer.position.set(n.x,n.y,n.z).scaleInPlace(s.worldScalingFactor);const o=r.transform.orientation;this.pointer.rotationQuaternion.set(o.x,o.y,o.z,o.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const o=n.transform.position,l=n.transform.orientation;this.grip.position.set(o.x,o.y,o.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class YD{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new G,this.onControllerRemovedObservable=new G,this._onInputSourcesChange=s=>{this._addAndRemoveControllers(s.added,s.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(s=>s.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(s=>{s.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(s=>{this.controllers.forEach(r=>{r.updateFromXRFrame(s,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)})}),this._options.customControllersRepositoryURL&&(hs.BaseRepositoryUrl=this._options.customControllersRepositoryURL),hs.UseOnlineRepository=!this._options.disableOnlineControllerRepository,hs.UseOnlineRepository)try{hs.UpdateProfilesList().catch(()=>{hs.UseOnlineRepository=!1})}catch{hs.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(n=>n.inputSource);for(const n of e)if(i.indexOf(n)===-1){const o=new XD(this.xrSessionManager.scene,n,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(o),this.onControllerAddedObservable.notifyObservers(o)}const s=[],r=[];this.controllers.forEach(n=>{t.indexOf(n.inputSource)===-1?s.push(n):r.push(n)}),this.controllers=s,r.forEach(n=>{this.onControllerRemovedObservable.notifyObservers(n),n.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),hs.ClearControllerCache()}}class Hn extends _s{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:s,selectionMesh:r}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&i.grip?i.grip:i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:s,selectionMesh:r,meshUnderPointer:null,pick:null,tmpRay:new tt(new m,new m),disabledByNearInteraction:!1,id:Hn._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(i);case"gaze":return this._attachGazeMode(i);case"screen":case"transient-pointer":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new m,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new q(.9,.9,.9),this.laserPointerDefaultColor=new q(.7,.7,.7),this.selectionMeshDefaultColor=new q(.8,.8,.8),this.selectionMeshPickedColor=new q(.3,.3,1),this._identityMatrix=D.Identity(),this._screenCoordinatesRef=m.Zero(),this._viewportRef=new Vr(0,0,0,0),this._scene=this._xrSessionManager.scene,this._options.lookAndPickMode===void 0&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)},!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new tt(new m,new m),disabledByNearInteraction:!1,id:Hn._IdCounter++},this._attachGazeMode()}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}_getPointerSelectionDisabledByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0}_setPointerSelectionDisabledByPointerId(e,t){const i=Object.keys(this._controllers);for(let s=0;s<i.length;++s)if(this._controllers[i[s]].id===e){this._controllers[i[s]].disabledByNearInteraction=t;return}}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var l;const i=this._controllers[t];if(this._options.lookAndPickMode&&((l=i.xrController)==null?void 0:l.inputSource.targetRayMode)!=="transient-pointer")return;if(!this._options.enablePointerSelectionOnAllControllers&&t!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}i.laserPointer.isVisible=this.displayLaserPointer;let s;if(i.xrController)s=this._options.forceGripIfAvailable&&i.xrController.grip?i.xrController.grip.position:i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay,this._options.forceGripIfAvailable);else if(i.webXRCamera)s=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&s){const h=this._xrSessionManager.scene,c=this._options.xrInput.xrCamera;c&&(c.viewport.toGlobalToRef(h.getEngine().getRenderWidth()/c.rigCameras.length,h.getEngine().getRenderHeight(),this._viewportRef),m.ProjectToRef(s,this._identityMatrix,c.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&this._screenCoordinatesRef.x!==1/0&&this._screenCoordinatesRef.y!==1/0&&(h.pointerX=this._screenCoordinatesRef.x,h.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const n=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!r||!r.hit?i.pick=n:!n||!n.hit||r.distance<n.distance?i.pick=r:i.pick=n,i.pick&&i.xrController&&(i.pick.aimTransform=i.xrController.pointer,i.pick.gripTransform=i.xrController.grip||null,i.pick.originMesh=i.xrController.pointer);const o=i.pick;if(o&&o.pickedPoint&&o.hit){this._updatePointerDistance(i.laserPointer,o.distance),i.selectionMesh.position.copyFrom(o.pickedPoint),i.selectionMesh.scaling.x=Math.sqrt(o.distance),i.selectionMesh.scaling.y=Math.sqrt(o.distance),i.selectionMesh.scaling.z=Math.sqrt(o.distance);const h=this._convertNormalToDirectionOfRay(o.getNormal(!0),i.tmpRay),c=.001;if(i.selectionMesh.position.copyFrom(o.pickedPoint),h){const u=m.Cross(Bs.Y,h),d=m.Cross(h,u);m.RotationFromAxisToRef(d,h,u,i.selectionMesh.rotation),i.selectionMesh.position.addInPlace(h.scale(c))}i.selectionMesh.isVisible=this.displaySelectionMesh,i.meshUnderPointer=o.pickedMesh}else i.selectionMesh.isVisible=!1,this._updatePointerDistance(i.laserPointer,1),i.meshUnderPointer=null})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene}_attachGazeMode(e){const t=this._controllers[e&&e.uniqueId||"camera"],i=this._options.timeToSelect||3e3,s=this._options.useUtilityLayer?this._utilityLayerScene:this._scene;let r=new es;const n=Bl("selection",{diameter:.0035*15,thickness:.0025*6,tessellation:20},s);n.isVisible=!1,n.isPickable=!1,n.parent=t.selectionMesh;let o=0,l=!1;const h={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{if(t.pick){if(this._augmentPointerInit(h,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))l&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,h)),l=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,h),l=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,h),n.isVisible=!1;else{const c=1-o/i;n.scaling.set(c,c,c)}else l=!1,o=0;this._scene.simulatePointerMove(t.pick,h),r=t.pick}}),this._options.renderingGroupId!==void 0&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&l&&(this._scene.simulatePointerUp(t.pick,h),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){const s=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(n=>{if(n.changes.pressed){const o=n.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),o?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(o&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const l=this._controllers[this._attachedController];l&&l.pointerDownTriggered&&!l.finalPointerUpTriggered&&(this._augmentPointerInit(i,l.id,l.screenCoordinates),this._scene.simulatePointerUp(new es,{pointerId:l.id,pointerType:"xr"}),l.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}})};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=n=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)})},r=n=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)})};t.eventListeners={selectend:r,selectstart:s},this._xrSessionManager.session.addEventListener("selectstart",s),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(m.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1),e}_detachController(e){const t=this._controllers[e];if(t){if(t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(i=>{const s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const i={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new es,i),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}catch{X.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Hm("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new de("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Bl("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new de("targetMat",t);return n.specularColor=q.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){var r;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(r=e.pickedPoint)==null||r.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}Hn._IdCounter=200;Hn.Name=dt.POINTER_SELECTION;Hn.Version=1;fi.AddWebXRFeature(Hn.Name,(a,e)=>()=>new Hn(a,e),Hn.Version,!0);Ss.prototype._projectOnTrianglesToRef=function(a,e,t,i,s,r){const n=U.Vector3[0],o=U.Vector3[1];let l=1/0;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-i);h+=i){const c=t[h],u=t[h+1],d=t[h+2];if(s&&d===4294967295){h+=2;continue}const f=e[c],_=e[u],p=e[d];if(!f||!_||!p)continue;const g=m.ProjectOnTriangleToRef(a,f,_,p,o);g<l&&(n.copyFrom(o),l=g)}return r.copyFrom(n),l};Ss.prototype._projectOnUnIndexedTrianglesToRef=function(a,e,t,i){const s=U.Vector3[0],r=U.Vector3[1];let n=1/0;for(let o=this.verticesStart;o<this.verticesStart+this.verticesCount;o+=3){const l=e[o],h=e[o+1],c=e[o+2],u=m.ProjectOnTriangleToRef(a,l,h,c,r);u<n&&(s.copyFrom(r),n=u)}return i.copyFrom(s),n};Ss.prototype.projectToRef=function(a,e,t,i){const s=this.getMaterial();if(!s)return-1;let r=3,n=!1;switch(s.fillMode){case 3:case 5:case 6:case 8:return-1;case 7:r=1,n=!0;break}return s.fillMode===4?-1:!t.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(a,e,t,i):this._projectOnTrianglesToRef(a,e,t,r,n,i)};var pr;(function(a){a[a.DEHYDRATED=0]="DEHYDRATED",a[a.HOVER=1]="HOVER",a[a.TOUCH=2]="TOUCH"})(pr||(pr={}));var So;(function(a){a[a.DISABLED=0]="DISABLED",a[a.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",a[a.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT"})(So||(So={}));class Xn extends _s{constructor(e,t){super(e),this._options=t,this._tmpRay=new tt(new m,new m),this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n,currentAnimationState:pr.DEHYDRATED,grabRay:new tt(new m,new m),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Xn._IdCounter++,pickedPointVisualCue:o},this._controllers[i.uniqueId]._worldScaleObserver=this._controllers[i.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add(l=>{if(l.newScaleFactor!==l.previousScaleFactor){this._controllers[i.uniqueId].touchCollisionMesh.dispose(),this._controllers[i.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:h,touchCollisionMeshFunction:c,hydrateCollisionMeshFunction:u}=this._generateNewTouchPointMesh();this._controllers[i.uniqueId].touchCollisionMesh=h,this._controllers[i.uniqueId].touchCollisionMeshFunction=c,this._controllers[i.uniqueId].hydrateCollisionMeshFunction=u,this._controllers[i.uniqueId].pickedPointVisualCue=this._generateVisualCue()}}),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(i);case"gaze":return null;case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new q(.8,.8,.8),this.selectionMeshPickedColor=new q(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,this._options.nearInteractionControllerMode===void 0&&(this._options.nearInteractionControllerMode=So.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return super.attach()?(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0):!1}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}setFarInteractionFeature(e){this._farInteractionFeature=e}_nearPickPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable}_nearGrabPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable}_nearInteractionPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)}_controllerAvailablePredicate(e,t){let i=e;for(;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0}_handleTransitionAnimation(e,t){var i;if(!(e.currentAnimationState===t||this._options.nearInteractionControllerMode!==So.CENTERED_IN_FRONT||(i=e.xrController)!=null&&i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case pr.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===pr.HOVER)break;case pr.HOVER:if(e.touchCollisionMeshFunction(!0),t===pr.TOUCH)break}else switch(e.currentAnimationState){case pr.TOUCH:if(e.touchCollisionMeshFunction(!1),t===pr.HOVER)break;case pr.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===pr.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(U.Vector3[0]),s.grabRay.direction.copyFrom(U.Vector3[0]),this._options.nearInteractionControllerMode===So.CENTERED_IN_FRONT&&!((r=s.xrController)!=null&&r.inputSource.hand)&&(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var l;const i=this._controllers[t],s=(l=i.xrController)==null?void 0:l.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad)){i.pick=null;return}if(i.hoverInteraction=!1,i.nearInteraction=!1,i.xrController){if(s){const h=s.get("index-finger-tip");if(h){const c=e.getJointPose(h,this._xrSessionManager.referenceSpace);if(c&&c.transform){const u=this._scene.useRightHandedSystem?1:-1;U.Vector3[0].set(c.transform.position.x,c.transform.position.y,c.transform.position.z*u),U.Quaternion[0].set(c.transform.orientation.x,c.transform.orientation.y,c.transform.orientation.z*u,c.transform.orientation.w*u),this._processTouchPoint(t,U.Vector3[0],U.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==So.DISABLED){let h=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===So.CENTERED_ON_CONTROLLER&&(h=i.xrController.grip),this._processTouchPoint(t,h.position,h.rotationQuaternion)}}else return;const r=(h,c)=>{let u=null;return!c||!c.hit?u=h:!h||!h.hit||c.distance<h.distance?u=c:u=h,u},n=h=>{let c=new es,u=!1;const d=h&&h.pickedPoint&&h.hit;return h!=null&&h.pickedPoint&&(u=h.pickedPoint.x===0&&h.pickedPoint.y===0&&h.pickedPoint.z===0),d&&!u&&(c=h),c};if(!i.grabInteraction){let h=null,c=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(c=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const u=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,f=>this._nearInteractionPredicate(f)),d=r(u,c);if(d&&d.hit&&(h=n(d),h.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let f=null;const _=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(i,_,this._utilityLayerScene,T=>this._nearPickPredicate(T)));const p=this._pickWithSphere(i,_,this._scene,T=>this._nearPickPredicate(T)),g=r(p,f),x=n(g);x.hit&&(h=x,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=h,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=pr.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=pr.TOUCH:i.hoverInteraction&&(o=pr.HOVER),this._handleTransitionAnimation(i,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene:this._scene,t=pa("nearInteraction",{diameter:.0035*3*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=Q.Identity();const i=new de("targetMat",e);return i.specularColor=q.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return this._farInteractionFeature?this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e):!0}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{!this._options.enableNearInteractionOnAllControllers&&e.uniqueId!==this._attachedController||!t.xrController||!t.xrController.inputSource.hand&&(!this._options.nearInteractionControllerMode||!t.xrController.inputSource.gamepad)||(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))});const s=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):r&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const r=n=>{t.squeezeComponent=n.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}):(t.selectionComponent=n.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},n=o=>{t.xrController&&o.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:n,selectstart:r},this._xrSessionManager.session.addEventListener("selectstart",r),this._xrSessionManager.session.addEventListener("selectend",n)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(i=>{const s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{if(!t.downTriggered)return;const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new es,i)}),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const i=Object.keys(this._controllers);i.length?this._attachedController=i[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene:this._scene,i=pa("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:Ei.ParseFromSnippetAsync("8RUNKL#3",t).then(P=>{i.material=P});const s=new Jv;s.setEasingMode(Us.EASINGMODE_EASEINOUT);const r=new m(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new m(n,n,n).scaleInPlace(e),l=this._controllerPickRadius*(7/6),h=new m(l,l,l).scaleInPlace(e),c=this._controllerPickRadius*(4/5),u=new m(c,c,c).scaleInPlace(e),d=this._controllerPickRadius*(3/2),f=new m(d,d,d).scaleInPlace(e),_=[{frame:0,value:r},{frame:10,value:f},{frame:18,value:o}],p=[{frame:0,value:o},{frame:10,value:u},{frame:18,value:r}],g=[{frame:0,value:m.ZeroReadOnly},{frame:12,value:h},{frame:15,value:r}],x=[{frame:0,value:r},{frame:10,value:m.ZeroReadOnly},{frame:15,value:m.ZeroReadOnly}],T=new K("touch","scaling",60,K.ANIMATIONTYPE_VECTOR3,K.ANIMATIONLOOPMODE_CONSTANT),S=new K("release","scaling",60,K.ANIMATIONTYPE_VECTOR3,K.ANIMATIONLOOPMODE_CONSTANT),C=new K("hydrate","scaling",60,K.ANIMATIONTYPE_VECTOR3,K.ANIMATIONLOOPMODE_CONSTANT),v=new K("dehydrate","scaling",60,K.ANIMATIONTYPE_VECTOR3,K.ANIMATIONLOOPMODE_CONSTANT);return T.setEasingFunction(s),S.setEasingFunction(s),C.setEasingFunction(s),v.setEasingFunction(s),T.setKeys(_),S.setKeys(p),C.setKeys(g),v.setKeys(x),{touchCollisionMesh:i,touchCollisionMeshFunction:P=>{const L=P?T:S;t.beginDirectAnimation(i,[L],0,18,!1,1)},hydrateCollisionMeshFunction:P=>{const L=P?C:v;P&&(i.isVisible=!0),t.beginDirectAnimation(i,[L],0,15,!1,1,()=>{P||(i.isVisible=!1)})}}}_pickWithSphere(e,t,i,s){const r=new es;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=ua.CreateFromCenterAndRadius(n,t);for(let l=0;l<i.meshes.length;l++){const h=i.meshes[l];if(!s(h)||!this._controllerAvailablePredicate(h,e.xrController.uniqueId))continue;const c=Xn.PickMeshWithSphere(h,o);c&&c.hit&&c.distance<r.distance&&(r.hit=c.hit,r.pickedMesh=h,r.pickedPoint=c.pickedPoint,r.aimTransform=e.xrController.pointer,r.gripTransform=e.xrController.grip||null,r.originMesh=e.touchCollisionMesh,r.distance=c.distance,r.bu=c.bu,r.bv=c.bv,r.faceId=c.faceId,r.subMeshId=c.subMeshId)}}return r}static PickMeshWithSphere(e,t,i=!1){const s=e.subMeshes,r=new es,n=e.getBoundingInfo();if(!e._generatePointsArray()||!e.subMeshes||!n||!i&&!ua.Intersects(n.boundingSphere,t))return r;const o=U.Vector3[0],l=U.Vector3[1],h=new tt(m.Zero(),m.Zero(),1);let c=1/0,u,d,f,_;const p=U.Vector3[2],g=U.Matrix[0];g.copyFrom(e.getWorldMatrix()),g.invert(),m.TransformCoordinatesToRef(t.center,g,p);for(let x=0;x<s.length;x++)s[x].projectToRef(p,e._positions,e.getIndices(),l),m.TransformCoordinatesToRef(l,e.getWorldMatrix(),l),u=m.Distance(l,t.center),f=m.Distance(l,e.getAbsolutePosition()),d=m.Distance(t.center,e.getAbsolutePosition()),d!==-1&&f!==-1&&f>d&&(u=0,l.copyFrom(t.center)),u!==-1&&u<c&&(c=u,tt.CreateFromToToRef(t.center,l,h),h.length=c*2,_=h.intersectsMesh(e),o.copyFrom(l));return c<t.radius&&(r.hit=!0,r.distance=c,r.pickedMesh=e,r.pickedPoint=o.clone(),_&&_.bu!==null&&_.bv!==null&&(r.faceId=_.faceId,r.subMeshId=_.subMeshId,r.bu=_.bu,r.bv=_.bv)),r}}Xn._IdCounter=200;Xn.Name=dt.NEAR_INTERACTION;Xn.Version=1;fi.AddWebXRFeature(Xn.Name,(a,e)=>()=>new Xn(a,e),Xn.Version,!0);class $D{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class hg{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new G,this._onSessionGranted=s=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),typeof window<"u"&&window.location&&window.location.protocol==="http:"&&window.location.hostname!=="localhost")throw X.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const s=t.sessionMode||"immersive-vr",r=t.referenceSpaceType||"local-floor";let o=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(typeof SVGSVGElement>"u"?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";o+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const l=document.createElement("style");l.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(l);const h=document.createElement("button");h.className="babylonVRicon",h.title=`${s} - ${r}`,this._buttons.push(new $D(h,s,r)),this._buttons[this._buttons.length-1].update=function(c){this.element.style.display=c===null||c===this?"":"none",h.className="babylonVRicon"+(c===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map(r=>e.sessionManager.isSessionSupportedAsync(r.sessionMode));e.onStateChangedObservable.add(r=>{r==qi.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((r,n)=>{r?(this.overlay.appendChild(this._buttons[n].element),this._buttons[n].element.onclick=this._enterXRWithButtonIndex.bind(this,n)):X.Warn(`Session mode "${this._buttons[n].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const s=new hg(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==qi.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==qi.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(t=>{t.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}var Co;(function(a){a[a.INIT=0]="INIT",a[a.STARTED=1]="STARTED",a[a.ENDED=2]="ENDED"})(Co||(Co={}));function Od(a){let e=0;const t=Date.now();a.observableParameters=a.observableParameters??{};const i=a.contextObservable.add(s=>{const r=Date.now();e=r-t;const n={startTime:t,currentTime:r,deltaTime:e,completeRate:e/a.timeout,payload:s};a.onTick&&a.onTick(n),a.breakCondition&&a.breakCondition()&&(a.contextObservable.remove(i),a.onAborted&&a.onAborted(n)),e>=a.timeout&&(a.contextObservable.remove(i),a.onEnded&&a.onEnded(n))},a.observableParameters.mask,a.observableParameters.insertFirst,a.observableParameters.scope);return i}class KD{constructor(e){this.onEachCountObservable=new G,this.onTimerAbortedObservable=new G,this.onTimerEndedObservable=new G,this.onStateChangedObservable=new G,this._observer=null,this._breakOnNextTick=!1,this._tick=t=>{const i=Date.now();this._timer=i-this._startTime;const s={startTime:this._startTime,currentTime:i,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:t},r=this._breakOnNextTick||this._breakCondition(s);r||this._timer>=this._timeToEnd?this._stop(s,r):this.onEachCountObservable.notifyObservers(s)},this._setState(Co.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===Co.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(Co.STARTED)}stop(){this._state===Co.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(Co.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class yl extends _s{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,i=>i.name==="rotationCone");t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new xe(1,1,1,1),this._tmpRay=new tt(new m,new m),this._tmpVector=new m,this._tmpQuaternion=new Q,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new G,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new G,this.onAfterCameraTeleportRotation=new G,this._attachController=i=>{if(this._controllers[i.uniqueId]||this._options.forceHandedness&&i.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[i.uniqueId]={xrController:i,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const s=this._controllers[i.uniqueId];if(s.xrController.inputSource.targetRayMode==="tracked-pointer"&&s.xrController.inputSource.gamepad){const r=()=>{if(i.motionController){const n=i.motionController.getComponentOfType(Ar.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(Ar.TOUCHPAD_TYPE);if(!n||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;s.teleportationState.mainComponentUsed=!0,s.teleportationComponent=o,s.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!this.teleportationEnabled)return;const l=()=>{s.teleportationState.forward=!0,s.teleportationState.initialHit=!1,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const h=this._options.timeToTeleport||3e3;Od({timeout:h,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};o.changes.pressed&&(o.changes.pressed.current?this._options.timeToTeleportStart?Od({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{o.pressed&&l()}}):l():(s.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else s.teleportationComponent=n,s.onAxisChangedObserver=n.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&s.teleportationState.backwards&&(s.teleportationState.backwards=!1),o.y>.7&&!s.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!s.teleportationState.backwards){s.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,Q.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const l=this._xrSessionManager.scene.pickWithRay(this._tmpRay,h=>this._floorMeshes.indexOf(h)!==-1);l&&l.pickedPoint&&(this._options.xrInput.xrCamera.position.x=l.pickedPoint.x,this._options.xrInput.xrCamera.position.z=l.pickedPoint.z)}if(o.y<-.7&&!this._currentTeleportationControllerId&&!s.teleportationState.rotating&&this.teleportationEnabled&&(s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(s.teleportationState.forward)this._currentTeleportationControllerId===s.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{s.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):s.teleportationState.currentRotation=0);else if(!s.teleportationState.rotating&&Math.abs(o.x)>.7){s.teleportationState.rotating=!0;const l=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(l),Q.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else s.teleportationState.rotating=!1;o.x===0&&o.y===0&&(s.teleportationState.blocked&&(s.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),s.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?r():i.onMotionControllerInitObservable.addOnce(()=>{r()})}else{s.teleportationState.mainComponentUsed=!0;let r=!1;const n=()=>{this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.forward=!0,s.teleportationState.initialHit=!1,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const o=this._options.timeToTeleport||3e3;Od({timeout:o,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add(o=>{o.type===Re.POINTERDOWN?(r=!1,this._options.timeToTeleportStart?Od({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&n()},breakCondition:()=>r?(r=!1,!0):!1}):n()):o.type===Re.POINTERUP&&(r=!0,s.teleportationState.forward=!1,this._currentTeleportationControllerId="")})}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new xe(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add(i=>{var s;this.parabolicCheckRadius=this.parabolicCheckRadius/i.previousScaleFactor*i.newScaleFactor,(s=this._options.teleportationTargetMesh)==null||s.scaling.scaleInPlace(i.newScaleFactor/i.previousScaleFactor)})}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return super.attach()?(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0):!1}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);t!==-1&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);t!==-1&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(t===-1){for(let i=0;i<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}}return t!==-1?(this._snapToPositions.splice(t,1),!0):!1}setSelectionFeature(e){this._selectionFeature=e}_onXRFrame(e){const t=this._xrSessionManager.currentFrame,i=this._xrSessionManager.scene;if(!this.attach||!t)return;const s=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!s)return;s.rotationQuaternion=s.rotationQuaternion||new Q;const r=this._controllers[this._currentTeleportationControllerId];if(r&&r.teleportationState.forward){Q.RotationYawPitchRollToRef(r.teleportationState.currentRotation+r.teleportationState.baseRotation,0,0,s.rotationQuaternion);let n=!1;const o=r.xrController.inputSource.targetRayMode!=="transient-pointer";if(r.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){const l=i.pickWithRay(this._tmpRay,c=>{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(c)||this._options.blockAllPickableMeshes&&c.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(c)!==-1)return!0;const u=this._floorMeshes.indexOf(c);return u===-1?!1:this._floorMeshes[u].absolutePosition.y<this._options.xrInput.xrCamera.globalPosition.y}),h=l&&l.pickedMesh&&this._floorMeshes.indexOf(l.pickedMesh)!==-1;if(l&&l.pickedMesh&&!h){if(r.teleportationState.mainComponentUsed&&!r.teleportationState.initialHit){r.teleportationState.forward=!1;return}r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(l);return}else l&&l.pickedPoint&&(r.teleportationState.initialHit=!0,r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(l),this._setTargetMeshVisibility(!0,!1,o),this._showParabolicPath(l))}if(this.parabolicRayEnabled&&!n){const l=r.xrController.pointer.rotationQuaternion.toEulerAngles().x,h=1+(Math.PI/2-Math.abs(l)),c=this.parabolicCheckRadius*h;this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(c*2),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(c)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();const u=i.pickWithRay(this._tmpRay,f=>this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(f)||this._options.blockAllPickableMeshes&&f.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(f)!==-1?!0:this._floorMeshes.indexOf(f)!==-1),d=u&&u.pickedMesh&&this._floorMeshes.indexOf(u.pickedMesh)!==-1;if(u&&u.pickedMesh&&!d){if(r.teleportationState.mainComponentUsed&&!r.teleportationState.initialHit){r.teleportationState.forward=!1;return}r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(u);return}else u&&u.pickedPoint&&(r.teleportationState.initialHit=!0,r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(u),this._setTargetMeshVisibility(!0,!1,o),this._showParabolicPath(u))}this._setTargetMeshVisibility(n,!1,o)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=km("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const n=new yu("teleportationPlaneDynamicTexture",512,e,!0);n.hasAlpha=!0;const o=n.getContext(),l=512/2,h=512/2,c=200;o.beginPath(),o.arc(l,h,c,0,2*Math.PI,!1),o.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",o.fill(),o.lineWidth=10,o.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",o.stroke(),o.closePath(),n.update();const u=new de("teleportationPlaneMaterial",e);u.diffuseTexture=n,t.material=u}const i=Bl("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const r=new K("animationInnerCircle","position.y",30,K.ANIMATIONTYPE_FLOAT,K.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new FE;o.setEasingMode(Us.EASINGMODE_EASEINOUT),r.setEasingFunction(o),i.animations=[],i.animations.push(r),e.beginAnimation(i,0,60,!0)}const s=Hm("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Bs.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const r=new de("torusConsMat",e);r.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,r.disableLighting?r.emissiveColor=new q(.3,.3,1):r.diffuseColor=new q(.3,.3,1),r.alpha=.9,i.material=r,s.material=r,this._teleportationRingMaterial=r}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach(n=>{const o=m.DistanceSquared(n,e);o<=r&&o<s&&(s=o,i=n)})}return i}_setTargetMeshPosition(e){const t=e.pickedPoint;if(!this._options.teleportationTargetMesh||!t)return;const i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}_setTargetMeshVisibility(e,t,i){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible===e&&!t||(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(s=>{s.isVisible=e}),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach())))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Li.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=On.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=qm("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,this._options.renderingGroupId!==void 0&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(!(!t||!t.teleportationState.forward||!this.teleportationEnabled)&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!(this.snapPointsOnly&&!this._snappedToPoint))){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const i=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,Q.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}yl.Name=dt.TELEPORTATION;yl.Version=1;fi.AddWebXRFeature(yl.Name,(a,e)=>()=>new yl(a,e),yl.Version,!0);class cg{constructor(){}static CreateAsync(e,t={}){const i=new cg;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new hg(e,s)}return lg.CreateAsync(e).then(s=>{if(i.baseExperience=s,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new YD(s.sessionManager,s.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const r={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(Hn.Name,t.useStablePlugins?"stable":"latest",r),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(yl.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}if(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Xn.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Ft.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(s=>(O.Error("Error initializing XR"),O.Error(s),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}Ee.prototype.createDefaultLight=function(a=!1){if(a&&this.lights)for(let e=0;e<this.lights.length;e++)this.lights[e].dispose();this.lights.length===0&&new Ho("default light",m.Up(),this)};Ee.prototype.createDefaultCamera=function(a=!1,e=!1,t=!1){if(e&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){const i=this.getWorldExtends(l=>l.isVisible&&l.isEnabled()),s=i.max.subtract(i.min),r=i.min.add(s.scale(.5));let n,o=s.length()*1.5;if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),a){const l=new $t("default camera",-(Math.PI/2),Math.PI/2,o,r,this);l.lowerRadiusLimit=o*.01,l.wheelPrecision=100/o,n=l}else{const l=new qs("default camera",new m(r.x,r.y,-o),this);l.setTarget(r),n=l}n.minZ=o*.01,n.maxZ=o*1e3,n.speed=o*.2,this.activeCamera=n,t&&n.attachControl()}};Ee.prototype.createDefaultCameraOrLight=function(a=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(a,e,t)};Ee.prototype.createDefaultSkybox=function(a,e=!1,t=1e3,i=0,s=!0){if(!a)return O.Warn("Can not create default skybox without environment texture."),null;s&&a&&(this.environmentTexture=a);const r=Ym("hdrSkyBox",{size:t},this);if(e){const n=new ye("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=k.SKYBOX_MODE),n.microSurface=1-i,n.disableLighting=!0,n.twoSidedLighting=!0,r.material=n}else{const n=new de("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=k.SKYBOX_MODE),n.disableLighting=!0,r.material=n}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r};Ee.prototype.createDefaultEnvironment=function(a){return Uo?new Uo(a,this):null};Ee.prototype.createDefaultVRExperience=function(a={}){return new Ul(this,a)};Ee.prototype.createDefaultXRExperienceAsync=function(a={}){return cg.CreateAsync(this,a).then(e=>e)};function fT(a){for(;a.firstChild;)a.removeChild(a.firstChild);a.srcObject=null,a.src="",a.removeAttribute("src")}class ga extends k{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new G),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):O.Error(e==null?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((e==null?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}else if(!this.video.muted){O.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(t=>{this._processError(t)});return}}this._processError(e)})}constructor(e,t,i,s=!1,r=!1,n=k.TRILINEAR_SAMPLINGMODE,o={},l,h=5){var u;super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||X.IsExponentOfTwo(this.video.videoWidth)&&X.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=k.WRAP_ADDRESSMODE,this.wrapV=k.WRAP_ADDRESSMODE):(this.wrapU=k.CLAMP_ADDRESSMODE,this.wrapV=k.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(this._texture!=null)if(this._displayingPosterTexture)this._displayingPosterTexture=!1;else return;if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),!this.video.autoplay&&!this._settings.poster&&!this._settings.independentVideoSource){const d=this.video.onplaying,f=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=f,this.video.onplaying=d,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}else this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._reset=()=>{this._texture!=null&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(this._texture==null||this.video.readyState<this.video.HAVE_CURRENT_DATA||this._displayingPosterTexture)return;const d=this.getScene().getFrameId();this._frameId!==d&&(this._frameId=d,this._getEngine().updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:this.video,this._invertY))},this._settings={autoPlay:!0,loop:!0,autoUpdateTexture:!0,...o},this._onError=l,this._generateMipMaps=s,this._initialSamplingMode=n,this.autoUpdateTexture=this._settings.autoUpdateTexture,this._currentSrc=t,this.name=e||this._getName(t),this.video=this._getVideo(t),(u=this._engine)!=null&&u.createExternalTexture&&(this._externalTexture=this._engine.createExternalTexture(this.video)),this._settings.independentVideoSource||(this._settings.poster&&(this.video.poster=this._settings.poster),this._settings.autoPlay!==void 0&&(this.video.autoplay=this._settings.autoPlay),this._settings.loop!==void 0&&(this.video.loop=this._settings.loop),this._settings.muted!==void 0&&(this.video.muted=this._settings.muted),this.video.setAttribute("playsinline",""),this.video.addEventListener("paused",this._updateInternalTexture),this.video.addEventListener("seeked",this._updateInternalTexture),this.video.addEventListener("loadeddata",this._updateInternalTexture),this.video.addEventListener("emptied",this._reset),this._settings.autoPlay&&this._handlePlay()),this._createInternalTextureOnEvent=this._settings.poster&&!this._settings.autoPlay?"play":"canplay",this.video.addEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._format=h;const c=this.video.readyState>=this.video.HAVE_CURRENT_DATA;this._settings.poster&&(!this._settings.autoPlay||!c)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):c&&this._createInternalTexture()}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:typeof e=="object"?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return X.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(X.SetCorsBehavior(e,t),t.src=e):(X.SetCorsBehavior(e[0],t),e.forEach(i=>{const s=document.createElement("source");s.src=i,t.appendChild(s)})),this.onDisposeObservable.addOnce(()=>{fT(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new ga(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)==null||e.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(r.mozSrcObject!==void 0?r.mozSrcObject=t:typeof r.srcObject=="object"?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise(n=>{const o=()=>{const l=new ga("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{r.remove()}),l.onDisposeObservable.addOnce(()=>{fT(r)}),n(l),r.removeEventListener("playing",o)};r.addEventListener("playing",o),r.play()})}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce(()=>{r.getTracks().forEach(o=>{o.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then(function(n){t&&t(n)}).catch(function(n){O.Error(n.name)})}}E([I("settings")],ga.prototype,"_settings",void 0);E([I("src")],ga.prototype,"_currentSrc",void 0);E([I()],ga.prototype,"isVideo",void 0);k._CreateVideoTexture=(a,e,t,i=!1,s=!1,r=k.TRILINEAR_SAMPLINGMODE,n={},o,l=5)=>new ga(a,e,t,i,s,r,n,o,l);V("BABYLON.VideoTexture",ga);class ug extends js{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new ga((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,k.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(n=>{var o;((o=n.pickInfo)==null?void 0:o.pickedMesh)===this.mesh&&this._texture.video.play()},Re.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}ug.MODE_MONOSCOPIC=js.MODE_MONOSCOPIC;ug.MODE_TOPBOTTOM=js.MODE_TOPBOTTOM;ug.MODE_SIDEBYSIDE=js.MODE_SIDEBYSIDE;const jD="glowMapGenerationPixelShader",qD=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform sampler2D emissiveSampler;
#endif
#ifdef VERTEXALPHA
varying vec4 vColor;
#endif
uniform vec4 glowColor;uniform float glowIntensity;
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
vec4 finalColor=glowColor;
#ifdef DIFFUSE
vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW
finalColor.a*=albedoTexture.a;
#endif
#ifdef HIGHLIGHT
finalColor.a=albedoTexture.a;
#endif
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vUVOpacity);
#ifdef OPACITYRGB
finalColor.a*=getLuminance(opacityMap.rgb);
#else
finalColor.a*=opacityMap.a;
#endif
finalColor.a*=opacityIntensity;
#endif
#ifdef VERTEXALPHA
finalColor.a*=vColor.a;
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE)
discard;
#endif
#ifdef EMISSIVE
vec4 emissive=texture2D(emissiveSampler,vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
gl_FragColor=emissive*finalColor*glowIntensity;
#else
gl_FragColor=finalColor*glowIntensity;
#endif
#ifdef HIGHLIGHT
gl_FragColor.a=glowColor.a;
#endif
}`;W.ShadersStore[jD]=qD;const QD="glowMapGenerationVertexShader",ZD=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;varying vec4 vPosition;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform mat4 opacityMatrix;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform mat4 emissiveMatrix;
#endif
#ifdef VERTEXALPHA
attribute vec4 color;varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef CUBEMAP
vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#else
vPosition=viewProjection*worldPos;gl_Position=vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef DIFFUSEUV2
vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef OPACITYUV2
vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef EMISSIVEUV2
vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#ifdef VERTEXALPHA
vColor=color;
#endif
#include<clipPlaneVertex>
}`;W.ShadersStore[QD]=ZD;class Xr{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){const s=e[i];t?this._materialForRendering[s.uniqueId]=[s,t]:delete this._materialForRendering[s.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){return this._effectIntensity[e.uniqueId]??1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new xe},this._effectIntensity={},this.neutralColor=new xe,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new G,this.onBeforeRenderMainTextureObservable=new G,this.onBeforeComposeObservable=new G,this.onBeforeRenderMeshToEffect=new G,this.onAfterRenderMeshToEffect=new G,this.onAfterComposeObservable=new G,this.onSizeChangedObservable=new G,this._materialForRendering={},this.name=e,this._scene=t||Ae.LastCreatedScene,Xr._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}_numInternalDraws(){return 1}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,generateStencilBuffer:!1,...e},this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()}_generateIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);const t=new y(this._engine,e,y.PositionKind,!1,!1,2);this._vertexBuffers[y.PositionKind]=t}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?H.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?H.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new oi("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType,!1,k.TRILINEAR_SAMPLINGMODE,!0,this._effectLayerOptions.generateStencilBuffer),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=k.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=k.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(k.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0;for(const e in this._materialForRendering){const[t,i]=this._materialForRendering[e];this._mainTexture.setMaterialForRendering(t,i)}if(this._mainTexture.customIsReadyFunction=(e,t,i)=>{if((i||t===0)&&e.subMeshes)for(let s=0;s<e.subMeshes.length;++s){const r=e.subMeshes[s],n=r.getMaterial(),o=r.getRenderingMesh();if(!n)continue;const h=o._getInstancesRenderList(r._id,!!r.getReplacementMesh()).hardwareInstancedRendering[r._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,r,n),!this._isReady(r,h,this._emissiveTextureAndColor.texture))return!1}return!0},this._mainTexture.customRenderFunction=(e,t,i,s)=>{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let r;const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r<s.length;r++)this._renderSubMesh(s.data[r]);n.setColorWrite(!0)}for(r=0;r<e.length;r++)this._renderSubMesh(e.data[r]);for(r=0;r<t.length;r++)this._renderSubMesh(t.data[r]);const o=n.getAlphaMode();for(r=0;r<i.length;r++)this._renderSubMesh(i.data[r],!0);n.setAlphaMode(o)},this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var T;const s=this._scene.getEngine(),r=e.getMesh(),n=(T=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:T[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[y.PositionKind];let c=!1,u=!1;if(o){const S=o.needAlphaTesting(),C=o.getAlphaTestTexture(),v=C&&C.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);C&&(S||v)&&(l.push("#define DIFFUSE"),r.isVerticesDataPresent(y.UV2Kind)&&C.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),u=!0):r.isVerticesDataPresent(y.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),S&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),C.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const b=o.opacityTexture;b&&(l.push("#define OPACITY"),r.isVerticesDataPresent(y.UV2Kind)&&b.coordinatesIndex===1?(l.push("#define OPACITYUV2"),u=!0):r.isVerticesDataPresent(y.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),r.isVerticesDataPresent(y.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),u=!0):r.isVerticesDataPresent(y.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(y.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==ee.MATERIAL_OPAQUE&&(h.push(y.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(y.UVKind),l.push("#define UV1")),u&&(h.push(y.UV2Kind),l.push("#define UV2"));const d=new zo;if(r.useBones&&r.computeBonesUsingShaders){h.push(y.MatricesIndicesKind),h.push(y.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(y.MatricesIndicesExtraKind),h.push(y.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const S=r.skeleton;S&&S.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(S?S.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else l.push("#define NUM_BONE_INFLUENCERS 0");const f=r.morphTargetManager;let _=0;f&&(_=f.numMaxInfluencers||f.numInfluencers,_>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+_),f.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),$u(h,r,_))),t&&(l.push("#define INSTANCES"),oo(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),no(o,this._scene,l),this._addCustomEffectDefines(l);const p=e._getDrawWrapper(void 0,!0),g=p.defines,x=l.join(`
`);if(g!==x){const S=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];sn(S),p.setEffect(this._engine.createEffect("glowMapGeneration",h,S,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],x,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),x)}return p.effect.isReady()}render(){for(let n=0;n<this._postProcesses.length;n++)if(!this._postProcesses[n].isReady())return;const e=this._scene.getEngine(),t=this._numInternalDraws();let i=!0;for(let n=0;n<t;++n){let o=this._mergeDrawWrapper[n];o||(o=this._mergeDrawWrapper[n]=new Bi(this._engine),o.setEffect(this._createMergeEffect())),i=i&&o.effect.isReady()}if(!i)return;this.onBeforeComposeObservable.notifyObservers(this);const s=e.getAlphaMode();for(let n=0;n<t;++n){const o=this._mergeDrawWrapper[n];e.enableEffect(o),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,o.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(o.effect,n)}e.setAlphaMode(s),this.onAfterComposeObservable.notifyObservers(this);const r=this._mainTexture.getSize();this._setMainTextureSize(),(r.width!==this._mainTextureDesiredSize.width||r.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}hasMesh(e){return this.renderingGroupId===-1||e.renderingGroupId===this.renderingGroupId}shouldRender(){return this.isEnabled&&this._shouldRender}_shouldRenderMesh(e){return!0}_canRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_shouldRenderEmissiveTextureForMesh(){return!0}_renderSubMesh(e,t=!1){var p;if(!this.shouldRender())return;const i=e.getMaterial(),s=e.getMesh(),r=e.getReplacementMesh(),n=e.getRenderingMesh(),o=e.getEffectiveMesh(),l=this._scene,h=l.getEngine();if(o._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!i||!this._canRenderMesh(n,i))return;let c=n.overrideMaterialSideOrientation??i.sideOrientation;o._getWorldMatrixDeterminant()<0&&(c=c===ee.ClockWiseSideOrientation?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation);const d=c===ee.ClockWiseSideOrientation;h.setState(i.backFaceCulling,i.zOffset,void 0,d,i.cullBackFaces,void 0,i.zOffsetUnits);const f=n._getInstancesRenderList(e._id,!!r);if(f.mustReturn||!this._shouldRenderMesh(n))return;const _=f.hardwareInstancedRendering[e._id]||n.hasThinInstances;if(this._setEmissiveTextureAndColor(n,e,i),this.onBeforeRenderMeshToEffect.notifyObservers(s),this._useMeshMaterial(n))n.render(e,t,r||void 0);else if(this._isReady(e,_,this._emissiveTextureAndColor.texture)){const g=(p=o._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:p[h.currentRenderPassId];let x=e._getDrawWrapper();if(!x&&g&&(x=g._getDrawWrapper()),!x)return;const T=x.effect;if(h.enableEffect(x),_||n._bind(e,T,i.fillMode),g?g.bindForSubMesh(o.getWorldMatrix(),o,e):(T.setMatrix("viewProjection",l.getTransformMatrix()),T.setMatrix("world",o.getWorldMatrix()),T.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!g){const S=i.needAlphaTesting(),C=i.getAlphaTestTexture(),v=C&&C.hasAlpha&&(i.useAlphaFromDiffuseTexture||i._useAlphaFromAlbedoTexture);if(C&&(S||v)){T.setTexture("diffuseSampler",C);const A=C.getTextureMatrix();A&&T.setMatrix("diffuseMatrix",A)}const b=i.opacityTexture;if(b){T.setTexture("opacitySampler",b),T.setFloat("opacityIntensity",b.level);const A=b.getTextureMatrix();A&&T.setMatrix("opacityMatrix",A)}if(this._emissiveTextureAndColor.texture&&(T.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),T.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),n.useBones&&n.computeBonesUsingShaders&&n.skeleton){const A=n.skeleton;if(A.isUsingTextureForMatrices){const P=A.getTransformMatrixTexture(n);if(!P)return;T.setTexture("boneSampler",P),T.setFloat("boneTextureWidth",4*(A.bones.length+1))}else T.setMatrices("mBones",A.getTransformMatrices(n))}Sa(n,T),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(T),t&&h.setAlphaMode(i.alphaMode),T.setFloat("glowIntensity",this.getEffectIntensity(n)),Gr(T,i,l)}n._processRendering(o,e,T,i.fillMode,f,_,(S,C)=>T.setMatrix("world",C))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[y.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){const e=this._vertexBuffers[y.PositionKind];e&&(e.dispose(),this._vertexBuffers[y.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(const i of this._mergeDrawWrapper)i.dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();const t=this._scene.effectLayers.indexOf(this,0);t>-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return X.Instantiate(e.customType).Parse(e,t,i)}}Xr._SceneComponentInitialization=a=>{throw Ge("EffectLayerSceneComponent")};E([I()],Xr.prototype,"name",void 0);E([cm()],Xr.prototype,"neutralColor",void 0);E([I()],Xr.prototype,"isEnabled",void 0);E([mv()],Xr.prototype,"camera",null);E([I()],Xr.prototype,"renderingGroupId",null);E([I()],Xr.prototype,"disableBoundingBoxesFromEffectLayer",void 0);wi.AddParser(he.NAME_EFFECTLAYER,(a,e,t,i)=>{if(a.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s<a.effectLayers.length;s++){const r=Xr.Parse(a.effectLayers[s],e,i);t.effectLayers.push(r)}}});wi.prototype.removeEffectLayer=function(a){const e=this.effectLayers.indexOf(a);return e!==-1&&this.effectLayers.splice(e,1),e};wi.prototype.addEffectLayer=function(a){this.effectLayers.push(a)};class JD{constructor(e){this.name=he.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||Ae.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine(),this.scene.effectLayers=[])}register(){this.scene._isReadyForMeshStage.registerStep(he.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(he.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(he.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(he.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){const e=this.scene.effectLayers;for(const t of e)t._rebuild()}serialize(e){e.effectLayers=[];const t=this.scene.effectLayers;for(const i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){e.effectLayers&&e.effectLayers.forEach(t=>{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const o of e.subMeshes)if(!r.isReady(o,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===ve.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==ve.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const r=s._mainTexture;r._shouldRender()&&(this.scene.incrementRenderId(),r.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i<t.length;i++){const s=t[i];s.renderingGroupId===e&&s.shouldRender()&&s.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}}Xr._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_EFFECTLAYER);e||(e=new JD(a),a._addComponent(e))};const eO="glowMapMergePixelShader",tO=`varying vec2 vUV;uniform sampler2D textureSampler;
#ifdef EMISSIVE
uniform sampler2D textureSampler2;
#endif
uniform float offset;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef EMISSIVE
baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;
#else
baseColor.a=abs(offset-baseColor.a);
#ifdef STROKE
float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;
#endif
#endif
#if LDR
baseColor=clamp(baseColor,0.,1.0);
#endif
gl_FragColor=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[eO]=tO;const iO="glowMapMergeVertexShader",sO=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[iO]=sO;wi.prototype.getGlowLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===Ur.EffectName)return this.effectLayers[t];return null};class Ur extends Xr{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new xe(0,0,0,1),this._options={mainTextureRatio:Ur.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return Ur.EffectName}_createMergeEffect(){let e=`#define EMISSIVE 
`;return this._options.ldrMerge&&(e+=`#define LDR 
`),this._engine.createEffect("glowMapMerge",[y.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?H.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?H.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new oi("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=k.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=k.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(k.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const s=Math.floor(e/2),r=Math.floor(t/2);this._blurTexture2=new oi("GlowLayerBlurRTT2",{width:s,height:r},this._scene,!1,!0,i),this._blurTexture2.wrapU=k.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=k.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(k.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new ts("GlowLayerHBP1",new Z(1,0),n,{width:e,height:t},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new ts("GlowLayerVBP1",new Z(0,1),n,{width:e,height:t},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new ts("GlowLayerHBP2",new Z(1,0),n,{width:s,height:r},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new ts("GlowLayerVBP2",new Z(0,1),n,{width:s,height:r},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{const o=this._blurTexture1.renderTarget;if(o){this._scene.postProcessManager.directRender(this._postProcesses1,o,!0);const l=this._blurTexture2.renderTarget;l&&this._scene.postProcessManager.directRender(this._postProcesses2,l,!0),this._engine.unBindFramebuffer(l??o,!0)}}),this._postProcesses.map(o=>{o.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(ee.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const r=i.emissiveIntensity??1;s*=r,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){this._includedOnlyMeshes.indexOf(e.uniqueId)===-1&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);t!==-1&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return super.hasMesh(e)?this._includedOnlyMeshes.length?this._includedOnlyMeshes.indexOf(e.uniqueId)!==-1:this._excludedMeshes.length?this._excludedMeshes.indexOf(e.uniqueId)===-1:!0:!1}_useMeshMaterial(e){return this._meshesUsingTheirOwnMaterials.length==0?!1:this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=_e.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;t<this._includedOnlyMeshes.length;t++){const i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[t]);i&&e.includedMeshes.push(i.id)}if(e.excludedMeshes=[],this._excludedMeshes.length)for(t=0;t<this._excludedMeshes.length;t++){const i=this._scene.getMeshByUniqueId(this._excludedMeshes[t]);i&&e.excludedMeshes.push(i.id)}return e}static Parse(e,t,i){const s=_e.Parse(()=>new Ur(e.name,t,e.options),e,t,i);let r;for(r=0;r<e.excludedMeshes.length;r++){const n=t.getMeshById(e.excludedMeshes[r]);n&&s.addExcludedMesh(n)}for(r=0;r<e.includedMeshes.length;r++){const n=t.getMeshById(e.includedMeshes[r]);n&&s.addIncludedOnlyMesh(n)}return s}}Ur.EffectName="GlowLayer";Ur.DefaultBlurKernelSize=32;Ur.DefaultTextureRatio=.5;E([I()],Ur.prototype,"blurKernelSize",null);E([I()],Ur.prototype,"intensity",null);E([I("options")],Ur.prototype,"_options",void 0);V("BABYLON.GlowLayer",Ur);const rO="glowBlurPostProcessPixelShader",nO=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)
{return dot(color,vec3(0.2126,0.7152,0.0722));}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)
{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}
gl_FragColor=baseColor;}`;W.ShadersStore[rO]=nO;wi.prototype.getHighlightLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===Gs.EffectName)return this.effectLayers[t];return null};class _T extends De{constructor(e,t,i,s,r,n=k.BILINEAR_SAMPLINGMODE,o,l){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,s,r,n,o,l),this.direction=t,this.kernel=i,this.onApplyObservable.add(h=>{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class Gs extends Xr{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new G,this.onAfterBlurObservable=new G,this._instanceGlowingMeshStencilReference=Gs.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Gs.NeutralColor,this._engine.isStencilEnable||O.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Gs.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[y.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE 
`:void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?H.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?H.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new oi("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=k.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=k.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(k.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new An("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new _T("HighlightLayerHBP",new Z(1,0),this._options.blurHorizontalSize,1,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new _T("HighlightLayerVBP",new Z(0,1),this._options.blurVerticalSize,1,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new ts("HighlightLayerHBP",new Z(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new ts("HighlightLayerVBP",new Z(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const s=this._blurTexture.renderTarget;s&&(this._scene.postProcessManager.directRender(this._postProcesses,s,!0),this._engine.unBindFramebuffer(s,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(s=>{s.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(ee.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(ee.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return super.shouldRender()?!!this._meshes:!1}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(s=>{i.stencilState=s.getEngine().getStencilBuffer(),s.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(s=>{s.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:this._meshes[e.uniqueId]!==void 0&&this._meshes[e.uniqueId]!==null}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(r=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[r.uniqueId]?this._defaultStencilReference(r):r.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(r=>{this.isEnabled&&this._defaultStencilReference(r)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Gs.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=_e.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=_e.Parse(()=>new Gs(e.name,t,e.options),e,t,i);let r;for(r=0;r<e.excludedMeshes.length;r++){const n=t.getMeshById(e.excludedMeshes[r]);n&&s.addExcludedMesh(n)}for(r=0;r<e.meshes.length;r++){const n=e.meshes[r],o=t.getMeshById(n.meshId);o&&s.addMesh(o,q.FromArray(n.color),n.glowEmissiveOnly)}return s}}Gs.EffectName="HighlightLayer";Gs.NeutralColor=new xe(0,0,0,0);Gs.GlowingMeshStencilReference=2;Gs.NormalMeshStencilReference=1;E([I()],Gs.prototype,"innerGlow",void 0);E([I()],Gs.prototype,"outerGlow",void 0);E([I()],Gs.prototype,"blurHorizontalSize",null);E([I()],Gs.prototype,"blurVerticalSize",null);E([I("options")],Gs.prototype,"_options",void 0);V("BABYLON.HighlightLayer",Gs);const aO="layerPixelShader",oO=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef LINEAR
baseColor.rgb=toGammaSpace(baseColor.rgb);
#endif
#ifdef ALPHATEST
if (baseColor.a<0.4)
discard;
#endif
gl_FragColor=baseColor*color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[aO]=oO;const lO="layerVertexShader",hO=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[lO]=hO;class dg{static AddFlare(e,t,i,s,r){return new dg(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new q(1,1,1),this.texture=s?new k(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Bi(n),this._drawWrapper.effect=n.createEffect("lensFlare",[y.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}const cO="lensFlarePixelShader",uO=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[cO]=uO;const dO="lensFlareVertexShader",fO=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[dO]=fO;class Hl{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||Ae.LastCreatedScene,Hl._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=n=>i.activeCamera&&n.material&&n.isVisible&&n.isEnabled()&&n.isBlocker&&(n.layerMask&i.activeCamera.layerMask)!=0;const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[y.PositionKind]=new y(s,r,y.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){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)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=m.Project(t,D.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=m.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=this.viewportBorder*2,e.height+=this.viewportBorder*2,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return t.z>0&&!i||t.z<0&&i?(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&this._positionY<e.y+e.height,!0):!1}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const t=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();const s=new tt(this._scene.activeCamera.globalPosition,t),r=this._scene.pickWithRay(s,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>i}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),i=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(i)||!this._isVisible())return!1;let s,r;this._positionX<this.borderLimit+i.x?s=this.borderLimit+i.x-this._positionX:this._positionX>i.x+i.width-this.borderLimit?s=this._positionX-i.x-i.width+this.borderLimit:s=0,this._positionY<this.borderLimit+i.y?r=this.borderLimit+i.y-this._positionY:this._positionY>i.y+i.height-this.borderLimit?r=this._positionY-i.y-i.height+this.borderLimit:r=0;let n=s>r?s:r;n-=this.viewportBorder,n>this.borderLimit&&(n=this.borderLimit);let o=1-ge.Clamp(n/this.borderLimit,0,1);if(o<0)return!1;o>1&&(o=1),this.viewportBorder>0&&(i.x+=this.viewportBorder,i.y+=this.viewportBorder,i.width-=this.viewportBorder*2,i.height-=this.viewportBorder*2,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const l=i.x+i.width/2,h=i.y+i.height/2,c=l-this._positionX,u=h-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d<this.lensFlares.length;d++){const f=this.lensFlares[d];if(!f._drawWrapper.effect.isReady()||f.texture&&!f.texture.isReady())continue;e.enableEffect(f._drawWrapper),e.bindBuffers(this._vertexBuffers,this._indexBuffer,f._drawWrapper.effect),e.setAlphaMode(f.alphaMode);const _=l-c*f.position,p=h-u*f.position,g=f.size,x=f.size*e.getAspectRatio(this._scene.activeCamera,!0),T=2*(_/(i.width+i.x*2))-1,S=1-2*(p/(i.height+i.y*2)),C=D.FromValues(g/2,0,0,0,0,x/2,0,0,0,0,1,0,T,S,0,1);f._drawWrapper.effect.setMatrix("viewportMatrix",C),f._drawWrapper.effect.setTexture("textureSampler",f.texture),f._drawWrapper.effect.setFloat4("color",f.color.r*o,f.color.g*o,f.color.b*o,1),e.drawElementsType(ee.TriangleFillMode,0,6)}return e.setDepthBuffer(!0),e.setAlphaMode(0),!0}rebuild(){var e;this._createIndexBuffer();for(const t in this._vertexBuffers)(e=this._vertexBuffers[t])==null||e._rebuild()}dispose(){const e=this._vertexBuffers[y.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[y.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();const t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)}static Parse(e,t,i){const s=t.getLastEntryById(e.emitterId),r=e.name||"lensFlareSystem#"+e.emitterId,n=new Hl(r,s,t);n.id=e.id||r,n.borderLimit=e.borderLimit;for(let o=0;o<e.flares.length;o++){const l=e.flares[o];dg.AddFlare(l.size,l.position,q.FromArray(l.color),l.textureName?i+l.textureName:"",n)}return n}serialize(){const e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(let t=0;t<this.lensFlares.length;t++){const i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:X.GetFilename(i.texture?i.texture.name:"")})}return e}}Hl._SceneComponentInitialization=a=>{throw Ge("LensFlareSystemSceneComponent")};wi.AddParser(he.NAME_LENSFLARESYSTEM,(a,e,t,i)=>{if(a.lensFlareSystems!==void 0&&a.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let s=0,r=a.lensFlareSystems.length;s<r;s++){const n=a.lensFlareSystems[s],o=Hl.Parse(n,e,i);t.lensFlareSystems.push(o)}}});wi.prototype.getLensFlareSystemByName=function(a){for(let e=0;e<this.lensFlareSystems.length;e++)if(this.lensFlareSystems[e].name===a)return this.lensFlareSystems[e];return null};wi.prototype.getLensFlareSystemById=function(a){for(let e=0;e<this.lensFlareSystems.length;e++)if(this.lensFlareSystems[e].id===a)return this.lensFlareSystems[e];return null};wi.prototype.getLensFlareSystemByID=function(a){return this.getLensFlareSystemById(a)};wi.prototype.removeLensFlareSystem=function(a){const e=this.lensFlareSystems.indexOf(a);return e!==-1&&this.lensFlareSystems.splice(e,1),e};wi.prototype.addLensFlareSystem=function(a){this.lensFlareSystems.push(a)};class _O{constructor(e){this.name=he.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=[]}register(){this.scene._afterCameraDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)}rebuild(){for(let e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()}addFromContainer(e){e.lensFlareSystems&&e.lensFlareSystems.forEach(t=>{this.scene.addLensFlareSystem(t)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(i=>{this.scene.removeLensFlareSystem(i),t&&i.dispose()})}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;X.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();X.EndPerformanceCounter("Lens flares",t.length>0)}}}Hl._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_LENSFLARESYSTEM);e||(e=new _O(a),a._addComponent(e))};const pO="bayerDitherFunctions",mO=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}
float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); 
vec2 P2=floor(0.5*mod(_P,4.0)); 
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); 
vec2 P2=floor(0.5 *mod(_P,4.0)); 
vec2 P4=floor(0.25*mod(_P,8.0)); 
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;W.IncludesShadersStore[pO]=mO;const gO="shadowMapFragmentExtraDeclaration",xO=`#if SM_FLOAT==0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include<bayerDitherFunctions>
uniform float softTransparentShadowSM;
#endif
varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
uniform vec3 lightDataSM;varying vec3 vPositionWSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;W.IncludesShadersStore[gO]=xO;const TO="shadowMapFragment",EO=`float depthSM=vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
gl_FragDepth=clamp(depthSM,0.0,1.0); 
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
#else
gl_FragColor=pack(depthSM);
#endif
return;`;W.IncludesShadersStore[TO]=EO;const SO="shadowMapPixelShader",CO=`#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEXTURE
float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture<ALPHATESTVALUE)
discard;
#endif
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#ifdef ALPHATEXTURE
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard;
#else
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;
#endif
#endif
#include<shadowMapFragment>
}`;W.ShadersStore[SO]=CO;const vO="sceneVertexDeclaration",bO=`uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;
`;W.IncludesShadersStore[vO]=bO;const AO="meshVertexDeclaration",yO=`uniform mat4 world;uniform float visibility;
`;W.IncludesShadersStore[AO]=yO;const RO="shadowMapVertexDeclaration",IO=`#include<sceneVertexDeclaration>
#include<meshVertexDeclaration>
`;W.IncludesShadersStore[RO]=IO;const PO="shadowMapUboDeclaration",MO=`layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;W.IncludesShadersStore[PO]=MO;const DO="shadowMapVertexExtraDeclaration",OO=`#if SM_NORMALBIAS==1
uniform vec3 lightDataSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
varying vec3 vPositionWSM;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;W.IncludesShadersStore[DO]=OO;const NO="shadowMapVertexNormalBias",FO=`#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
#else
vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);
#endif
float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;
#endif
`;W.IncludesShadersStore[NO]=FO;const wO="shadowMapVertexMetric",LO=`#if SM_USEDISTANCE==1
vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#else
gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
zSM=gl_Position.z;gl_Position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
`;W.IncludesShadersStore[wO]=LO;const BO="shadowMapVertexShader",UO=`attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#include<helperFunctions>
#include<__decl__shadowMapVertex>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normWorldSM=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vec3 vNormalW=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>
gl_Position=viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEXTURE
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
}`;W.ShadersStore[BO]=UO;const VO="depthBoxBlurPixelShader",kO=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)
for (int y=-OFFSET; y<=OFFSET; y++)
colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;W.ShadersStore[VO]=kO;const GO="shadowMapFragmentSoftTransparentShadow",zO=`#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;
#endif
`;W.IncludesShadersStore[GO]=zO;class ze{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===ze.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===ze.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===ze.FILTER_PCF||e===ze.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===ze.FILTER_PCF||e===ze.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===ze.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(ze.FILTER_POISSONSAMPLING);!e&&this.filter!==ze.FILTER_POISSONSAMPLING||(this.filter=e?t:ze.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===ze.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(ze.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==ze.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:ze.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===ze.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(ze.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==ze.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:ze.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===ze.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(ze.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==ze.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:ze.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===ze.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(ze.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==ze.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:ze.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===ze.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(ze.FILTER_PCF);!e&&this.filter!==ze.FILTER_PCF||(this.filter=e?t:ze.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===ze.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(ze.FILTER_PCSS);!e&&this.filter!==ze.FILTER_PCSS||(this.filter=e?t:ze.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return ze.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(const s of e.getChildren())this.removeShadowCaster(s);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new G,this.onAfterShadowMapRenderObservable=new G,this.onBeforeShadowMapRenderMeshObservable=new G,this.onAfterShadowMapRenderMeshObservable=new G,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=ze.FILTER_NONE,this._filteringQuality=ze.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=m.Zero(),this._viewMatrix=D.Zero(),this._projectionMatrix=D.Zero(),this._transformMatrix=D.Zero(),this._cachedPosition=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=D.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),ze._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new oi(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new oi(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=k.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=k.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(k.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(s,r,n,o)=>this._renderForShadowMap(s,r,n,o),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var s;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(s=e._debugPushGroup)==null||s.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(s=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=s,this._filter===ze.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var r,n;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===ze.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(r=e._debugPopGroup)==null||r.call(e,1);return}const s=this.getShadowMapForRendering();s&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,s.renderTarget,!0),e.unBindFramebuffer(s.renderTarget,!0),(n=e._debugPopGroup)==null||n.call(e,1))});const t=new xe(0,0,0,0),i=new xe(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===ze.FILTER_PCF?s.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?s.clear(t,!0,!0,!1):s.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(s=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=s.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let s=Ts.MIN_RENDERINGGROUPS;s<Ts.MAX_RENDERINGGROUPS;s++)this._shadowMap.setRenderingAutoClearDepthStencil(s,!1)}_initializeBlurRTTAndPostProcesses(){const e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new oi(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=k.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=k.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(k.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new ts(this._light.name+"KernelBlurX",new Z(1,0),this.blurKernel,1,null,k.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new ts(this._light.name+"KernelBlurY",new Z(0,1),this.blurKernel,1,null,k.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new De(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,k.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r<s.length;r++)this._renderSubMeshForShadowMap(s.data[r]);for(r=0;r<e.length;r++)this._renderSubMeshForShadowMap(e.data[r]);for(r=0;r<t.length;r++)this._renderSubMeshForShadowMap(t.data[r]);if(this._transparencyShadow)for(r=0;r<i.length;r++)this._renderSubMeshForShadowMap(i.data[r],!0);else for(r=0;r<i.length;r++)i.data[r].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){const i=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,n=r.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||e.verticesCount===0||e._renderId===r.getRenderId())return;const l=s._getWorldMatrixDeterminant()<0;let h=i.overrideMaterialSideOrientation??o.sideOrientation;l&&(h=h===0?1:0);const c=h===0;n.setState(o.backFaceCulling,void 0,void 0,c,o.cullBackFaces);const u=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(u.mustReturn)return;const d=n.getCaps().instancedArrays&&(u.visibleInstances[e._id]!==null&&u.visibleInstances[e._id]!==void 0||i.hasThinInstances);if(!(this.customAllowRendering&&!this.customAllowRendering(e)))if(this.isReady(e,d,t)){e._renderId=r.getRenderId();const f=o.shadowDepthWrapper,_=(f==null?void 0:f.getEffect(e,this,n.currentRenderPassId))??e._getDrawWrapper(),p=Bi.GetEffect(_);n.enableEffect(_),d||i._bind(e,p,o.fillMode),this.getTransformMatrix(),p.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===st.LIGHTTYPEID_DIRECTIONALLIGHT?p.setVector3("lightDataSM",this._cachedDirection):p.setVector3("lightDataSM",this._cachedPosition);const g=this._getCamera();if(g&&p.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(g),this.getLight().getDepthMinZ(g)+this.getLight().getDepthMaxZ(g)),t&&this.enableSoftTransparentShadow&&p.setFloat("softTransparentShadowSM",s.visibility*o.alpha),f)e._setMainDrawWrapperOverride(_),f.standalone?f.baseMaterial.bindForSubMesh(s.getWorldMatrix(),i,e):o.bindForSubMesh(s.getWorldMatrix(),i,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(p.setTexture("diffuseSampler",this._opacityTexture),p.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),i.useBones&&i.computeBonesUsingShaders&&i.skeleton){const T=i.skeleton;if(T.isUsingTextureForMatrices){const S=T.getTransformMatrixTexture(i);if(!S)return;p.setTexture("boneSampler",S),p.setFloat("boneTextureWidth",4*(T.bones.length+1))}else p.setMatrices("mBones",T.getTransformMatrices(i))}Sa(i,p),i.morphTargetManager&&i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(p),Gr(p,o,r)}!this._useUBO&&!f&&this._bindCustomEffectForRenderSubMeshForShadowMap(e,p,s),bf(p,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();const x=s.getWorldMatrix();d&&(s.getMeshUniformBuffer().bindToEffect(p,"Mesh"),s.transferToEffect(x)),this.forceBackFacesOnly&&n.setState(!0,0,!1,!0,o.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(i),this.onBeforeShadowMapRenderObservable.notifyObservers(p),i._processRendering(s,e,p,o.fillMode,u,d,(T,S)=>{s!==i&&!T?(i.getMeshUniformBuffer().bindToEffect(p,"Mesh"),i.transferToEffect(S)):(s.getMeshUniformBuffer().bindToEffect(p,"Mesh"),s.transferToEffect(T?S:x))}),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(p),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===ze.FILTER_NONE||this.filter===ze.FILTER_PCSS?this._shadowMap.updateSamplingMode(k.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(k.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s){e&&e(this);return}const r=s.renderList;if(!r){e&&e(this);return}const n=[];for(const h of r)n.push(...h.subMeshes);if(n.length===0){e&&e(this);return}let o=0;const l=()=>{var h;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[o],i.useInstances,((h=n[o].getMaterial())==null?void 0:h.needAlphaBlendingForMesh(n[o].getMesh()))??!1);)if(o++,o>=n.length){e&&e(this);return}setTimeout(l,16)}};l()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(y.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===st.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s==null?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const o=e._getDrawWrapper(void 0,!0);let l=o.effect,h=o.defines;const c=[y.PositionKind],u=e.getMesh();this.normalBias&&u.isVerticesDataPresent(y.NormalKind)&&(c.push(y.NormalKind),n.push("#define NORMAL"),u.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const d=s.needAlphaTesting();if((d||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const x=s.alphaCutOff??ze.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),d&&n.push(`#define ALPHATESTVALUE ${x}${x%1===0?".":""}`),u.isVerticesDataPresent(y.UVKind)&&(c.push(y.UVKind),n.push("#define UV1")),u.isVerticesDataPresent(y.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(c.push(y.UV2Kind),n.push("#define UV2"))}const f=new zo;if(u.useBones&&u.computeBonesUsingShaders&&u.skeleton){c.push(y.MatricesIndicesKind),c.push(y.MatricesWeightsKind),u.numBoneInfluencers>4&&(c.push(y.MatricesIndicesExtraKind),c.push(y.MatricesWeightsExtraKind));const x=u.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+u.numBoneInfluencers),u.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,u),x.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(x.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const _=u.morphTargetManager;let p=0;if(_&&(p=_.numMaxInfluencers||_.numInfluencers,p>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+p),_.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),$u(c,u,p))),no(s,this._scene,n),t&&(n.push("#define INSTANCES"),oo(c),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const x of this.customShaderOptions.defines)n.indexOf(x)===-1&&n.push(x);const g=n.join(`
`);if(h!==g){h=g;let x="shadowMap";const T=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],S=["diffuseSampler","boneSampler","morphTargets"],C=["Scene","Mesh"];if(sn(T),this.customShaderOptions){if(x=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const b of this.customShaderOptions.attributes)c.indexOf(b)===-1&&c.push(b);if(this.customShaderOptions.uniforms)for(const b of this.customShaderOptions.uniforms)T.indexOf(b)===-1&&T.push(b);if(this.customShaderOptions.samplers)for(const b of this.customShaderOptions.samplers)S.indexOf(b)===-1&&S.push(b)}const v=this._scene.getEngine();l=v.createEffect(x,{attributes:c,uniformsNames:T,uniformBuffersNames:C,samplers:S,defines:g,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},v),o.setEffect(l,h)}if(!l.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;!i.shadowsEnabled||!s.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===ze.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ze.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===ze.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ze.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();n&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===ze.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===ze.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),m.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(m.Dot(this._lightDirection,m.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),D.LookAtLHToRef(t,t.add(this._lightDirection),m.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const s=i.renderList;s&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,s)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();t.done!==!0;t=e.next()){const[i,s]=t.value;s===this&&this._light._shadowGenerators.delete(i)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var i;const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let s=0;s<t.renderList.length;s++){const r=t.renderList[s];e.renderList.push(r.id)}return e}static Parse(e,t,i){const s=t.getLightById(e.lightId),r=e.cameraId!==void 0?t.getCameraById(e.cameraId):null,n=i?i(e.mapSize,s,r):new ze(e.mapSize,s,void 0,r),o=n.getShadowMap();for(let l=0;l<e.renderList.length;l++)t.getMeshesById(e.renderList[l]).forEach(function(c){o&&(o.renderList||(o.renderList=[]),o.renderList.push(c))});return e.id!==void 0&&(n.id=e.id),n.forceBackFacesOnly=!!e.forceBackFacesOnly,e.darkness!==void 0&&n.setDarkness(e.darkness),e.transparencyShadow&&n.setTransparencyShadow(!0),e.frustumEdgeFalloff!==void 0&&(n.frustumEdgeFalloff=e.frustumEdgeFalloff),e.bias!==void 0&&(n.bias=e.bias),e.normalBias!==void 0&&(n.normalBias=e.normalBias),e.usePercentageCloserFiltering?n.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?n.useContactHardeningShadow=!0:e.usePoissonSampling?n.usePoissonSampling=!0:e.useExponentialShadowMap?n.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?n.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?n.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?n.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?n.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurExponentialShadowMap=!0),e.contactHardeningLightSizeUVRatio!==void 0&&(n.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),e.filteringQuality!==void 0&&(n.filteringQuality=e.filteringQuality),e.depthScale&&(n.depthScale=e.depthScale),e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(n.useKernelBlur=e.useKernelBlur),e.blurKernel&&(n.blurKernel=e.blurKernel),n}}ze.CLASSNAME="ShadowGenerator";ze.FILTER_NONE=0;ze.FILTER_EXPONENTIALSHADOWMAP=1;ze.FILTER_POISSONSAMPLING=2;ze.FILTER_BLUREXPONENTIALSHADOWMAP=3;ze.FILTER_CLOSEEXPONENTIALSHADOWMAP=4;ze.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5;ze.FILTER_PCF=6;ze.FILTER_PCSS=7;ze.QUALITY_HIGH=0;ze.QUALITY_MEDIUM=1;ze.QUALITY_LOW=2;ze.DEFAULT_ALPHA_CUTOFF=.5;ze._SceneComponentInitialization=a=>{throw Ge("ShadowGeneratorSceneComponent")};const WO="depthPixelShader",HO=`#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
varying float vDepthMetric;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vec4 vViewPos;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
gl_FragColor=pack(vViewPos.z);
#else
gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
gl_FragColor=pack(gl_FragCoord.z);
#else
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
gl_FragColor=pack(vDepthMetric);
#else
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`;W.ShadersStore[WO]=HO;const XO="pointCloudVertexDeclaration",YO=`#ifdef POINTSIZE
uniform float pointSize;
#endif
`;W.IncludesShadersStore[XO]=YO;const $O="depthVertexShader",KO=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform mat4 view;varying vec4 vViewPos;
#endif
#include<pointCloudVertexDeclaration>
varying float vDepthMetric;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
gl_Position=viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vViewPos=view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
#else
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#include<pointCloudVertex>
}
`;W.ShadersStore[$O]=KO;class Yo{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=k.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=t===0,this.isPacked?this.clearColor=new xe(1,1,1,1):this.clearColor=new xe(n?1e8:1,0,0,1),Yo._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==k.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=k.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=k.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new oi(o??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=k.CLAMP_ADDRESSMODE,this._depthMap.wrapV=k.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(u=>{u.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var u;(u=l._debugPushGroup)==null||u.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)==null||u.call(l,1)}),this._depthMap.customIsReadyFunction=(u,d,f)=>{if((f||d===0)&&u.subMeshes)for(let _=0;_<u.subMeshes.length;++_){const p=u.subMeshes[_],g=p.getRenderingMesh(),x=g._getInstancesRenderList(p._id,!!p.getReplacementMesh()),T=l.getCaps().instancedArrays&&(x.visibleInstances[p._id]!==null&&x.visibleInstances[p._id]!==void 0||g.hasThinInstances);if(!this.isReady(p,T))return!1}return!0};const c=u=>{var A;const d=u.getRenderingMesh(),f=u.getEffectiveMesh(),_=this._scene,p=_.getEngine(),g=u.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!g||f.infiniteDistance||g.disableDepthWrite||u.verticesCount===0||u._renderId===_.getRenderId())return;const x=f._getWorldMatrixDeterminant()<0;let T=d.overrideMaterialSideOrientation??g.sideOrientation;x&&(T=T===0?1:0);const S=T===0;p.setState(g.backFaceCulling,0,!1,S,this.reverseCulling?!g.cullBackFaces:g.cullBackFaces);const C=d._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(C.mustReturn)return;const v=p.getCaps().instancedArrays&&(C.visibleInstances[u._id]!==null&&C.visibleInstances[u._id]!==void 0||d.hasThinInstances),b=this._camera||_.activeCamera;if(this.isReady(u,v)&&b){u._renderId=_.getRenderId();const P=(A=f._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:A[p.currentRenderPassId];let L=u._getDrawWrapper();!L&&P&&(L=P._getDrawWrapper());const w=b.mode===ve.ORTHOGRAPHIC_CAMERA;if(!L)return;const $=L.effect;p.enableEffect(L),v||d._bind(u,$,g.fillMode),P?P.bindForSubMesh(f.getWorldMatrix(),f,u):($.setMatrix("viewProjection",_.getTransformMatrix()),$.setMatrix("world",f.getWorldMatrix()),this._storeCameraSpaceZ&&$.setMatrix("view",_.getViewMatrix()));let J,ne;if(w?(J=!p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:1,ne=p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:1):(J=p.useReverseDepthBuffer&&p.isNDCHalfZRange?b.minZ:p.isNDCHalfZRange?0:b.minZ,ne=p.useReverseDepthBuffer&&p.isNDCHalfZRange?0:b.maxZ),$.setFloat2("depthValues",J,J+ne),!P){if(g.needAlphaTesting()){const oe=g.getAlphaTestTexture();oe&&($.setTexture("diffuseSampler",oe),$.setMatrix("diffuseMatrix",oe.getTextureMatrix()))}if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){const oe=d.skeleton;if(oe.isUsingTextureForMatrices){const re=oe.getTransformMatrixTexture(d);if(!re)return;$.setTexture("boneSampler",re),$.setFloat("boneTextureWidth",4*(oe.bones.length+1))}else $.setMatrices("mBones",oe.getTransformMatrices(d))}Gr($,g,_),Sa(d,$),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind($),g.pointsCloud&&$.setFloat("pointSize",g.pointSize)}d._processRendering(f,u,$,g.fillMode,C,v,(oe,re)=>$.setMatrix("world",re))}};this._depthMap.customRenderFunction=(u,d,f,_)=>{let p;if(_.length)for(p=0;p<_.length;p++)c(_.data[p]);for(p=0;p<u.length;p++)c(u.data[p]);for(p=0;p<d.length;p++)c(d.data[p]);if(this.forceDepthWriteTransparentMeshes)for(p=0;p<f.length;p++)c(f.data[p]);else for(p=0;p<f.length;p++)f.data[p].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}isReady(e,t){var p;const i=this._scene.getEngine(),s=e.getMesh(),r=s.getScene(),n=(p=s._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:p[i.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);const o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;const l=[],h=[y.PositionKind];if(o&&o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),s.isVerticesDataPresent(y.UVKind)&&(h.push(y.UVKind),l.push("#define UV1")),s.isVerticesDataPresent(y.UV2Kind)&&(h.push(y.UV2Kind),l.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders){h.push(y.MatricesIndicesKind),h.push(y.MatricesWeightsKind),s.numBoneInfluencers>4&&(h.push(y.MatricesIndicesExtraKind),h.push(y.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const g=e.getRenderingMesh().skeleton;g!=null&&g.isUsingTextureForMatrices&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),$u(h,s,u))),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),oo(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),no(o,r,l);const d=e._getDrawWrapper(void 0,!0),f=d.defines,_=l.join(`
`);if(f!==_){const g=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];sn(g),d.setEffect(i.createEffect("depth",h,g,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Yo._SceneComponentInitialization=a=>{throw Ge("DepthRendererSceneComponent")};const jO="minmaxReduxPixelShader",qO=`varying vec2 vUV;uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);
#ifdef DEPTH_REDUX
float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#else
float maxz=max(max(max(f1,f2),f3),f4);
#endif
glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform ivec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
void main(void)
{glFragColor=vec4(0.);if (true) { 
discard;}}
#endif
`;W.ShadersStore[jO]=qO;class QO{constructor(e){this.onAfterReductionPerformed=new G,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new qd(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new De("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?`
#define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();n.onApply=((c,u)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",c,u)})(o,l),this._reductionSteps.push(n);let h=1;for(;o>1||l>1;){o=Math.max(Math.round(o/2),1),l=Math.max(Math.round(l/2),1);const c=new De("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:o,height:l},null,1,r.getEngine(),!1,"#define "+(o==1&&l==1?"LAST":o==1||l==1?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(c.autoClear=!1,c.forceFullscreenViewport=s,c.onApply=((u,d)=>f=>{u==1||d==1?f.setInt2("texSize",u,d):f.setFloat2("texSize",u,d)})(o,l),this._reductionSteps.push(c),h++,o==1&&l==1){const u=(d,f,_)=>{const p=new Float32Array(4*d*f),g={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(_.inputTexture.texture,d,f,-1,0,p,!1),g.min=p[0],g.max=p[1],this.onAfterReductionPerformed.notifyObservers(g)}};c.onAfterRenderObservable.add(u(o,l,c))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;const e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e,1)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let t=0;t<this._reductionSteps.length;++t)this._reductionSteps[t].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null}}class ZO extends QO{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){const s=this._camera.getScene();this._depthRenderer&&(delete s._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(s._depthRenderer||(s._depthRenderer={}),e=this._depthRenderer=new Yo(s,t,this._camera,!1,1),e.enabled=!1,this._depthRendererId="minmax"+this._camera.id,s._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,s=!0){super.setSourceTexture(e,t,i,s)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){if(super.dispose(e),this._depthRenderer&&e){const t=this._depthRenderer.getDepthMap().getScene();t&&delete t._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}}}const pT=m.Up(),JO=m.Zero(),Yi=new m,cl=new m,Nd=new D;class ps extends ze{_validateFilter(e){return e===ze.FILTER_NONE||e===ze.FILTER_PCF||e===ze.FILTER_PCSS?e:(O.Error('Unsupported filter "'+e+'"!'),ze.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,ps.MIN_CASCADES_COUNT),ps.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let i=0;i<e.length;i++){const s=e[i];if(!s)continue;const r=s.getBoundingInfo(),n=r.boundingBox;this._scbiMin.minimizeInPlace(n.minimumWorld),this._scbiMax.maximizeInPlace(n.maximumWorld)}const t=this._scene.meshes;for(let i=0;i<t.length;i++){const s=t[i];if(!s||!s.isVisible||!s.isEnabled||!s.receiveShadows)continue;const r=s.getBoundingInfo(),n=r.boundingBox;this._scbiMin.minimizeInPlace(n.minimumWorld),this._scbiMax.maximizeInPlace(n.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return ps.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){const t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){const t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new ZO(t),this._depthReducer.onAfterReductionPerformed.add(i=>{let s=i.min,r=i.max;s>=r&&(s=0,r=1),(s!=this._minDistance||r!=this._maxDistance)&&this.setMinMaxDistance(s,r)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t;return((t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)??-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+r*s,l=t+n*s,h=l-o,c=l/o;for(let u=0;u<this._cascades.length;++u){const d=(u+1)/this._numCascades,f=o*c**d,_=o+h*d,p=this._lambda*(f-_)+_;this._cascades[u].prevBreakDistance=u===0?r:this._cascades[u-1].breakDistance,this._cascades[u].breakDistance=(p-t)/s,this._viewSpaceFrustumsZ[u]=p,this._frustumLengths[u]=(this._cascades[u].breakDistance-this._cascades[u].prevBreakDistance)*s}this._breaksAreDirty=!1}_computeMatrices(){const e=this._scene;if(!this._getCamera())return;m.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),Math.abs(m.Dot(this._lightDirection,m.Up()))===1&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);const i=e.getEngine().useReverseDepthBuffer;for(let s=0;s<this._numCascades;++s){this._computeFrustumInWorldSpace(s),this._computeCascadeFrustum(s),this._cascadeMaxExtents[s].subtractToRef(this._cascadeMinExtents[s],Yi),this._frustumCenter[s].addToRef(this._lightDirection.scale(this._cascadeMinExtents[s].z),this._shadowCameraPos[s]),D.LookAtLHToRef(this._shadowCameraPos[s],this._frustumCenter[s],pT,this._viewMatrices[s]);let r=0,n=Yi.z;const o=this._shadowCastersBoundingInfo;o.update(this._viewMatrices[s]),n=Math.min(n,o.boundingBox.maximumWorld.z),!this._depthClamp||this.filter===ze.FILTER_PCSS?r=Math.min(r,o.boundingBox.minimumWorld.z):r=Math.max(r,o.boundingBox.minimumWorld.z),D.OrthoOffCenterLHToRef(this._cascadeMinExtents[s].x,this._cascadeMaxExtents[s].x,this._cascadeMinExtents[s].y,this._cascadeMaxExtents[s].y,i?n:r,i?r:n,this._projectionMatrices[s],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[s].z=r,this._cascadeMaxExtents[s].z=n,this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),m.TransformCoordinatesToRef(JO,this._transformMatrices[s],Yi),Yi.scaleInPlace(this._mapSize/2),cl.copyFromFloats(Math.round(Yi.x),Math.round(Yi.y),Math.round(Yi.z)),cl.subtractInPlace(Yi).scaleInPlace(2/this._mapSize),D.TranslationToRef(cl.x,cl.y,0,Nd),this._projectionMatrices[s].multiplyToRef(Nd,this._projectionMatrices[s]),this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),this._transformMatrices[s].copyToArray(this._transformMatricesAsArray,s*16)}}_computeFrustumInWorldSpace(e){const t=this._getCamera();if(!t)return;const i=this._cascades[e].prevBreakDistance,s=this._cascades[e].breakDistance,r=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();const n=t.maxZ===0,o=t.maxZ;n&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));const l=D.Invert(t.getTransformationMatrix());n&&(t.maxZ=o,t.getProjectionMatrix(!0));const h=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let c=0;c<ps._FrustumCornersNDCSpace.length;++c)Yi.copyFrom(ps._FrustumCornersNDCSpace[(c+h)%ps._FrustumCornersNDCSpace.length]),r&&Yi.z===-1&&(Yi.z=0),m.TransformCoordinatesToRef(Yi,l,this._frustumCornersWorldSpace[e][c]);for(let c=0;c<ps._FrustumCornersNDCSpace.length/2;++c)Yi.copyFrom(this._frustumCornersWorldSpace[e][c+4]).subtractInPlace(this._frustumCornersWorldSpace[e][c]),cl.copyFrom(Yi).scaleInPlace(i),Yi.scaleInPlace(s),Yi.addInPlace(this._frustumCornersWorldSpace[e][c]),this._frustumCornersWorldSpace[e][c+4].copyFrom(Yi),this._frustumCornersWorldSpace[e][c].addInPlace(cl)}_computeCascadeFrustum(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),!!this._getCamera()){for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][i]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let i=0;for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s){const r=this._frustumCornersWorldSpace[e][s].subtractToRef(this._frustumCenter[e],Yi).length();i=Math.max(i,r)}i=Math.ceil(i*16)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{const i=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,Yi),D.LookAtLHToRef(i,Yi,pT,Nd);for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s)m.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][s],Nd,Yi),this._cascadeMinExtents[e].minimizeInPlace(Yi),this._cascadeMaxExtents[e].maximizeInPlace(Yi)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){const e=Ae.LastCreatedEngine;return e?e._features.supportCSM:!1}constructor(e,t,i,s,r=!0){if(!ps.IsSupported){O.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,s,r),this.usePercentageCloserFiltering=!0}_initializeGenerator(){var e;this.penumbraDarkness=this.penumbraDarkness??1,this._numCascades=this._numCascades??ps.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=this.stabilizeCascades??!1,this._freezeShadowCastersBoundingInfoObservable=this._freezeShadowCastersBoundingInfoObservable??null,this.freezeShadowCastersBoundingInfo=this.freezeShadowCastersBoundingInfo??!1,this._scbiMin=this._scbiMin??new m(0,0,0),this._scbiMax=this._scbiMax??new m(0,0,0),this._shadowCastersBoundingInfo=this._shadowCastersBoundingInfo??new or(new m(0,0,0),new m(0,0,0)),this._breaksAreDirty=this._breaksAreDirty??!0,this._minDistance=this._minDistance??0,this._maxDistance=this._maxDistance??1,this._currentLayer=this._currentLayer??0,this._shadowMaxZ=this._shadowMaxZ??((e=this._getCamera())==null?void 0:e.maxZ)??1e4,this._debug=this._debug??!1,this._depthClamp=this._depthClamp??!0,this._cascadeBlendPercentage=this._cascadeBlendPercentage??.1,this._lambda=this._lambda??.5,this._autoCalcDepthBounds=this._autoCalcDepthBounds??!1,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){const e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new oi(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),this._shadowMap===null)return;this._transformMatricesAsArray=new Float32Array(this._numCascades*16),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(this._numCascades*2),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let t=0;t<this._numCascades;++t){this._cascades[t]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[t]=D.Zero(),this._projectionMatrices[t]=D.Zero(),this._transformMatrices[t]=D.Zero(),this._cascadeMinExtents[t]=new m,this._cascadeMaxExtents[t]=new m,this._frustumCenter[t]=new m,this._shadowCameraPos[t]=new m,this._frustumCornersWorldSpace[t]=new Array(ps._FrustumCornersNDCSpace.length);for(let i=0;i<ps._FrustumCornersNDCSpace.length;++i)this._frustumCornersWorldSpace[t][i]=new m}const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===ze.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(t=e._debugPushGroup)==null||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==ze.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();if(!n)return;const o=n.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===ze.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===ze.FILTER_PCSS){for(let l=0;l<this._numCascades;++l)this._lightSizeUVCorrection[l*2+0]=l===0?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[l].x-this._cascadeMinExtents[l].x),this._lightSizeUVCorrection[l*2+1]=l===0?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[l].y-this._cascadeMinExtents[l].y),this._depthCorrection[l]=l===0?1:(this._cascadeMaxExtents[l].z-this._cascadeMinExtents[l].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,n),t.setTexture("depthSampler"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/o,this._contactHardeningLightSizeUVRatio*o,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){const e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){const s=t.renderList[i];e.renderList.push(s.id)}return e}static Parse(e,t){const i=ze.Parse(e,t,(s,r,n)=>new ps(s,r,void 0,n));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}ps._FrustumCornersNDCSpace=[new m(-1,1,-1),new m(1,1,-1),new m(1,-1,-1),new m(-1,-1,-1),new m(-1,1,1),new m(1,1,1),new m(1,-1,1),new m(-1,-1,1)];ps.CLASSNAME="CascadedShadowGenerator";ps.DEFAULT_CASCADES_COUNT=4;ps.MIN_CASCADES_COUNT=2;ps.MAX_CASCADES_COUNT=4;ps._SceneComponentInitialization=a=>{throw Ge("ShadowGeneratorSceneComponent")};wi.AddParser(he.NAME_SHADOWGENERATOR,(a,e)=>{if(a.shadowGenerators!==void 0&&a.shadowGenerators!==null)for(let t=0,i=a.shadowGenerators.length;t<i;t++){const s=a.shadowGenerators[t];s.className===ps.CLASSNAME?ps.Parse(s,e):ze.Parse(s,e)}});class eN{constructor(e){this.name=he.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(he.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];const t=this.scene.lights;for(const i of t){const s=i.getShadowGenerators();if(s){const r=s.values();for(let n=r.next();n.done!==!0;n=r.next()){const o=n.value;e.shadowGenerators.push(o.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){const t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){const s=t.lights[i],r=s.getShadowGenerators();if(s.isEnabled()&&s.shadowEnabled&&r){const n=r.values();for(let o=n.next();o.done!==!0;o=n.next()){const h=o.value.getShadowMap();t.textures.indexOf(h)!==-1&&e.push(h)}}}}}ze._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_SHADOWGENERATOR);e||(e=new eN(a),a._addComponent(e))};Ct.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new Pc(a,m.Zero(),e));class Pc extends Xo{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 st.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new m(1,0,0);case 1:return new m(-1,0,0);case 2:return new m(0,-1,0);case 3:return new m(0,1,0);case 4:return new m(0,0,1);case 5:return new m(0,0,-1)}return m.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,o=this.getScene().getEngine().useReverseDepthBuffer;D.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}E([I()],Pc.prototype,"shadowAngle",null);class Ua{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const s=this._renderingCanvas.getBoundingClientRect(),r=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position=r==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=s.left+"px",this._loadingDiv.style.top=s.top+"px",this._loadingDiv.style.width=s.width+"px",this._loadingDiv.style.height=s.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";const e=`@-webkit-keyframes spin1 {                    0% { -webkit-transform: rotate(0deg);}
                    100% { -webkit-transform: rotate(360deg);}
                }                @keyframes spin1 {                    0% { transform: rotate(0deg);}
                    100% { transform: rotate(360deg);}
                }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);const t=!!window.SVGSVGElement,i=new Image;Ua.DefaultLogoUrl?i.src=Ua.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=document.createElement("div");s.style.width="300px",s.style.gridColumn="1",s.style.gridRow="1",s.style.top="50%",s.style.left="50%",s.style.transform="translate(-50%, -50%)",s.style.position="absolute";const r=new Image;if(Ua.DefaultSpinnerUrl?r.src=Ua.DefaultSpinnerUrl:r.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",r.style.animation="spin1 0.75s infinite linear",r.style.webkitAnimation="spin1 0.75s infinite linear",r.style.transformOrigin="50% 50%",r.style.webkitTransformOrigin="50% 50%",!t){const n={w:16,h:18.5},o={w:30,h:30};i.style.width=`${n.w}vh`,i.style.height=`${n.h}vh`,i.style.left=`calc(50% - ${n.w/2}vh)`,i.style.top=`calc(50% - ${n.h/2}vh)`,r.style.width=`${o.w}vh`,r.style.height=`${o.h}vh`,r.style.left=`calc(50% - ${o.w/2}vh)`,r.style.top=`calc(50% - ${o.h/2}vh)`}s.appendChild(r),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(s),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){if(!this._loadingDiv)return;const e=()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",e)}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}Ua.DefaultLogoUrl="";Ua.DefaultSpinnerUrl="";H.DefaultLoadingScreenFactory=a=>new Ua(a);class co{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";const n=this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),o=this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),l=this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),h=this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),c=this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),u=this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r);return{front:n,back:o,left:l,right:h,up:c,down:u,size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),l=new Float32Array(o),h=n?Math.max(1,Math.round(s/4/e)):1,c=1/h,u=c*c,d=t[1].subtract(t[0]).scale(c/e),f=t[3].subtract(t[2]).scale(c/e),_=1/e;let p=0;for(let g=0;g<e;g++)for(let x=0;x<h;x++){let T=t[0],S=t[2];for(let C=0;C<e;C++)for(let v=0;v<h;v++){const b=S.subtract(T).scale(p).add(T);b.normalize();const A=this.CalcProjectionSpherical(b,i,s,r);l[g*e*3+C*3+0]+=A.r*u,l[g*e*3+C*3+1]+=A.g*u,l[g*e*3+C*3+2]+=A.b*u,T=T.add(d),S=S.add(f)}p+=_*c}return l}static CalcProjectionSpherical(e,t,i,s){let r=Math.atan2(e.z,e.x);const n=Math.acos(e.y);for(;r<-Math.PI;)r+=2*Math.PI;for(;r>Math.PI;)r-=2*Math.PI;let o=r/Math.PI;const l=n/Math.PI;o=o*.5+.5;let h=Math.round(o*i);h<0?h=0:h>=i&&(h=i-1);let c=Math.round(l*s);c<0?c=0:c>=s&&(c=s-1);const u=s-c-1,d=t[u*i*3+h*3+0],f=t[u*i*3+h*3+1],_=t[u*i*3+h*3+2];return{r:d,g:f,b:_}}}co.FACE_LEFT=[new m(-1,-1,-1),new m(1,-1,-1),new m(-1,1,-1),new m(1,1,-1)];co.FACE_RIGHT=[new m(1,-1,1),new m(-1,-1,1),new m(1,1,1),new m(-1,1,1)];co.FACE_FRONT=[new m(1,-1,-1),new m(1,-1,1),new m(1,1,-1),new m(1,1,1)];co.FACE_BACK=[new m(-1,-1,1),new m(-1,-1,-1),new m(-1,1,1),new m(-1,1,-1)];co.FACE_DOWN=[new m(1,1,-1),new m(1,1,1),new m(-1,1,-1),new m(-1,1,1)];co.FACE_UP=[new m(-1,-1,-1),new m(-1,-1,1),new m(1,-1,-1),new m(1,-1,1)];class _p{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-(128+8)),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r<e.length-t&&(s=String.fromCharCode(e[r]),s!=`
`);r++)i+=s;return i}static RGBE_ReadHeader(e){let t=0,i=0,s=this._ReadStringLine(e,0);if(s[0]!="#"||s[1]!="?")throw"Bad HDR Format.";let r=!1,n=!1,o=0;do o+=s.length+1,s=this._ReadStringLine(e,o),s=="FORMAT=32-bit_rle_rgbe"?n=!0:s.length==0&&(r=!0);while(!r);if(!n)throw"HDR Bad header format, unsupported FORMAT";o+=s.length+1,s=this._ReadStringLine(e,o);const h=/^-Y (.*) \+X (.*)$/g.exec(s);if(!h||h.length<3)throw"HDR Bad header format, no size";if(i=parseInt(h[2]),t=parseInt(h[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return co.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,l,h,c=t.dataPosition,u=0,d=0,f=0;const _=new ArrayBuffer(s*4),p=new Uint8Array(_),g=new ArrayBuffer(t.width*t.height*4*3),x=new Float32Array(g);for(;i>0;){if(r=e[c++],n=e[c++],o=e[c++],l=e[c++],r!=2||n!=2||o&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|l)!=s)throw"HDR Bad header format, wrong scan line width";for(u=0,f=0;f<4;f++)for(d=(f+1)*s;u<d;)if(r=e[c++],n=e[c++],r>128){if(h=r-128,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (run)";for(;h-- >0;)p[u++]=n}else{if(h=r,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (non-run)";if(p[u++]=n,--h>0)for(let T=0;T<h;T++)p[u++]=e[c++]}for(f=0;f<s;f++)r=p[f],n=p[f+s],o=p[f+2*s],l=p[f+3*s],this._Rgbe2float(x,r,n,o,l,(t.height-i)*s*3+f*3);i--}return x}static _RGBEReadPixelsNOTRLE(e,t){let i=t.height;const s=t.width;let r,n,o,l,h,c=t.dataPosition;const u=new ArrayBuffer(t.width*t.height*4*3),d=new Float32Array(u);for(;i>0;){for(h=0;h<t.width;h++)r=e[c++],n=e[c++],o=e[c++],l=e[c++],this._Rgbe2float(d,r,n,o,l,(t.height-i)*s*3+h*3);i--}return d}}const tN="hdrFilteringVertexShader",iN=`attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[tN]=iN;const sN="hdrFilteringPixelShader",rN=`#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;W.ShadersStore[sN]=rN;class OS{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);const i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){const t=e.getSize().width,i=ge.ILog2(t)+1,s=this._effectWrapper.effect,r=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();const n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new m(0,0,-1),new m(0,-1,0),new m(1,0,0)],[new m(0,0,1),new m(0,-1,0),new m(-1,0,0)],[new m(1,0,0),new m(0,0,1),new m(0,1,0)],[new m(1,0,0),new m(0,0,-1),new m(0,-1,0)],[new m(1,0,0),new m(0,-1,0),new m(0,0,1)],[new m(-1,0,0),new m(0,-1,0),new m(0,0,-1)]];s.setFloat("hdrScale",this.hdrScale),s.setFloat2("vFilteringInfo",e.getSize().width,i),s.setTexture("inputTexture",e);for(let c=0;c<6;c++){s.setVector3("up",o[c][0]),s.setVector3("right",o[c][1]),s.setVector3("front",o[c][2]);for(let u=0;u<i;u++){this._engine.bindFramebuffer(r,c,void 0,void 0,!0,u),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let d=Math.pow(2,(u-this._lodGenerationOffset)/this._lodGenerationScale)/t;u===0&&(d=0),s.setFloat("alphaG",d),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);const l=r.texture.type,h=r.texture.format;return r._swapAndDie(e._texture),e._texture.type=l,e._texture.format=h,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e}_createEffect(e,t){const i=[];return e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u"),new da({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t})}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise(i=>{this._effectRenderer=new Nf(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(O.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class No extends Et{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(D.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,l=null,h=null,c=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=m.Zero(),this.onLoadObservable=new G,e&&(this._coordinatesMode=k.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=D.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=h,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=c,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?X.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(u=this.getScene())!=null&&u.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2);const s=r=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const n=_p.GetCubeMapTextureData(r,this._size,this._supersample);if(this._generateHarmonics){const c=yc.ConvertCubeMapToSphericalPolynomial(n);this.sphericalPolynomial=c}const o=[];let l=null,h=null;for(let c=0;c<6;c++){i===2?h=new Uint16Array(this._size*this._size*3):i===0&&(l=new Uint8Array(this._size*this._size*3));const u=n[No._FacesMapping[c]];if(this.gammaSpace||h||l){for(let d=0;d<this._size*this._size;d++)if(this.gammaSpace&&(u[d*3+0]=Math.pow(u[d*3+0],Kc),u[d*3+1]=Math.pow(u[d*3+1],Kc),u[d*3+2]=Math.pow(u[d*3+2],Kc)),h&&(h[d*3+0]=Ln(u[d*3+0]),h[d*3+1]=Ln(u[d*3+1]),h[d*3+2]=Ln(u[d*3+2])),l){let f=Math.max(u[d*3+0]*255,0),_=Math.max(u[d*3+1]*255,0),p=Math.max(u[d*3+2]*255,0);const g=Math.max(Math.max(f,_),p);if(g>255){const x=255/g;f*=x,_*=x,p*=x}l[d*3+0]=f,l[d*3+1]=_,l[d*3+2]=p}}h?o.push(h):l?o.push(l):o.push(u)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const r=this._onLoad,n=new OS(e);this._onLoad=()=>{n.prefilter(this,r)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,s,null,this._onLoad,this._onError)}clone(){const e=new No(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&((t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.getActiveTextures().indexOf(this)!==-1))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new No(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=m.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=m.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}No._FacesMapping=["right","left","up","down","front","back"];V("BABYLON.HDRCubeTexture",No);class Fo{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new G,this._onDataLayoutChanged=new G,this._animationPropertiesOverride=null,this._scene=i||Ae.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=_e.Clone(()=>new Fo(this.name,this.influence,this._scene),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),this.id!=null&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),_e.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Fo(e.name,e.influence);if(i.setPositions(e.positions),e.id!=null&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let s=0;s<e.animations.length;s++){const r=e.animations[s],n=Si("BABYLON.Animation");n&&i.animations.push(n.Parse(r))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);const s=new Fo(t,i,e.getScene());return s.setPositions(e.getVerticesData(y.PositionKind)),e.isVerticesDataPresent(y.NormalKind)&&s.setNormals(e.getVerticesData(y.NormalKind)),e.isVerticesDataPresent(y.TangentKind)&&s.setTangents(e.getVerticesData(y.TangentKind)),e.isVerticesDataPresent(y.UVKind)&&s.setUVs(e.getVerticesData(y.UVKind)),s}}E([I()],Fo.prototype,"id",void 0);class fg extends k{get depth(){return this._depth}constructor(e,t,i,s,r,n,o=!0,l=!1,h=k.TRILINEAR_SAMPLINGMODE,c=0,u){super(null,n,!o,l),this.format=r,this._texture=n.getEngine().createRawTexture2DArray(e,t,i,s,r,o,l,h,null,c,u),this._depth=s,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,s,r,n=!0,o=!1,l=3,h=0){return new fg(e,t,i,s,5,r,n,o,l,h)}}class zn{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Wi(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=Ae.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const t=this._scene.getEngine().getCaps();this._canUseTextureForTargets=t.canUseGLVertexID&&t.textureFloat&&t.maxVertexTextureImageUnits>0&&t.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){var e;return zn.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this._syncActiveTargets(t)})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._syncActiveTargets(!0)})),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new zn(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const s of this._targets){if(i++,s.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=zn.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(s),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=s.influence,this._supportsNormals=this._supportsNormals&&s.hasNormals,this._supportsTangents=this._supportsTangents&&s.hasTangents,this._supportsUVs=this._supportsUVs&&s.hasUVs;const r=s.getPositions();if(r){const n=r.length/3;if(this._vertexCount===0)this._vertexCount=n;else if(this._vertexCount!==n){O.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),(!this._influences||this._influences.length!==t)&&(this._influences=new Float32Array(t));for(let s=0;s<t;s++)this._influences[s]=this._tempInfluences[s];e&&this.synchronize()}synchronize(){if(!(!this._scene||this.areUpdatesFrozen)){if(this.isUsingTextureForTargets&&(this._vertexCount||this.numMaxInfluencers>0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const i=this._targetStoreTexture.getSize();i.width===this._textureWidth&&i.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const i=this._targets.length,s=new Float32Array(i*this._textureWidth*this._textureHeight*4);let r=0;for(let n=0;n<i;n++){const o=this._targets[n],l=o.getPositions(),h=o.getNormals(),c=o.getUVs(),u=o.getTangents();if(!l){n===0&&O.Error("Invalid morph target. Target must have positions.");return}r=n*this._textureWidth*this._textureHeight*4;for(let d=0;d<this._vertexCount;d++)s[r]=l[d*3],s[r+1]=l[d*3+1],s[r+2]=l[d*3+2],r+=4,this._supportsNormals&&h&&(s[r]=h[d*3],s[r+1]=h[d*3+1],s[r+2]=h[d*3+2],r+=4),this._supportsUVs&&c&&(s[r]=c[d*2],s[r+1]=c[d*2+1],r+=4),this._supportsTangents&&u&&(s[r]=u[d*3],s[r+1]=u[d*3+1],s[r+2]=u[d*3+2],r+=4)}this._targetStoreTexture=fg.CreateRGBATexture(s,this._textureWidth,this._textureHeight,i,this._scene,!1,!1,1,1)}}for(const e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){const e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new zn(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(Fo.Parse(s,t));return i}}zn.EnableTextureStorage=!0;zn.MaxActiveMorphTargetsInVertexAttributeMode=8;class nN{constructor(){this._hasHit=!1,this._hitNormal=m.Zero(),this._hitPoint=m.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class t_ extends nN{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=m.Zero(),this._rayToWorld=m.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=m.Distance(this._rayFromWorld,this._hitPoint)}reset(e=m.Zero(),t=m.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}let NS=class FS{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ge("CannonJSPlugin")}constructor(e,t=FS.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new m(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach(t=>{t.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(t)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null}getImpostorWithPhysicsBody(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null}raycast(e,t){return this._physicsPlugin.raycast(e,t)}raycastToRef(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)}};class pp{constructor(e=!0,t=10,i=CANNON){if(this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=new Array,this._firstFrame=!0,this._tmpQuaternion=new Q,this._minus90X=new Q(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new Q(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=m.Zero(),this._tmpDeltaPosition=m.Zero(),this._tmpUnityRotation=new Q,this.BJSCANNON=i,!this.isSupported()){O.Error("CannonJS is not available. Please make sure you included the js file.");return}this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new t_}getPluginVersion(){return 1}setGravity(e){const t=e;this.world.gravity.set(t.x,t.y,t.z)}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){if(this._firstFrame){this._firstFrame=!1;for(const i of t)i.type==We.HeightmapImpostor||i.type===We.PlaneImpostor||i.beforeStep()}this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()}_removeMarkedPhysicsBodiesFromWorld(){this._physicsBodiesToRemoveAfterStep.length>0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{typeof this.world.removeBody=="function"?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t){O.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),typeof this.world.addBody=="function"?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(o){const l=i[o];e.physicsBody[o].set(l.x,l.y,l.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const s=r=>{if(!r.rotationQuaternion)return;const n=r.getPhysicsImpostor();if(n&&n.parent!==e&&r.parent){const l=r.getAbsolutePosition().subtract(r.parent.getAbsolutePosition()),h=r.rotationQuaternion.multiply(this._tmpQuaternion);n.physicsBody&&(this.removePhysicsBody(n),n.physicsBody=null),n.parent=e,n.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(n),new this.BJSCANNON.Vec3(l.x,l.y,l.z),new this.BJSCANNON.Quaternion(h.x,h.y,h.z,h.w)),e.physicsBody.mass+=n.getParam("mass")}r.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(s)};t.filter(r=>!!r.physicsImpostor).forEach(s)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)===-1&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?new this.BJSCANNON.Vec3().set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?new this.BJSCANNON.Vec3().set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?new this.BJSCANNON.Vec3().set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?new this.BJSCANNON.Vec3().set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case Qt.HingeJoint:case Qt.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case Qt.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case Qt.SpringJoint:{const o=r;s=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case Qt.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case Qt.PointToPointJoint:case Qt.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce);break}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==Qt.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==Qt.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s<this._physicsMaterials.length;s++)if(r=this._physicsMaterials[s],r.friction===t&&r.restitution===i)return r;const n=new this.BJSCANNON.Material(e);return n.friction=t,n.restitution=i,this._physicsMaterials.push(n),n}_checkWithEpsilon(e){return e<rt?rt:e}_createShape(e){const t=e.object;let i;const s=e.getObjectExtents();switch(e.type){case We.SphereImpostor:{const r=s.x,n=s.y,o=s.z;i=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(r),this._checkWithEpsilon(n),this._checkWithEpsilon(o))/2);break}case We.CylinderImpostor:{let r=e.getParam("nativeOptions");r||(r={});const n=r.radiusTop!==void 0?r.radiusTop:this._checkWithEpsilon(s.x)/2,o=r.radiusBottom!==void 0?r.radiusBottom:this._checkWithEpsilon(s.x)/2,l=r.height!==void 0?r.height:this._checkWithEpsilon(s.y),h=r.numSegments!==void 0?r.numSegments:16;i=new this.BJSCANNON.Cylinder(n,o,l,h);const c=new this.BJSCANNON.Quaternion;c.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);const u=new this.BJSCANNON.Vec3(0,0,0);i.transformAllPoints(u,c);break}case We.BoxImpostor:{const r=s.scale(.5);i=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(r.x),this._checkWithEpsilon(r.y),this._checkWithEpsilon(r.z)));break}case We.PlaneImpostor:O.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),i=new this.BJSCANNON.Plane;break;case We.MeshImpostor:{const r=t.getVerticesData?t.getVerticesData(y.PositionKind):[],n=t.getIndices?t.getIndices():[];if(!r){O.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");return}const o=t.position.clone(),l=t.rotation&&t.rotation.clone(),h=t.rotationQuaternion&&t.rotationQuaternion.clone();t.position.copyFromFloats(0,0,0),t.rotation&&t.rotation.copyFromFloats(0,0,0),t.rotationQuaternion&&t.rotationQuaternion.copyFrom(e.getParentsRotation()),t.rotationQuaternion&&t.parent&&t.rotationQuaternion.conjugateInPlace();const c=t.computeWorldMatrix(!0),u=[];let d;for(d=0;d<r.length;d+=3)m.TransformCoordinates(m.FromArray(r,d),c).toArray(u,d);O.Warn("MeshImpostor only collides against spheres."),i=new this.BJSCANNON.Trimesh(u,n),t.position.copyFrom(o),l&&t.rotation&&t.rotation.copyFrom(l),h&&t.rotationQuaternion&&t.rotationQuaternion.copyFrom(h);break}case We.HeightmapImpostor:{const r=t.position.clone(),n=t.rotation&&t.rotation.clone(),o=t.rotationQuaternion&&t.rotationQuaternion.clone();t.position.copyFromFloats(0,0,0),t.rotation&&t.rotation.copyFromFloats(0,0,0),t.rotationQuaternion&&t.rotationQuaternion.copyFrom(e.getParentsRotation()),t.rotationQuaternion&&t.parent&&t.rotationQuaternion.conjugateInPlace(),t.rotationQuaternion&&t.rotationQuaternion.multiplyInPlace(this._minus90X),i=this._createHeightmap(t),t.position.copyFrom(r),n&&t.rotation&&t.rotation.copyFrom(n),o&&t.rotationQuaternion&&t.rotationQuaternion.copyFrom(o),t.computeWorldMatrix(!0);break}case We.ParticleImpostor:i=new this.BJSCANNON.Particle;break;case We.NoImpostor:i=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0));break}return i}_createHeightmap(e,t){let i=e.getVerticesData(y.PositionKind);const s=e.computeWorldMatrix(!0),r=[];let n;for(n=0;n<i.length;n+=3)m.TransformCoordinates(m.FromArray(i,n),s).toArray(r,n);i=r;const o=new Array,l=t||~~(Math.sqrt(i.length/3)-1),h=e.getBoundingInfo(),c=Math.min(h.boundingBox.extendSizeWorld.x,h.boundingBox.extendSizeWorld.y),u=h.boundingBox.extendSizeWorld.z,d=c*2/l;for(let _=0;_<i.length;_=_+3){const p=Math.round(i[_+0]/d+l/2),g=Math.round((i[_+1]/d-l/2)*-1),x=-i[_+2]+u;o[p]||(o[p]=[]),o[p][g]||(o[p][g]=x),o[p][g]=Math.max(x,o[p][g])}for(let _=0;_<=l;++_){if(!o[_]){let p=1;for(;!o[(_+p)%l];)p++;o[_]=o[(_+p)%l].slice()}for(let p=0;p<=l;++p)if(!o[_][p]){let g=1,x;for(;x===void 0;)x=o[_][(p+g++)%l];o[_][p]=x}}const f=new this.BJSCANNON.Heightfield(o,{elementSize:d});return f.minY=u,f}_updatePhysicsBodyTransformation(e){const t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),!t.getBoundingInfo())return;const i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);let s=t.rotationQuaternion;if(s){if((e.type===We.PlaneImpostor||e.type===We.HeightmapImpostor)&&(s=s.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===We.HeightmapImpostor){const r=t;let n=r.getBoundingInfo();const o=r.rotationQuaternion;r.rotationQuaternion=this._tmpUnityRotation,r.computeWorldMatrix(!0);const l=i.clone();let h=r.getPivotMatrix();h?h=h.clone():h=D.Identity();const c=D.Translation(n.boundingBox.extendSizeWorld.x,0,-n.boundingBox.extendSizeWorld.z);r.setPreTransformMatrix(c),r.computeWorldMatrix(!0),n=r.getBoundingInfo();const u=n.boundingBox.centerWorld.subtract(i).subtract(r.position).negate();this._tmpPosition.copyFromFloats(u.x,u.y-n.boundingBox.extendSizeWorld.y,u.z),this._tmpDeltaPosition.copyFrom(n.boundingBox.centerWorld.subtract(l)),this._tmpDeltaPosition.y+=n.boundingBox.extendSizeWorld.y,r.rotationQuaternion=o,r.setPreTransformMatrix(h),r.computeWorldMatrix(!0)}else e.type===We.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(s.x,s.y,s.z,s.w)}}setTransformationFromPhysicsBody(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){const t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}setPhysicsBodyTransformation(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}isSupported(){return this.BJSCANNON!==void 0}setLinearVelocity(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.velocity;return t?new m(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new m(t.x,t.y,t.z):null}setBodyMass(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}getBodyMass(e){return e.physicsBody.mass}getBodyFriction(e){return e.physicsBody.material.friction}setBodyFriction(e,t){e.physicsBody.material.friction=t}getBodyRestitution(e){return e.physicsBody.material.restitution}setBodyRestitution(e,t){e.physicsBody.material.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.wakeUp()}updateDistanceJoint(e,t){e.physicsJoint.distance=t}setMotor(e,t,i,s){s||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}setLimit(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=t===void 0?-t:t}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}getRadius(e){return e.physicsBody.shapes[0].boundingSphereRadius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes[0];t.x=i.halfExtents.x*2,t.y=i.halfExtents.y*2,t.z=i.halfExtents.z*2}dispose(){}_extendNamespace(){const e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,s,r){if(r=r||10,s=s||0,s===0)this.internalStep(i),this.time+=i;else{let n=Math.floor((this.time+s)/i)-Math.floor(this.time/i);n=Math.min(n,r)||1;const o=performance.now();for(let d=0;d!==n&&(this.internalStep(i),!(performance.now()-o>i*1e3));d++);this.time+=s;const h=this.time%i/i,c=e,u=this.bodies;for(let d=0;d!==u.length;d++){const f=u[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,c),c.scale(h,c),f.position.vadd(c,f.interpolatedPosition)):(f.interpolatedPosition.set(f.position.x,f.position.y,f.position.z),f.interpolatedQuaternion.set(f.quaternion.x,f.quaternion.y,f.quaternion.z,f.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}NS.DefaultPluginFactory=()=>new pp;class mT{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=m.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new t_}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(s){s.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(s=>{s.afterStep(),this._tmpImpostorsArray[s.uniqueId]=s});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const s=this._tmpImpostorsArray[+i.body1.name],r=this._tmpImpostorsArray[+i.body2.name];if(!s||!r){i=i.next;continue}s.onCollide({body:r.physicsBody,point:null,distance:0,impulse:0,normal:null}),r.onCollide({body:s.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){O.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:e.getParam("mass")!==0,density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},i=[e];(o=>{o.getChildMeshes&&o.getChildMeshes().forEach(function(l){l.physicsImpostor&&i.push(l.physicsImpostor)})})(e.object);const r=o=>Math.max(o,rt),n=new Q;i.forEach(o=>{if(!o.object.rotationQuaternion)return;const l=o.object.rotationQuaternion;n.copyFrom(l),o.object.rotationQuaternion.set(0,0,0,1),o.object.computeWorldMatrix(!0);const h=n.toEulerAngles(),c=o.getObjectExtents(),u=57.29577951308232;if(o===e){const d=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(d,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(d.x),t.pos.push(d.y),t.pos.push(d.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const d=o.object.position.clone();t.posShape.push(d.x),t.posShape.push(d.y),t.posShape.push(d.z),t.rotShape.push(h.x*u,h.y*u,h.z*u)}switch(o.object.rotationQuaternion.copyFrom(n),o.type){case We.ParticleImpostor:O.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case We.SphereImpostor:{const d=c.x,f=c.y,_=c.z,p=Math.max(r(d),r(f),r(_))/2;t.type.push("sphere"),t.size.push(p),t.size.push(p),t.size.push(p);break}case We.CylinderImpostor:{const d=r(c.x)/2,f=r(c.y);t.type.push("cylinder"),t.size.push(d),t.size.push(f),t.size.push(f);break}case We.PlaneImpostor:case We.BoxImpostor:default:{const d=r(c.x),f=r(c.y),_=r(c.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(_);break}}o.object.rotationQuaternion=l}),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case Qt.BallAndSocketJoint:n="jointBall";break;case Qt.SpringJoint:{O.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=s;o.min=l.length||o.min,o.max=Math.max(o.min,o.max)}case Qt.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case Qt.PrismaticJoint:n="jointPrisme";break;case Qt.SliderJoint:n="jointSlide";break;case Qt.WheelJoint:n="jointWheel";break;case Qt.HingeJoint:default:n="jointHinge";break}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){O.Warn(t)}}isSupported(){return this.BJSOIMO!==void 0}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new m(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new m(t.x,t.y,t.z):null}setBodyMass(e,t){const i=t===0;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,i!==void 0&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){i!==void 0?O.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,i===void 0?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=i.halfWidth*2,t.y=i.halfHeight*2,t.z=i.halfDepth*2}dispose(){this.world.clear()}raycast(e,t){return O.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){O.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Wn{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new Q,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new m,this._tmpContactNormal=new m,this._tmpVec3=new m,this._tmpMatrix=new D,typeof t=="function"){O.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){O.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=s=>{s=this.bjsAMMO.wrapPointer(s,this.bjsAMMO.btManifoldPoint);const r=s.getPositionWorldOnA(),n=s.m_normalWorldOnB;this._tmpContactPoint.x=r.x(),this._tmpContactPoint.y=r.y(),this._tmpContactPoint.z=r.z(),this._tmpContactNormal.x=n.x(),this._tmpContactNormal.y=n.y(),this._tmpContactNormal.z=n.z(),this._tmpContactImpulse=s.getAppliedImpulse(),this._tmpContactDistance=s.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new t_,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(t==0)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--}executeStep(e,t){for(const i of t)i.soft||i.beforeStep();this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep);for(const i of t)if(i.soft?this._afterSoftStep(i):i.afterStep(),i._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(i))for(const s of i._onPhysicsCollideCallbacks)for(const r of s.otherImpostors)(i.physicsBody.isActive()||r.physicsBody.isActive())&&this._isImpostorPairInContact(i,r)&&(i.onCollide({body:r.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),r.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===We.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,l;const h=new Array;for(let d=0;d<i;d++)s=t.at(d),r=s.get_m_x(),n=r.x(),o=r.y(),l=r.z(),h.push(new m(n,o,l));const c=e.object,u=e.getParam("shape");e._isFromLine?e.object=qm("lines",{points:h,instance:c}):e.object=TS("ext",{shape:u,path:h,instance:c})}_softbodyOrClothStep(e){const t=e.type===We.ClothImpostor?1:-1,i=e.object;let s=i.getVerticesData(y.PositionKind);s||(s=[]);let r=i.getVerticesData(y.NormalKind);r||(r=[]);const n=s.length/3,o=e.physicsBody.get_m_nodes();let l,h,c,u,d,f,_,p;for(let x=0;x<n;x++){l=o.at(x),h=l.get_m_x(),c=h.x(),u=h.y(),d=h.z()*t;const T=l.get_m_n();f=T.x(),_=T.y(),p=T.z()*t,s[3*x]=c,s[3*x+1]=u,s[3*x+2]=d,r[3*x]=f,r[3*x+1]=_,r[3*x+2]=p}const g=new le;g.positions=s,g.normals=r,g.uvs=i.getVerticesData(y.UVKind),g.colors=i.getVerticesData(y.ColorKind),i&&i.getIndices&&(g.indices=i.getIndices()),g.applyToMesh(i)}applyImpulse(e,t,i){if(e.soft)O.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();const s=this._tmpAmmoVectorA,r=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),s.setValue(i.x,i.y,i.z),r.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(r,s)}}applyForce(e,t,i){if(e.soft)O.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();const s=this._tmpAmmoVectorA,r=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){const n=e.object.getWorldMatrix().getTranslation();s.setValue(i.x-n.x,i.y-n.y,i.z-n.z)}else s.setValue(i.x,i.y,i.z);r.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(r,s)}}generatePhysicsBody(e){if(e._pluginData.toDispose=[],e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){const t=this._createShape(e),i=e.getParam("mass");if(e._pluginData.mass=i,e.soft)t.get_m_cfg().set_collisions(17),t.get_m_cfg().set_kDP(e.getParam("damping")),this.bjsAMMO.castObject(t,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),t.setActivationState(Wn._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(t,1,-1),e.physicsBody=t,e._pluginData.toDispose.push(t),this.setBodyPressure(e,0),e.type===We.SoftbodyImpostor&&this.setBodyPressure(e,e.getParam("pressure")),this.setBodyStiffness(e,e.getParam("stiffness")),this.setBodyVelocityIterations(e,e.getParam("velocityIterations")),this.setBodyPositionIterations(e,e.getParam("positionIterations"));else{const s=new this.bjsAMMO.btVector3(0,0,0),r=new this.bjsAMMO.btTransform;e.object.computeWorldMatrix(!0),r.setIdentity(),i!==0&&t.calculateLocalInertia(i,s),this._tmpAmmoVectorA.setValue(e.object.position.x,e.object.position.y,e.object.position.z),this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x,e.object.rotationQuaternion.y,e.object.rotationQuaternion.z,e.object.rotationQuaternion.w),r.setOrigin(this._tmpAmmoVectorA),r.setRotation(this._tmpAmmoQuaternion);const n=new this.bjsAMMO.btDefaultMotionState(r),o=new this.bjsAMMO.btRigidBodyConstructionInfo(i,n,t,s),l=new this.bjsAMMO.btRigidBody(o);if(i===0&&(l.setCollisionFlags(l.getCollisionFlags()|Wn._KINEMATIC_FLAG),l.setActivationState(Wn._DISABLE_DEACTIVATION_FLAG)),e.type==We.NoImpostor&&!t.getChildShape&&l.setCollisionFlags(l.getCollisionFlags()|Wn._DISABLE_COLLISION_FLAG),e.type!==We.MeshImpostor&&e.type!==We.NoImpostor){const u=e.object.getBoundingInfo();this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(u.boundingBox.centerWorld),this._tmpVec3.x/=e.object.scaling.x,this._tmpVec3.y/=e.object.scaling.y,this._tmpVec3.z/=e.object.scaling.z,e.setDeltaPosition(this._tmpVec3)}const h=e.getParam("group"),c=e.getParam("mask");h&&c?this.world.addRigidBody(l,h,c):this.world.addRigidBody(l),e.physicsBody=l,e._pluginData.toDispose=e._pluginData.toDispose.concat([l,o,n,r,s,t])}this.setBodyRestitution(e,e.getParam("restitution")),this.setBodyFriction(e,e.getParam("friction"))}}removePhysicsBody(e){this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach(t=>{this.bjsAMMO.destroy(t)}),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData;s.mainPivot||(s.mainPivot=new m(0,0,0)),s.connectedPivot||(s.connectedPivot=new m(0,0,0));let r;switch(e.joint.type){case Qt.DistanceJoint:{const n=s.maxDistance;n&&(s.mainPivot=new m(0,-n/2,0),s.connectedPivot=new m(0,n/2,0)),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case Qt.HingeJoint:{s.mainAxis||(s.mainAxis=new m(0,0,0)),s.connectedAxis||(s.connectedAxis=new m(0,0,0));const n=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),o=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);r=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),n,o);break}case Qt.BallAndSocketJoint:r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:O.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(y.PositionKind);n||(n=[]);let o;if(t&&t!==i){let h;t.rotationQuaternion?h=t.rotationQuaternion:t.rotation?h=Q.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):h=Q.Identity(),D.Compose(m.One(),h,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else D.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const l=r.length/3;for(let h=0;h<l;h++){const c=[];for(let u=0;u<3;u++){let d=new m(n[r[h*3+u]*3+0],n[r[h*3+u]*3+1],n[r[h*3+u]*3+2]);d=m.TransformCoordinates(d,o);let f;u==0?f=this._tmpAmmoVectorA:u==1?f=this._tmpAmmoVectorB:f=this._tmpAmmoVectorC,f.setValue(d.x,d.y,d.z),c.push(f)}e.addTriangle(c[0],c[1],c[2]),s++}i.getChildMeshes().forEach(h=>{s+=this._addMeshVerts(e,t,h)})}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData(y.PositionKind);i||(i=[]);let s=t.getVerticesData(y.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let l=0;l<i.length;l+=3){let h=new m(i[l],i[l+1],i[l+2]),c=new m(s[l],s[l+1],s[l+2]);h=m.TransformCoordinates(h,t.getWorldMatrix()),c=m.TransformNormal(c,t.getWorldMatrix()),r.push(h.x,h.y,h.z),n.push(c.x,c.y,c.z)}const o=new le;return o.positions=r,o.normals=n,o.uvs=t.getVerticesData(y.UVKind),o.colors=t.getVerticesData(y.ColorKind),t&&t.getIndices&&(o.indices=t.getIndices()),o.applyToMesh(t),t.position=m.Zero(),t.rotationQuaternion=null,t.rotation=m.Zero(),t.computeWorldMatrix(!0),o}return le.ExtractFromMesh(t)}_createSoftbody(e){const t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);const s=this._softVertexData(e),r=s.positions,n=s.normals;if(r===null||n===null)return new this.bjsAMMO.btCompoundShape;{const o=[],l=[];for(let _=0;_<r.length;_+=3){const p=new m(r[_],r[_+1],r[_+2]),g=new m(n[_],n[_+1],n[_+2]);o.push(p.x,p.y,-p.z),l.push(g.x,g.y,-g.z)}const h=new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(),o,t.getIndices(),i.length/3,!0),c=r.length/3,u=h.get_m_nodes();let d,f;for(let _=0;_<c;_++)d=u.at(_),f=d.get_m_n(),f.setX(l[3*_]),f.setY(l[3*_+1]),f.setZ(l[3*_+2]);return h}}}_createCloth(e){const t=e.object;if(t&&t.getIndices){t.getIndices();const i=this._softVertexData(e),s=i.positions,r=i.normals;if(s===null||r===null)return new this.bjsAMMO.btCompoundShape;{const n=s.length,o=Math.sqrt(n/3);e.segments=o;const l=o-1;return this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*l],s[3*l+1],s[3*l+2]),this._tmpAmmoVectorD.setValue(s[n-3],s[n-2],s[n-1]),this._tmpAmmoVectorC.setValue(s[n-3-3*l],s[n-2-3*l],s[n-1-3*l]),new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,o,o,e.getParam("fixedPoints"),!0)}}}_createRope(e){let t,i;const s=this._softVertexData(e),r=s.positions,n=s.normals;if(r===null||n===null)return new this.bjsAMMO.btCompoundShape;s.applyToMesh(e.object,!0),e._isFromLine=!0;const o=n.map(d=>d*d),l=(d,f)=>d+f;if(o.reduce(l)===0)t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const d=e.getParam("path");if(e.getParam("shape")===null)return O.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=d.length,i=t-1,this._tmpAmmoVectorA.setValue(d[0].x,d[0].y,d[0].z),this._tmpAmmoVectorB.setValue(d[t-1].x,d[t-1].y,d[t-1].z)}e.segments=i;let c=e.getParam("fixedPoints");c=c>3?3:c;const u=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,c);return u.get_m_cfg().set_collisions(17),u}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),t==null&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(y.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let l=0;l<o;l++){const h=[];for(let c=0;c<3;c++){let u=new m(n[r[l*3+c]*3+0],n[r[l*3+c]*3+1],n[r[l*3+c]*3+2]);D.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),u=m.TransformCoordinates(u,this._tmpMatrix);let d;c==0?d=this._tmpAmmoVectorA:c==1?d=this._tmpAmmoVectorB:d=this._tmpAmmoVectorC,d.setValue(u.x,u.y,u.z),h.push(d)}e.addPoint(h[0],!0),e.addPoint(h[1],!0),e.addPoint(h[2],!0),s++}i.getChildMeshes().forEach(l=>{s+=this._addHullVerts(e,t,l)})}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const n=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let o=0;if(n.forEach(l=>{const h=l.getPhysicsImpostor();if(h){if(h.type==We.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const c=this._createShape(h),u=l.parent.getWorldMatrix().clone(),d=new m;u.decompose(d),this._tmpAmmoTransform.getOrigin().setValue(l.position.x*d.x,l.position.y*d.y,l.position.z*d.z),this._tmpAmmoQuaternion.setValue(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,c),h.dispose(),o++}}),o>0){if(e.type!=We.NoImpostor){const l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,l))}return s}else this.bjsAMMO.destroy(s),s=null}switch(e.type){case We.SphereImpostor:if(ge.WithinEpsilon(r.x,r.y,1e-4)&&ge.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{const n=[new this.bjsAMMO.btVector3(0,0,0)],o=[1];s=new this.bjsAMMO.btMultiSphereShape(n,o,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case We.CapsuleImpostor:{const n=r.x/2;s=new this.bjsAMMO.btCapsuleShape(n,r.y-n*2)}break;case We.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case We.PlaneImpostor:case We.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case We.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const n=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(n),this._addMeshVerts(n,i,i)==0?s=new this.bjsAMMO.btCompoundShape:s=new this.bjsAMMO.btBvhTriangleMeshShape(n)}break}case We.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const n=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(n,i,i)==0?(e._pluginData.toDispose.push(n),s=new this.bjsAMMO.btCompoundShape):s=n}break}case We.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case We.CustomImpostor:s=this._createCustom(e);break;case We.SoftbodyImpostor:s=this._createSoftbody(e);break;case We.ClothImpostor:s=this._createCloth(e);break;case We.RopeImpostor:s=this._createRope(e);break;default:O.Warn("The impostor type is not currently supported by the ammo plugin.");break}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>rt||Math.abs(s.getOrigin().y()-t.y)>rt||Math.abs(s.getOrigin().z()-t.z)>rt||Math.abs(s.getRotation().x()-i.x)>rt||Math.abs(s.getRotation().y()-i.y)>rt||Math.abs(s.getRotation().z()-i.z)>rt||Math.abs(s.getRotation().w()-i.w)>rt)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),e.mass==0){const r=e.physicsBody.getMotionState();r&&r.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return this.bjsAMMO!==void 0}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(e.soft?t=e.physicsBody.linearVelocity():t=e.physicsBody.getLinearVelocity(),!t)return null;const i=new m(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(e.soft?t=e.physicsBody.angularVelocity():t=e.physicsBody.getAngularVelocity(),!t)return null;const i=new m(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(O.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===We.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):O.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(O.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=t<0?0:t,t=t>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):O.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(O.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):O.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(O.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):O.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,l=Math.round((o-1)*i),h=Math.round((o-1)*s),c=o-1-h,u=l+o*c;e.physicsBody.appendAnchor(u,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){O.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){O.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Wn._DISABLE_COLLISION_FLAG=4;Wn._KINEMATIC_FLAG=2;Wn._DISABLE_DEACTIVATION_FLAG=4;wi.prototype.removeReflectionProbe=function(a){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(a);return e!==-1&&this.reflectionProbes.splice(e,1),e};wi.prototype.addReflectionProbe=function(a){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(a)};class td{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=D.Identity(),this._target=m.Zero(),this._add=m.Zero(),this._invertYAxis=!1,this.position=m.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let c=0;c<6;++c)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${c}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const c=this._scene.getEngine().getCaps();c.textureHalfFloatRender?o=2:c.textureFloatRender&&(o=1)}this._renderTargetTexture=new oi(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(c=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[c]),i.getSceneUniformBuffer().unbindEffect()),c){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1);break}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const u=i.useRightHandedSystem?D.LookAtRHToRef:D.LookAtLHToRef,d=i.useRightHandedSystem?D.PerspectiveFovRH:D.PerspectiveFovLH;u(this.position,this._target,m.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=d(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position});let h;this._renderTargetTexture.onBeforeBindObservable.add(()=>{var c,u;this._currentSceneUBO=i.getSceneUniformBuffer(),(u=(c=i.getEngine())._debugPushGroup)==null||u.call(c,`reflection probe generation for ${e}`,1),h=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var c,u;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),(u=(c=i.getEngine())._debugPopGroup)==null||u.call(c,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(e!==-1&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const t=this._parentContainer.reflectionProbes.indexOf(this);t>-1&&this._parentContainer.reflectionProbes.splice(t,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const t of this._sceneUBOs)t.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=_e.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let r=0;r<t.reflectionProbes.length;r++){const n=t.reflectionProbes[r];if(n.name===e.name){s=n;break}}return s=_e.Parse(()=>s||new td(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}E([Wu()],td.prototype,"_attachedMesh",void 0);E([bs()],td.prototype,"position",void 0);class aN{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0}stopAnimation(){this._animationStarted=!1}_animate(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class _g extends aN{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new G,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new xe(1,1,1,1),this.position=m.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}serialize(){const e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e}static Parse(e,t){const i=new _g(e.name,t);return i.position=m.FromArray(e.position),i.color=xe.FromArray(e.color),i.width=e.width,i.height=e.height,i.angle=e.angle,i.cellIndex=e.cellIndex,i.cellRef=e.cellRef,i.invertU=e.invertU,i.invertV=e.invertV,i.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,i.isPickable=e.isPickable,i.isVisible=e.isVisible,i.useAlphaForPicking=e.useAlphaForPicking,i._fromIndex=e.fromIndex,i._toIndex=e.toIndex,i._loopAnimation=e.loopAnimation,i._delay=e.delay,e.animationStarted&&i.playAnimation(i.fromIndex,i.toIndex,i.loopAnimation,i.delay),i}}Ee.prototype._internalPickSprites=function(a,e,t,i){if(!es)return null;let s=null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r<this.spriteManagers.length;r++){const n=this.spriteManagers[r];if(!n.isPickable)continue;const o=n.intersects(a,i,e,t);if(!(!o||!o.hit)&&!(!t&&s!=null&&o.distance>=s.distance)&&(s=o,t))break}return s||new es};Ee.prototype._internalMultiPickSprites=function(a,e,t){if(!es)return null;let i=[];if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s<this.spriteManagers.length;s++){const r=this.spriteManagers[s];if(!r.isPickable)continue;const n=r.multiIntersects(a,t,e);n!==null&&(i=i.concat(n))}return i};Ee.prototype.pickSprite=function(a,e,t,i,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(a,e,this._tempSpritePickingRay,s);const r=this._internalPickSprites(this._tempSpritePickingRay,t,i,s);return r&&(r.ray=this.createPickingRayInCameraSpace(a,e,s)),r};Ee.prototype.pickSpriteWithRay=function(a,e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}tt.TransformToRef(a,i.getViewMatrix(),this._tempSpritePickingRay);const s=this._internalPickSprites(this._tempSpritePickingRay,e,t,i);return s&&(s.ray=a),s};Ee.prototype.multiPickSprite=function(a,e,t,i){return this.createPickingRayInCameraSpaceToRef(a,e,this._tempSpritePickingRay,i),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)};Ee.prototype.multiPickSpriteWithRay=function(a,e,t){if(!this._tempSpritePickingRay)return null;if(!t){if(!this.activeCamera)return null;t=this.activeCamera}return tt.TransformToRef(a,t.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,e,t)};Ee.prototype.setPointerOverSprite=function(a){this._pointerOverSprite!==a&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,di.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=a,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,di.CreateNewFromSprite(this._pointerOverSprite,this)))};Ee.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};class oN{constructor(e){this.name=he.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=[],this.scene._tempSpritePickingRay=tt?tt.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new G,this.scene.onAfterSpritesRenderingObservable=new G,this._spritePredicate=t=>t.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(he.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(he.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(he.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null)),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,di.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,di.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,di.CreateNewFromSprite(i.pickedSprite,r,s));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,di.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const o=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(7,di.CreateNewFromSprite(o.pickedSprite,n,s)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,di.CreateNewFromSprite(o.pickedSprite,n,s)),r&&o.pickedSprite.actionManager.processTrigger(6,di.CreateNewFromSprite(o.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==o.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,di.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}const lN="imageProcessingCompatibility",hN=`#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));
#endif
`;W.IncludesShadersStore[lN]=hN;const cN="spritesPixelShader",uN=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
#ifdef PIXEL_PERFECT
vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}
#endif
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#ifdef PIXEL_PERFECT
vec2 uv=uvPixelPerfect(vUV);
#else
vec2 uv=vUV;
#endif
vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)
{if (color.a<0.95)
discard;}
color*=vColor;
#include<fogFragment>
gl_FragColor=color;
#include<imageProcessingCompatibility>
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[cN]=uN;const dN="spritesVertexShader",fN=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;
#include<fogVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; 
vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); 
vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;
#ifdef FOG
vFogDistance=viewPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[dN]=fN;class _N{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Ji(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(y.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o=6,l;if(this._useInstancing){const d=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ji(e,d,!1,2),l=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else l=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;const h=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(y.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[y.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=l,this._vertexBuffers.inverts=h,this._vertexBuffers.cellInfo=c,this._vertexBuffers[y.ColorKind]=u,this._createEffects()}_createEffects(){var t,i,s,r;(t=this._drawWrapperBase)==null||t.dispose(),(i=this._drawWrapperFog)==null||i.dispose(),(s=this._drawWrapperDepth)==null||s.dispose(),(r=this._drawWrapperFogDepth)==null||r.dispose(),this._drawWrapperBase=new Bi(this._engine),this._drawWrapperFog=new Bi(this._engine),this._drawWrapperDepth=new Bi(this._engine,!1),this._drawWrapperFogDepth=new Bi(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const e=this._pixelPerfect?`#define PIXEL_PERFECT
`:"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[y.PositionKind,"options","offsets","inverts","cellInfo",y.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[y.PositionKind,"options","offsets","inverts","cellInfo",y.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],e+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,o=this._drawWrapperDepth,l=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&(n=this._drawWrapperFog,o=this._drawWrapperFogDepth,l=!0);const h=n.effect;if(!h.isReady())return;const c=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),f=Math.min(this._capacity,e.length);let _=0,p=!0;for(let S=0;S<f;S++){const C=e[S];!C||!C.isVisible||(p=!1,C._animate(t),this._appendSpriteVertex(_++,C,0,0,d,u,r),this._useInstancing||(this._appendSpriteVertex(_++,C,1,0,d,u,r),this._appendSpriteVertex(_++,C,1,1,d,u,r),this._appendSpriteVertex(_++,C,0,1,d,u,r)))}if(p)return;this._buffer.update(this._vertexData);const g=!!c.depthCullingState.cull,x=c.depthCullingState.zOffset,T=c.depthCullingState.zOffsetUnits;if(c.setState(g,x,!1,!1,void 0,void 0,T),c.enableEffect(n),h.setTexture("diffuseSampler",this.texture),h.setMatrix("view",i),h.setMatrix("projection",s),l){const S=this._scene;h.setFloat4("vFogInfos",S.fogMode,S.fogStart,S.fogEnd,S.fogDensity),h.setColor3("vFogColor",S.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=c.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,h)),c.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):c.bindBuffers(this._vertexBuffers,this._indexBuffer,h),c.depthCullingState.depthFunc=c.useReverseDepthBuffer?518:515,this.disableDepthWrite||(h.setBool("alphaTest",!0),c.setColorWrite(!1),c.enableEffect(o),this._useInstancing?c.drawArraysType(7,0,4,_):c.drawElementsType(0,0,_/4*6),c.enableEffect(n),c.setColorWrite(!0),h.setBool("alphaTest",!1)),c.setAlphaMode(this.blendMode),this._useInstancing?c.drawArraysType(7,0,4,_):c.drawElementsType(0,0,_/4*6),this.autoResetAlpha&&c.setAlphaMode(0),u&&this._scene.getEngine().setState(g,x,!1,!0,void 0,void 0,T),c.unbindInstanceAttributes()}_appendSpriteVertex(e,t,i,s,r,n,o){let l=e*this._vertexBufferSize;if(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),s===0?s=this._epsilon:s===1&&(s=1-this._epsilon),o)o(t,r);else{t.cellIndex||(t.cellIndex=0);const h=r.width/this.cellWidth,c=t.cellIndex/h>>0;t._xOffset=(t.cellIndex-c*h)*this.cellWidth/r.width,t._yOffset=c*this.cellHeight/r.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[l]=t.position.x,this._vertexData[l+1]=t.position.y,this._vertexData[l+2]=t.position.z,this._vertexData[l+3]=t.angle,this._vertexData[l+4]=t.width,this._vertexData[l+5]=t.height,this._useInstancing?l-=2:(this._vertexData[l+6]=i,this._vertexData[l+7]=s),n?this._vertexData[l+8]=t.invertU?0:1:this._vertexData[l+8]=t.invertU?1:0,this._vertexData[l+9]=t.invertV?1:0,this._vertexData[l+10]=t._xOffset,this._vertexData[l+11]=t._yOffset,this._vertexData[l+12]=t._xSize/r.width,this._vertexData[l+13]=t._ySize/r.height,this._vertexData[l+14]=t.color.r,this._vertexData[l+15]=t.color.g,this._vertexData[l+16]=t.color.b,this._vertexData[l+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}rebuild(){var e;this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild();for(const t in this._vertexBuffers)this._vertexBuffers[t]._rebuild();(e=this._spriteBuffer)==null||e._rebuild()}dispose(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()}}class oa{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get children(){return this.sprites}get scene(){return this._scene}get capacity(){return this._spriteRenderer.capacity}get texture(){return this._spriteRenderer.texture}set texture(e){e.wrapU=k.CLAMP_ADDRESSMODE,e.wrapV=k.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null}get cellWidth(){return this._spriteRenderer.cellWidth}set cellWidth(e){this._spriteRenderer.cellWidth=e}get cellHeight(){return this._spriteRenderer.cellHeight}set cellHeight(e){this._spriteRenderer.cellHeight=e}get fogEnabled(){return this._spriteRenderer.fogEnabled}set fogEnabled(e){this._spriteRenderer.fogEnabled=e}get blendMode(){return this._spriteRenderer.blendMode}set blendMode(e){this._spriteRenderer.blendMode=e}get disableDepthWrite(){return this._disableDepthWrite}set disableDepthWrite(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e}get pixelPerfect(){return this._spriteRenderer.pixelPerfect}set pixelPerfect(e){this._spriteRenderer.pixelPerfect=e,e&&this.texture.samplingMode!==3&&this.texture.updateSamplingMode(3)}constructor(e,t,i,s,r,n=.01,o=k.TRILINEAR_SAMPLINGMODE,l=!1,h=null){this.name=e,this.sprites=[],this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new G,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=(u,d)=>{u.cellRef||(u.cellIndex=0);const f=u.cellIndex;typeof f=="number"&&isFinite(f)&&Math.floor(f)===f&&(u.cellRef=this._spriteMap[u.cellIndex]),u._xOffset=this._cellData[u.cellRef].frame.x/d.width,u._yOffset=this._cellData[u.cellRef].frame.y/d.height,u._xSize=this._cellData[u.cellRef].frame.w,u._ySize=this._cellData[u.cellRef].frame.h},r||(r=Ae.LastCreatedScene),r._getComponent(he.NAME_SPRITE)||r._addComponent(new oN(r)),this._fromPacked=l,this._scene=r;const c=this._scene.getEngine();if(this._spriteRenderer=new _N(c,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else if(s!==void 0)this.cellWidth=s,this.cellHeight=s;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new k(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,h)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(t!==null)try{let i;if(typeof t=="string"?i=JSON.parse(t):i=t,i.frames.length){const r={};for(let n=0;n<i.frames.length;n++){const o=i.frames[n];if(typeof Object.keys(o)[0]!="string")throw new Error("Invalid JSON Format.  Check the frame values and make sure the name is the first parameter.");const l=o[Object.keys(o)[0]];r[l]=o}i.frames=r}const s=Reflect.ownKeys(i.frames);this._spriteMap=s,this._packedAndReady=!0,this._cellData=i.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{const i=/\./g;let s;do s=i.lastIndex,i.test(e);while(i.lastIndex>0);const r=e.substring(0,s-1)+".json",n=()=>{O.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=l=>{try{const h=JSON.parse(l),c=Reflect.ownKeys(h.frames);this._spriteMap=c,this._packedAndReady=!0,this._cellData=h.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};X.LoadFile(r,o,void 0,void 0,!1,n)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=U.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const l=(o.x-s.x)/(r.x-s.x),h=1-(o.y-s.y)/(r.y-s.y),c=e._xOffset*n.width+l*e._xSize|0,u=e._yOffset*n.height+h*e._ySize|0;return this._textureContent[(c+u*n.width)*4+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=m.Zero(),o=m.Zero();let l=Number.MAX_VALUE,h=null;const c=U.Vector3[0],u=U.Vector3[1],d=t.getViewMatrix();let f=e,_=e;for(let p=0;p<r;p++){const g=this.sprites[p];if(g){if(i){if(!i(g))continue}else if(!g.isPickable)continue;if(m.TransformCoordinatesToRef(g.position,d,u),g.angle?(D.TranslationToRef(-u.x,-u.y,0,U.Matrix[1]),D.TranslationToRef(u.x,u.y,0,U.Matrix[2]),D.RotationZToRef(-g.angle,U.Matrix[3]),U.Matrix[1].multiplyToRef(U.Matrix[3],U.Matrix[4]),U.Matrix[4].multiplyToRef(U.Matrix[2],U.Matrix[0]),f=e.clone(),m.TransformCoordinatesToRef(e.origin,U.Matrix[0],f.origin),m.TransformNormalToRef(e.direction,U.Matrix[0],f.direction)):f=e,n.copyFromFloats(u.x-g.width/2,u.y-g.height/2,u.z),o.copyFromFloats(u.x+g.width/2,u.y+g.height/2,u.z),f.intersectsBoxMinMax(n,o)){const x=m.Distance(u,f.origin);if(l>x){if(!this._checkTextureAlpha(g,f,x,n,o))continue;if(_=f,l=x,h=g,s)break}}}}if(h){const p=new es;d.invertToRef(U.Matrix[0]),p.hit=!0,p.pickedSprite=h,p.distance=l;const g=U.Vector3[2];return g.copyFrom(_.direction),g.normalize(),g.scaleInPlace(l),_.origin.addToRef(g,c),p.pickedPoint=m.TransformCoordinates(c,U.Matrix[0]),p}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=m.Zero(),n=m.Zero();let o;const l=[],h=U.Vector3[0].copyFromFloats(0,0,0),c=U.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let d=0;d<s;d++){const f=this.sprites[d];if(f){if(i){if(!i(f))continue}else if(!f.isPickable)continue;if(m.TransformCoordinatesToRef(f.position,u,c),r.copyFromFloats(c.x-f.width/2,c.y-f.height/2,c.z),n.copyFromFloats(c.x+f.width/2,c.y+f.height/2,c.z),e.intersectsBoxMinMax(r,n)){if(o=m.Distance(c,e.origin),!this._checkTextureAlpha(f,e,o,r,n))continue;const _=new es;l.push(_),u.invertToRef(U.Matrix[0]),_.hit=!0,_.pickedSprite=f,_.distance=o;const p=U.Vector3[2];p.copyFrom(e.direction),p.normalize(),p.scaleInPlace(o),e.origin.addToRef(p,h),_.pickedPoint=m.TransformCoordinates(h,U.Matrix[0])}}}return l}render(){if(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))return;const t=this._scene.getEngine().getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}rebuild(){var e;(e=this._spriteRenderer)==null||e.rebuild()}dispose(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){const e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null}serialize(e=!1){const t={};t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[];for(const i of this.sprites)t.sprites.push(i.serialize());return t.metadata=this.metadata,t}static Parse(e,t,i){const s=new oa(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},t);e.fogEnabled!==void 0&&(s.fogEnabled=e.fogEnabled),e.blendMode!==void 0&&(s.blendMode=e.blendMode),e.disableDepthWrite!==void 0&&(s.disableDepthWrite=e.disableDepthWrite),e.pixelPerfect!==void 0&&(s.pixelPerfect=e.pixelPerfect),e.metadata!==void 0&&(s.metadata=e.metadata),e.texture?s.texture=k.Parse(e.texture,t,i):e.textureName&&(s.texture=new k(i+e.textureUrl,t,!1,e.invertY!==void 0?e.invertY:!0));for(const r of e.sprites)_g.Parse(r,s);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const o=new yi;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=oa.Parse(l,i||Ae.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the sprite manager")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return e==="_BLANK"?Promise.resolve(new oa("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((s,r)=>{const n=new yi;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.spriteManager),h=oa.Parse(l,t||Ae.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()})}}oa.SnippetUrl="https://snippet.babylonjs.com";oa.CreateFromSnippetAsync=oa.ParseFromSnippetAsync;class Xd{}Xd.LoaderInjectedPhysicsEngine=void 0;let ul={},Va={};const gT=(a,e,t,i)=>{if(!e.materials)return null;for(let s=0,r=e.materials.length;s<r;s++){const n=e.materials[s];if(a(n))return{parsedMaterial:n,material:ee.Parse(n,t,i)}}return null},pN=(a,e,t)=>{for(const i in e)if(a.name===e[i])return t.push(a.id),!0;return a.parentId!==void 0&&t.indexOf(a.parentId)!==-1?(t.push(a.id),!0):!1},xl=(a,e)=>a+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),wS=(a,e)=>{const t=e;if(e._waitingData.lods){if(e._waitingData.lods.ids&&e._waitingData.lods.ids.length>0){const i=e._waitingData.lods.ids,s=t.isEnabled(!1);if(e._waitingData.lods.distances){const r=e._waitingData.lods.distances;if(r.length>=i.length){const n=r.length>i.length?r[r.length-1]:0;t.setEnabled(!1);for(let o=0;o<i.length;o++){const l=i[o],h=a.getMeshById(l);h!=null&&t.addLODLevel(r[o],h)}n>0&&t.addLODLevel(n,null),s===!0&&t.setEnabled(!0)}else X.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},Fd=(a,e,t)=>{if(typeof a!="number"){const s=t.getLastEntryById(a);return s&&e!==void 0&&e!==null?s.instances[parseInt(e)]:s}const i=ul[a];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},cf=(a,e)=>typeof a!="number"?e.getLastMaterialById(a,!0):Va[a],xT=(a,e,t,i,s=!1)=>{const r=new Df(a);let n="importScene has failed JSON parse";try{var o=JSON.parse(e);n="";const l=je.loggingLevel===je.DETAILED_LOGGING;let h,c;if(o.environmentTexture!==void 0&&o.environmentTexture!==null){const d=o.isPBR!==void 0?o.isPBR:!0;if(o.environmentTextureType&&o.environmentTextureType==="BABYLON.HDRCubeTexture"){const f=o.environmentTextureSize?o.environmentTextureSize:128,_=new No((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,f,!0,!d,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(_.rotationY=o.environmentTextureRotationY),a.environmentTexture=_}else if(typeof o.environmentTexture=="object"){const f=Hi.Parse(o.environmentTexture,a,t);a.environmentTexture=f}else if(o.environmentTexture.endsWith(".env")){const f=new Hi((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),a.environmentTexture=f}else{const f=Hi.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),a.environmentTexture=f}if(o.createDefaultSkybox===!0){const f=a.activeCamera!==void 0&&a.activeCamera!==null?(a.activeCamera.maxZ-a.activeCamera.minZ)/2:1e3,_=o.skyboxBlurLevel||0;a.createDefaultSkybox(a.environmentTexture,d,f,_)}r.environmentTexture=a.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(a.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(h=0,c=o.lights.length;h<c;h++){const d=o.lights[h],f=st.Parse(d,a);f&&(ul[d.uniqueId]=f,r.lights.push(f),f._parentContainer=r,n+=h===0?`
	Lights:`:"",n+=`
		`+f.toString(l))}if(o.reflectionProbes!==void 0&&o.reflectionProbes!==null)for(h=0,c=o.reflectionProbes.length;h<c;h++){const d=o.reflectionProbes[h],f=td.Parse(d,a,t);f&&(r.reflectionProbes.push(f),f._parentContainer=r,n+=h===0?`
	Reflection Probes:`:"",n+=`
		`+f.toString(l))}if(o.animations!==void 0&&o.animations!==null)for(h=0,c=o.animations.length;h<c;h++){const d=o.animations[h],f=Si("BABYLON.Animation");if(f){const _=f.Parse(d);a.animations.push(_),r.animations.push(_),n+=h===0?`
	Animations:`:"",n+=`
		`+_.toString(l)}}if(o.materials!==void 0&&o.materials!==null)for(h=0,c=o.materials.length;h<c;h++){const d=o.materials[h],f=ee.Parse(d,a,t);f&&(Va[d.uniqueId||d.id]=f,r.materials.push(f),f._parentContainer=r,n+=h===0?`
	Materials:`:"",n+=`
		`+f.toString(l),f.getActiveTextures().forEach(p=>{r.textures.indexOf(p)==-1&&(r.textures.push(p),p._parentContainer=r)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(h=0,c=o.multiMaterials.length;h<c;h++){const d=o.multiMaterials[h],f=_a.ParseMultiMaterial(d,a);Va[d.uniqueId||d.id]=f,r.multiMaterials.push(f),f._parentContainer=r,n+=h===0?`
	MultiMaterials:`:"",n+=`
		`+f.toString(l),f.getActiveTextures().forEach(p=>{r.textures.indexOf(p)==-1&&(r.textures.push(p),p._parentContainer=r)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const d of o.morphTargetManagers){const f=zn.Parse(d,a);r.morphTargetManagers.push(f),f._parentContainer=r}if(o.skeletons!==void 0&&o.skeletons!==null)for(h=0,c=o.skeletons.length;h<c;h++){const d=o.skeletons[h],f=eo.Parse(d,a);r.skeletons.push(f),f._parentContainer=r,n+=h===0?`
	Skeletons:`:"",n+=`
		`+f.toString(l)}const u=o.geometries;if(u!=null){const d=new Array,f=u.vertexData;if(f!=null)for(h=0,c=f.length;h<c;h++){const _=f[h];d.push(zi.Parse(_,a,t))}d.forEach(_=>{_&&(r.geometries.push(_),_._parentContainer=r)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(h=0,c=o.transformNodes.length;h<c;h++){const d=o.transformNodes[h],f=Ke.Parse(d,a,t);ul[d.uniqueId]=f,r.transformNodes.push(f),f._parentContainer=r}if(o.meshes!==void 0&&o.meshes!==null)for(h=0,c=o.meshes.length;h<c;h++){const d=o.meshes[h],f=z.Parse(d,a,t);if(ul[d.uniqueId]=f,r.meshes.push(f),f._parentContainer=r,f.hasInstances)for(const _ of f.instances)r.meshes.push(_),_._parentContainer=r;n+=h===0?`
	Meshes:`:"",n+=`
		`+f.toString(l)}if(o.cameras!==void 0&&o.cameras!==null)for(h=0,c=o.cameras.length;h<c;h++){const d=o.cameras[h],f=ve.Parse(d,a);ul[d.uniqueId]=f,r.cameras.push(f),f._parentContainer=r,n+=h===0?`
	Cameras:`:"",n+=`
		`+f.toString(l)}if(o.postProcesses!==void 0&&o.postProcesses!==null)for(h=0,c=o.postProcesses.length;h<c;h++){const d=o.postProcesses[h],f=De.Parse(d,a,t);f&&(r.postProcesses.push(f),f._parentContainer=r,n+=h===0?`
Postprocesses:`:"",n+=`
		`+f.toString())}if(o.animationGroups!==void 0&&o.animationGroups!==null)for(h=0,c=o.animationGroups.length;h<c;h++){const d=o.animationGroups[h],f=Nn.Parse(d,a);r.animationGroups.push(f),f._parentContainer=r,n+=h===0?`
	AnimationGroups:`:"",n+=`
		`+f.toString(l)}if(o.spriteManagers)for(let d=0,f=o.spriteManagers.length;d<f;d++){const _=o.spriteManagers[d],p=oa.Parse(_,a,t);n+=`
		SpriteManager `+p.name}for(h=0,c=a.cameras.length;h<c;h++){const d=a.cameras[h];d._waitingParentId!==null&&(d.parent=Fd(d._waitingParentId,d._waitingParentInstanceIndex,a),d._waitingParentId=null,d._waitingParentInstanceIndex=null)}for(h=0,c=a.lights.length;h<c;h++){const d=a.lights[h];d&&d._waitingParentId!==null&&(d.parent=Fd(d._waitingParentId,d._waitingParentInstanceIndex,a),d._waitingParentId=null,d._waitingParentInstanceIndex=null)}for(h=0,c=a.transformNodes.length;h<c;h++){const d=a.transformNodes[h];d._waitingParentId!==null&&(d.parent=Fd(d._waitingParentId,d._waitingParentInstanceIndex,a),d._waitingParentId=null,d._waitingParentInstanceIndex=null)}for(h=0,c=a.meshes.length;h<c;h++){const d=a.meshes[h];d._waitingParentId!==null&&(d.parent=Fd(d._waitingParentId,d._waitingParentInstanceIndex,a),d._waitingParentId=null,d._waitingParentInstanceIndex=null),d._waitingData.lods&&wS(a,d)}for(a.multiMaterials.forEach(d=>{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(cf(f,a))}),d._waitingSubMaterialsUniqueIds=[]}),a.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=cf(d._waitingMaterialId,a),d._waitingMaterialId=null)}),h=0,c=a.skeletons.length;h<c;h++){const d=a.skeletons[h];d._hasWaitingData&&(d.bones!=null&&d.bones.forEach(f=>{if(f._waitingTransformNodeId){const _=a.getLastEntryById(f._waitingTransformNodeId);_&&f.linkTransformNode(_),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(h=0,c=a.meshes.length;h<c;h++){const d=a.meshes[h];d._waitingData.freezeWorldMatrix?(d.freezeWorldMatrix(),d._waitingData.freezeWorldMatrix=null):d.computeWorldMatrix(!0)}for(h=0,c=a.lights.length;h<c;h++){const d=a.lights[h];if(d._excludedMeshesIds.length>0){for(let f=0;f<d._excludedMeshesIds.length;f++){const _=a.getMeshById(d._excludedMeshesIds[f]);_&&d.excludedMeshes.push(_)}d._excludedMeshesIds=[]}if(d._includedOnlyMeshesIds.length>0){for(let f=0;f<d._includedOnlyMeshesIds.length;f++){const _=a.getMeshById(d._includedOnlyMeshesIds[f]);_&&d.includedOnlyMeshes.push(_)}d._includedOnlyMeshesIds=[]}}for(a.geometries.forEach(d=>{d._loadedUniqueId=""}),wi.Parse(o,a,r,t),h=0,c=a.meshes.length;h<c;h++){const d=a.meshes[h];d._waitingData.actions&&(It.Parse(d._waitingData.actions,d,a),d._waitingData.actions=null)}o.actions!==void 0&&o.actions!==null&&It.Parse(o.actions,null,a)}catch(l){const h=xl("loadAssets",o?o.producer:"Unknown")+n;if(i)i(h,l);else throw O.Log(h),l}finally{ul={},Va={},s||r.removeAllFromScene(),n!==null&&je.loggingLevel!==je.NO_LOGGING&&O.Log(xl("loadAssets",o?o.producer:"Unknown")+(je.loggingLevel!==je.MINIMAL_LOGGING?n:""))}return r};je.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:a=>a.indexOf("babylon")!==-1,importMesh:(a,e,t,i,s,r,n,o)=>{var c;let l="importMesh has failed JSON parse";try{var h=JSON.parse(t);l="";const u=je.loggingLevel===je.DETAILED_LOGGING;a?Array.isArray(a)||(a=[a]):a=null;const d=[],f=new Map,_=[];if(h.transformNodes!==void 0&&h.transformNodes!==null)for(let p=0,g=h.transformNodes.length;p<g;p++){const x=h.transformNodes[p],T=Ke.Parse(x,e,i);_.push(T),f.set(T._waitingParsedUniqueId,T),T._waitingParsedUniqueId=null}if(h.meshes!==void 0&&h.meshes!==null){const p=[],g=[],x=[],T=[];for(let C=0,v=h.meshes.length;C<v;C++){const b=h.meshes[C];if(a===null||pN(b,a,d)){if(a!==null&&delete a[a.indexOf(b.name)],b.geometryId!==void 0&&b.geometryId!==null&&h.geometries!==void 0&&h.geometries!==null){let P=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(L=>{P===!0||!h.geometries[L]||!Array.isArray(h.geometries[L])||h.geometries[L].forEach(w=>{if(w.id===b.geometryId){switch(L){case"vertexData":zi.Parse(w,e,i);break}P=!0}})}),P===!1&&O.Warn("Geometry not found for mesh "+b.id)}if(b.materialUniqueId||b.materialId){const P=b.materialUniqueId?x:g;let L=P.indexOf(b.materialUniqueId||b.materialId)!==-1;if(L===!1&&h.multiMaterials!==void 0&&h.multiMaterials!==null){const w=($,J)=>{P.push($);const ne=gT(J,h,e,i);ne&&ne.material&&(Va[ne.parsedMaterial.uniqueId||ne.parsedMaterial.id]=ne.material,l+=`
	Material `+ne.material.toString(u))};for(let $=0,J=h.multiMaterials.length;$<J;$++){const ne=h.multiMaterials[$];if(b.materialUniqueId&&ne.uniqueId===b.materialUniqueId||ne.id===b.materialId){ne.materialsUniqueIds?ne.materialsUniqueIds.forEach(re=>w(re,ce=>ce.uniqueId===re)):ne.materials.forEach(re=>w(re,ce=>ce.id===re)),P.push(ne.uniqueId||ne.id);const oe=_a.ParseMultiMaterial(ne,e);Va[ne.uniqueId||ne.id]=oe,oe&&(L=!0,l+=`
	Multi-Material `+oe.toString(u));break}}}if(L===!1){P.push(b.materialUniqueId||b.materialId);const w=gT($=>b.materialUniqueId&&$.uniqueId===b.materialUniqueId||$.id===b.materialId,h,e,i);!w||!w.material?O.Warn("Material not found for mesh "+b.id):(Va[w.parsedMaterial.uniqueId||w.parsedMaterial.id]=w.material,l+=`
	Material `+w.material.toString(u))}}if(b.skeletonId!==null&&b.skeletonId!==void 0&&h.skeletonId!==-1&&h.skeletons!==void 0&&h.skeletons!==null&&!(p.indexOf(b.skeletonId)>-1))for(let L=0,w=h.skeletons.length;L<w;L++){const $=h.skeletons[L];if($.id===b.skeletonId){const J=eo.Parse($,e);n.push(J),p.push($.id),l+=`
	Skeleton `+J.toString(u)}}if(b.morphTargetManagerId>-1&&h.morphTargetManagers!==void 0&&h.morphTargetManagers!==null&&!(T.indexOf(b.morphTargetManagerId)>-1))for(let L=0,w=h.morphTargetManagers.length;L<w;L++){const $=h.morphTargetManagers[L];if($.id===b.morphTargetManagerId){const J=zn.Parse($,e);T.push(J.uniqueId),l+=`
Morph target `+J.toString()}}const A=z.Parse(b,e,i);s.push(A),f.set(A._waitingParsedUniqueId,A),A._waitingParsedUniqueId=null,l+=`
	Mesh `+A.toString(u)}}e.multiMaterials.forEach(C=>{C._waitingSubMaterialsUniqueIds.forEach(v=>{C.subMaterials.push(cf(v,e))}),C._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(C=>{C._waitingMaterialId!==null&&(C.material=cf(C._waitingMaterialId,e),C._waitingMaterialId=null)});for(let C=0,v=e.transformNodes.length;C<v;C++){const b=e.transformNodes[C];if(b._waitingParentId!==null){let A=f.get(parseInt(b._waitingParentId))||null;A===null&&(A=e.getLastEntryById(b._waitingParentId));let P=A;b._waitingParentInstanceIndex&&(P=A.instances[parseInt(b._waitingParentInstanceIndex)],b._waitingParentInstanceIndex=null),b.parent=P,b._waitingParentId=null}}let S;for(let C=0,v=e.meshes.length;C<v;C++){if(S=e.meshes[C],S._waitingParentId){let b=f.get(parseInt(S._waitingParentId))||null;b===null&&(b=e.getLastEntryById(S._waitingParentId));let A=b;if(S._waitingParentInstanceIndex&&(A=b.instances[parseInt(S._waitingParentInstanceIndex)],S._waitingParentInstanceIndex=null),S.parent=A,((c=S.parent)==null?void 0:c.getClassName())==="TransformNode"){const P=_.indexOf(S.parent);P>-1&&_.splice(P,1)}S._waitingParentId=null}S._waitingData.lods&&wS(e,S)}for(const C of _)C.dispose();for(let C=0,v=e.skeletons.length;C<v;C++){const b=e.skeletons[C];b._hasWaitingData&&(b.bones!=null&&b.bones.forEach(A=>{if(A._waitingTransformNodeId){const P=e.getLastEntryById(A._waitingTransformNodeId);P&&A.linkTransformNode(P),A._waitingTransformNodeId=null}}),b._hasWaitingData=null)}for(let C=0,v=e.meshes.length;C<v;C++)S=e.meshes[C],S._waitingData.freezeWorldMatrix?(S.freezeWorldMatrix(),S._waitingData.freezeWorldMatrix=null):S.computeWorldMatrix(!0)}if(h.particleSystems!==void 0&&h.particleSystems!==null){const p=wi.GetIndividualParser(he.NAME_PARTICLESYSTEM);if(p)for(let g=0,x=h.particleSystems.length;g<x;g++){const T=h.particleSystems[g];d.indexOf(T.emitterId)!==-1&&r.push(p(T,e,i))}}return e.geometries.forEach(p=>{p._loadedUniqueId=""}),!0}catch(u){const d=xl("importMesh",h?h.producer:"Unknown")+l;if(o)o(d,u);else throw O.Log(d),u}finally{l!==null&&je.loggingLevel!==je.NO_LOGGING&&O.Log(xl("importMesh",h?h.producer:"Unknown")+(je.loggingLevel!==je.MINIMAL_LOGGING?l:"")),Va={}}return!1},load:(a,e,t,i)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(e);if(s="",r.useDelayedTextureLoading!==void 0&&r.useDelayedTextureLoading!==null&&(a.useDelayedTextureLoading=r.useDelayedTextureLoading&&!je.ForceFullSceneLoadingForIncremental),r.autoClear!==void 0&&r.autoClear!==null&&(a.autoClear=r.autoClear),r.clearColor!==void 0&&r.clearColor!==null&&(a.clearColor=xe.FromArray(r.clearColor)),r.ambientColor!==void 0&&r.ambientColor!==null&&(a.ambientColor=q.FromArray(r.ambientColor)),r.gravity!==void 0&&r.gravity!==null&&(a.gravity=m.FromArray(r.gravity)),r.useRightHandedSystem!==void 0&&(a.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&r.fogMode!==0)switch(a.fogMode=r.fogMode,a.fogColor=q.FromArray(r.fogColor),a.fogStart=r.fogStart,a.fogEnd=r.fogEnd,a.fogDensity=r.fogDensity,s+="	Fog mode for scene:  ",a.fogMode){case 1:s+=`exp
`;break;case 2:s+=`exp2
`;break;case 3:s+=`linear
`;break}if(r.physicsEnabled){let o;r.physicsEngine==="cannon"||r.physicsEngine===pp.name?o=new pp(void 0,void 0,Xd.LoaderInjectedPhysicsEngine):r.physicsEngine==="oimo"||r.physicsEngine===mT.name?o=new mT(void 0,Xd.LoaderInjectedPhysicsEngine):(r.physicsEngine==="ammo"||r.physicsEngine===Wn.name)&&(o=new Wn(void 0,Xd.LoaderInjectedPhysicsEngine,void 0)),s="	Physics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+` enabled
`;const l=r.physicsGravity?m.FromArray(r.physicsGravity):null;a.enablePhysics(l,o)}return r.metadata!==void 0&&r.metadata!==null&&(a.metadata=r.metadata),r.collisionsEnabled!==void 0&&r.collisionsEnabled!==null&&(a.collisionsEnabled=r.collisionsEnabled),xT(a,e,t,i,!0)?(r.autoAnimate&&a.beginAnimation(a,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),r.activeCameraID!==void 0&&r.activeCameraID!==null&&a.setActiveCameraById(r.activeCameraID),!0):!1}catch(n){const o=xl("importScene",r?r.producer:"Unknown")+s;if(i)i(o,n);else throw O.Log(o),n}finally{s!==null&&je.loggingLevel!==je.NO_LOGGING&&O.Log(xl("importScene",r?r.producer:"Unknown")+(je.loggingLevel!==je.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(a,e,t,i)=>xT(a,e,t,i)});class uf{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,H.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=e.bias===void 0?0:e.bias,this.power=e.power===void 0?1:e.power,this.leftColor=e.leftColor||q.White(),this.rightColor=e.rightColor||q.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new uf;return Cs.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new uf({isEnabled:e.isEnabled,leftColor:q.FromArray(e.leftColor),rightColor:q.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}_e._FresnelParametersParser=uf.Parse;class Js extends At{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new q(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}E([I(),te("_markAllSubMeshesAsLightsDirty")],Js.prototype,"maxSimultaneousLights",void 0);E([I(),te("_markAllSubMeshesAsLightsDirty")],Js.prototype,"disableLighting",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Js.prototype,"environmentTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"invertNormalMapX",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"invertNormalMapY",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Js.prototype,"normalTexture",void 0);E([li("emissive"),te("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"emissiveColor",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"emissiveTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Js.prototype,"occlusionStrength",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Js.prototype,"occlusionTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Js.prototype,"alphaCutOff",void 0);E([I()],Js.prototype,"doubleSided",null);E([ht(),te("_markAllSubMeshesAsTexturesDirty",null)],Js.prototype,"lightmapTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Js.prototype,"useLightmapAsShadowmap",void 0);class xa extends Js{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=_e.Clone(()=>new xa(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=_e.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=_e.Parse(()=>new xa(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}E([li(),te("_markAllSubMeshesAsTexturesDirty","_albedoColor")],xa.prototype,"baseColor",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],xa.prototype,"baseTexture",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],xa.prototype,"metallic",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],xa.prototype,"roughness",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],xa.prototype,"metallicRoughnessTexture",void 0);V("BABYLON.PBRMetallicRoughnessMaterial",xa);class Ta extends Js{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=_e.Clone(()=>new Ta(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=_e.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=_e.Parse(()=>new Ta(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}E([li("diffuse"),te("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Ta.prototype,"diffuseColor",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Ta.prototype,"diffuseTexture",void 0);E([li("specular"),te("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Ta.prototype,"specularColor",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty","_microSurface")],Ta.prototype,"glossiness",void 0);E([ht(),te("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Ta.prototype,"specularGlossinessTexture",void 0);V("BABYLON.PBRSpecularGlossinessMaterial",Ta);class Rl extends Et{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=D.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const s=this.getScene();s?s.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture():this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;e._features.support3DTextures?t=e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t=e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=r=>{if(typeof r!="string")return;let n=null,o=null,l;const h=r.split(`
`);let c=0,u=0,d=0,f=0,_=0;for(let p=0;p<h.length;p++){if(l=h[p],!Rl._NoneEmptyLineRegex.test(l)||l.indexOf("#")===0)continue;const g=l.split(" ");if(c===0){c=g.length,n=new Uint8Array(c*c*c*4),o=new Float32Array(c*c*c*4);continue}if(c!=0){const x=Math.max(parseInt(g[0]),0),T=Math.max(parseInt(g[1]),0),S=Math.max(parseInt(g[2]),0);_=Math.max(x,_),_=Math.max(T,_),_=Math.max(S,_);const C=(u+f*c+d*c*c)*4;o&&(o[C+0]=x,o[C+1]=T,o[C+2]=S),d++,d%c==0&&(f++,d=0,f%c==0&&(u++,f=0))}}if(o&&n)for(let p=0;p<o.length;p++)if(p>0&&(p+1)%4===0)n[p]=255;else{const g=o[p];n[p]=g/_*255}t.is3D?(t.updateSize(c,c,c),e.updateRawTexture3D(t,n,5,!1)):(t.updateSize(c*c,c),e.updateRawTexture(t,n,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Rl(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){this.delayLoadState===4&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new Rl(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}Rl._NoneEmptyLineRegex=/\S+/;V("BABYLON.ColorGradingTexture",Rl);class df extends Et{constructor(e,t,i,s=!1,r=!0,n=null,o=null,l=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=k.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=l,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?X.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");Hu(this.url,n=>{this._width=n.width,this._height=n.height,r.width=this._width,r.height=this._height;const o=r.getContext("2d");o.drawImage(n,0,0);const l=o.getImageData(0,0,n.width,n.height);this._buffer=l.data.buffer,r.remove(),e()},(n,o)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,o)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const r=this._getFloat32ArrayFromArrayBuffer(this._buffer),n=co.ConvertPanoramaToCubemap(r,this._width,this._height,this._size,this._supersample),o=[];for(let l=0;l<6;l++){const h=n[df._FacesMapping[l]];o.push(h)}return o};if(!e)return;const i=t(),s=this._texture;e.getEngine().updateRawCubeTexture(s,i,s.format,s.type,s.invertY),s.isReady=!0,e.removePendingData(s),s.onLoadedObservable.notifyObservers(s),s.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let s=0;for(let r=0;r<e.byteLength;r++)(r+1)%4!==0&&(i[s++]=t.getUint8(r)/255);return i}getClassName(){return"EquiRectangularCubeTexture"}clone(){const e=this.getScene();if(!e)return this;const t=new df(this.url,e,this._size,this._noMipmap,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t}}df._FacesMapping=["right","left","up","down","front","back"];class pg extends Et{constructor(e,t,i){var s;super(i.scene||i.engine),this.onLoadObservable=new G,!(!t||!i.engine&&!i.scene)&&(i={...pg._DefaultOptions,...i},this._generateMipMaps=i.generateMipMaps,this._samplingMode=i.samplingMode,this._textureMatrix=D.Identity(),this._format=i.format,this.name=e,this.element=t,this._isVideo=!!t.getVideoPlaybackQuality,this._externalTexture=this._isVideo?((s=this._engine)==null?void 0:s.createExternalTexture(t))??null:null,this.anisotropicFilteringLevel=1,this._createInternalTexture())}_createInternalTexture(){let e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);const i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()}getTextureMatrix(){return this._textureMatrix}update(e=null){const t=this._getEngine();if(this._texture==null||t==null)return;const i=this.isReady();if(this._isVideo){const s=this.element;if(s.readyState<s.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:s,e===null?!0:e)}else{const s=this.element;t.updateDynamicTexture(this._texture,s,e===null?!0:e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}dispose(){this.onLoadObservable.clear(),super.dispose()}}pg._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};const mN=1,gN=2,xN=3,TN=9,EN=10,SN=11,CN=48,vN=4,bN=0,AN=1,yN=2,RN=3;function i_(a){let e=0;return{id_length:a[e++],colormap_type:a[e++],image_type:a[e++],colormap_index:a[e++]|a[e++]<<8,colormap_length:a[e++]|a[e++]<<8,colormap_size:a[e++],origin:[a[e++]|a[e++]<<8,a[e++]|a[e++]<<8],width:a[e++]|a[e++]<<8,height:a[e++]|a[e++]<<8,pixel_size:a[e++],flags:a[e++]}}function LS(a,e){if(e.length<19){O.Error("Unable to load TGA file - Not enough data to contain header");return}let t=18;const i=i_(e);if(i.id_length+t>e.length){O.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let s=!1,r=!1,n=!1;switch(i.image_type){case TN:s=!0;case mN:r=!0;break;case EN:s=!0;case gN:break;case SN:s=!0;case xN:n=!0;break}let o;const l=i.pixel_size>>3,h=i.width*i.height*l;let c;if(r&&(c=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),s){o=new Uint8Array(h);let C,v,b,A=0;const P=new Uint8Array(l);for(;t<h&&A<h;)if(C=e[t++],v=(C&127)+1,C&128){for(b=0;b<l;++b)P[b]=e[t++];for(b=0;b<v;++b)o.set(P,A+b*l);A+=l*v}else{for(v*=l,b=0;b<v;++b)o[A+b]=e[t++];A+=v}}else o=e.subarray(t,t+=r?i.width*i.height:h);let u,d,f,_,p,g;switch((i.flags&CN)>>vN){default:case yN:u=0,f=1,g=i.width,d=0,_=1,p=i.height;break;case bN:u=0,f=1,g=i.width,d=i.height-1,_=-1,p=-1;break;case RN:u=i.width-1,f=-1,g=-1,d=0,_=1,p=i.height;break;case AN:u=i.width-1,f=-1,g=-1,d=i.height-1,_=-1,p=-1;break}const x="_getImageData"+(n?"Grey":"")+i.pixel_size+"bits",T=FN[x](i,c,o,d,_,p,u,f,g);a.getEngine()._uploadDataToTextureDirectly(a,T)}function IN(a,e,t,i,s,r,n,o,l){const h=t,c=e,u=a.width,d=a.height;let f,_=0,p,g;const x=new Uint8Array(u*d*4);for(g=i;g!==r;g+=s)for(p=n;p!==l;p+=o,_++)f=h[_],x[(p+u*g)*4+3]=255,x[(p+u*g)*4+2]=c[f*3+0],x[(p+u*g)*4+1]=c[f*3+1],x[(p+u*g)*4+0]=c[f*3+2];return x}function PN(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d,f=0,_,p;const g=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(_=n;_!==l;_+=o,f+=2){d=h[f+0]+(h[f+1]<<8);const x=((d&31744)>>10)*255/31|0,T=((d&992)>>5)*255/31|0,S=(d&31)*255/31|0;g[(_+c*p)*4+0]=x,g[(_+c*p)*4+1]=T,g[(_+c*p)*4+2]=S,g[(_+c*p)*4+3]=d&32768?0:255}return g}function MN(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,_;const p=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(f=n;f!==l;f+=o,d+=3)p[(f+c*_)*4+3]=255,p[(f+c*_)*4+2]=h[d+0],p[(f+c*_)*4+1]=h[d+1],p[(f+c*_)*4+0]=h[d+2];return p}function DN(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,_;const p=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(f=n;f!==l;f+=o,d+=4)p[(f+c*_)*4+2]=h[d+0],p[(f+c*_)*4+1]=h[d+1],p[(f+c*_)*4+0]=h[d+2],p[(f+c*_)*4+3]=h[d+3];return p}function ON(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d,f=0,_,p;const g=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(_=n;_!==l;_+=o,f++)d=h[f],g[(_+c*p)*4+0]=d,g[(_+c*p)*4+1]=d,g[(_+c*p)*4+2]=d,g[(_+c*p)*4+3]=255;return g}function NN(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,_;const p=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(f=n;f!==l;f+=o,d+=2)p[(f+c*_)*4+0]=h[d+0],p[(f+c*_)*4+1]=h[d+0],p[(f+c*_)*4+2]=h[d+0],p[(f+c*_)*4+3]=h[d+1];return p}const FN={GetTGAHeader:i_,UploadContent:LS,_getImageData8bits:IN,_getImageData16bits:PN,_getImageData24bits:MN,_getImageData32bits:DN,_getImageDataGrey8bits:ON,_getImageDataGrey16bits:NN};class wN{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=i_(s);i(r.width,r.height,t.generateMipMaps,!1,()=>{LS(t,s)})}}H._TextureLoaders.push(new wN);class LN{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=_p.RGBE_ReadHeader(s),n=_p.RGBE_ReadPixels(s,r),o=r.width*r.height,l=new Float32Array(o*4);for(let h=0;h<o;h+=1)l[h*4]=n[h*3],l[h*4+1]=n[h*3+1],l[h*4+2]=n[h*3+2],l[h*4+3]=1;i(r.width,r.height,t.generateMipMaps,!1,()=>{const h=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,h._uploadDataToTextureDirectly(t,l)})}}H._TextureLoaders.push(new LN);function BN(){const a={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21};let e=null;onmessage=n=>{if(n.data.action==="init"){if(n.data.url)try{importScripts(n.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:n.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(n.data.action==="transcode"){const o=n.data.config,l=n.data.imageData,h=new BASIS.BasisFile(l),c=i(h);let u=n.data.ignoreSupportedFormats?null:t(n.data.config,c),d=!1;u===null&&(d=!0,u=c.hasAlpha?a.cTFBC3:a.cTFBC1);let f=!0;h.startTranscoding()||(f=!1);const _=[];for(let p=0;p<c.images.length&&f;p++){const g=c.images[p];if(o.loadSingleImage===void 0||o.loadSingleImage===p){let x=g.levels.length;o.loadMipmapLevels===!1&&(x=1);for(let T=0;T<x;T++){const S=g.levels[T],C=s(h,p,T,u,d);if(!C){f=!1;break}S.transcodedPixels=C,_.push(S.transcodedPixels.buffer)}}}h.close(),h.delete(),d&&(u=-1),f?postMessage({action:"transcode",success:f,id:n.data.id,fileInfo:c,format:u},_):postMessage({action:"transcode",success:f,id:n.data.id})}};function t(n,o){let l=null;return n.supportedCompressionFormats&&(n.supportedCompressionFormats.astc?l=a.cTFASTC_4x4:n.supportedCompressionFormats.bc7?l=a.cTFBC7:n.supportedCompressionFormats.s3tc?l=o.hasAlpha?a.cTFBC3:a.cTFBC1:n.supportedCompressionFormats.pvrtc?l=o.hasAlpha?a.cTFPVRTC1_4_RGBA:a.cTFPVRTC1_4_RGB:n.supportedCompressionFormats.etc2?l=a.cTFETC2:n.supportedCompressionFormats.etc1?l=a.cTFETC1:l=a.cTFRGB565),l}function i(n){const o=n.getHasAlpha(),l=n.getNumImages(),h=[];for(let u=0;u<l;u++){const d={levels:[]},f=n.getNumLevels(u);for(let _=0;_<f;_++){const p={width:n.getImageWidth(u,_),height:n.getImageHeight(u,_)};d.levels.push(p)}h.push(d)}return{hasAlpha:o,images:h}}function s(n,o,l,h,c){const u=n.getImageTranscodedSizeInBytes(o,l,h);let d=new Uint8Array(u);if(!n.transcodeImage(d,o,l,h,1,0))return null;if(c){const f=n.getImageWidth(o,l)+3&-4,_=n.getImageHeight(o,l)+3&-4;d=r(d,0,f,_)}return d}function r(n,o,l,h){const c=new Uint16Array(4),u=new Uint16Array(l*h),d=l/4,f=h/4;for(let _=0;_<f;_++)for(let p=0;p<d;p++){const g=o+8*(_*d+p);c[0]=n[g]|n[g+1]<<8,c[1]=n[g+2]|n[g+3]<<8,c[2]=(2*(c[0]&31)+1*(c[1]&31))/3|(2*(c[0]&2016)+1*(c[1]&2016))/3&2016|(2*(c[0]&63488)+1*(c[1]&63488))/3&63488,c[3]=(2*(c[1]&31)+1*(c[0]&31))/3|(2*(c[1]&2016)+1*(c[0]&2016))/3&2016|(2*(c[1]&63488)+1*(c[0]&63488))/3&63488;for(let x=0;x<4;x++){const T=n[g+4+x];let S=(_*4+x)*l+p*4;u[S++]=c[T&3],u[S++]=c[T>>2&3],u[S++]=c[T>>4&3],u[S++]=c[T>>6&3]}}return u}}function UN(a,e,t){return new Promise((i,s)=>{const r=n=>{n.data.action==="init"?(a.removeEventListener("message",r),i(a)):n.data.action==="error"&&s(n.data.error||"error initializing worker")};a.addEventListener("message",r),a.postMessage({action:"init",url:t?X.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}var sa;(function(a){a[a.cTFETC1=0]="cTFETC1",a[a.cTFETC2=1]="cTFETC2",a[a.cTFBC1=2]="cTFBC1",a[a.cTFBC3=3]="cTFBC3",a[a.cTFBC4=4]="cTFBC4",a[a.cTFBC5=5]="cTFBC5",a[a.cTFBC7=6]="cTFBC7",a[a.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",a[a.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",a[a.cTFASTC_4x4=10]="cTFASTC_4x4",a[a.cTFATC_RGB=11]="cTFATC_RGB",a[a.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",a[a.cTFRGBA32=13]="cTFRGBA32",a[a.cTFRGB565=14]="cTFRGB565",a[a.cTFBGR565=15]="cTFBGR565",a[a.cTFRGBA4444=16]="cTFRGBA4444",a[a.cTFFXT1_RGB=17]="cTFFXT1_RGB",a[a.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",a[a.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",a[a.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",a[a.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(sa||(sa={}));const ro={JSModuleURL:`${X._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${X._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},VN=(a,e)=>{let t;switch(a){case sa.cTFETC1:t=36196;break;case sa.cTFBC1:t=33776;break;case sa.cTFBC4:t=33779;break;case sa.cTFASTC_4x4:t=37808;break;case sa.cTFETC2:t=37496;break;case sa.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let W_=null,Ro=null,kN=0;const GN=!1,zN=()=>(W_||(W_=new Promise((a,e)=>{Ro?a(Ro):X.LoadFileAsync(X.GetBabylonScriptURL(ro.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${BN})()`],{type:"application/javascript"}));Ro=new Worker(i),UN(Ro,t,ro.JSModuleURL).then(a,e)}).catch(e)})),W_),mp=(a,e)=>{const t=a instanceof ArrayBuffer?new Uint8Array(a):a;return new Promise((i,s)=>{zN().then(()=>{const r=kN++,n=l=>{l.data.action==="transcode"&&l.data.id===r&&(Ro.removeEventListener("message",n),l.data.success?i(l.data):s("Transcode is not supported on this device"))};Ro.addEventListener("message",n);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),Ro.postMessage({action:"transcode",id:r,imageData:o,config:e,ignoreSupportedFormats:GN},[o.buffer])},r=>{s(r)})})},wd=(a,e)=>{var i,s;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;a.isCube&&(t=(s=e._gl)==null?void 0:s.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,a,!0)},gp=(a,e)=>{const t=a.getEngine();for(let i=0;i<e.fileInfo.images.length;i++){const s=e.fileInfo.images[i].levels[0];if(a._invertVScale=a.invertY,e.format===-1||e.format===sa.cTFRGB565)if(a.type=10,a.format=4,t._features.basisNeedsPOT&&(ge.Log2(s.width)%1!==0||ge.Log2(s.height)%1!==0)){const r=new Tt(t,et.Temp);a._invertVScale=a.invertY,r.type=10,r.format=4,r.width=s.width+3&-4,r.height=s.height+3&-4,wd(r,t),t._uploadDataToTextureDirectly(r,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0),t._rescaleTexture(r,a,t.scenes[0],t._getInternalFormat(4),()=>{t._releaseTexture(r),wd(a,t)})}else a._invertVScale=!a.invertY,a.width=s.width+3&-4,a.height=s.height+3&-4,a.samplingMode=2,wd(a,t),t._uploadDataToTextureDirectly(a,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0);else{a.width=s.width,a.height=s.height,a.generateMipMaps=e.fileInfo.images[i].levels.length>1;const r=mg.GetInternalFormatFromBasisFormat(e.format,t);a.format=r,wd(a,t),e.fileInfo.images[i].levels.forEach((n,o)=>{t._uploadCompressedDataToTextureDirectly(a,r,n.width,n.height,n.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(ge.Log2(a.width)%1!==0||ge.Log2(a.height)%1!==0)&&(X.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),a._cachedWrapU=k.CLAMP_ADDRESSMODE,a._cachedWrapV=k.CLAMP_ADDRESSMODE)}}},mg={JSModuleURL:ro.JSModuleURL,WasmModuleURL:ro.WasmModuleURL,GetInternalFormatFromBasisFormat:VN,TranscodeAsync:mp,LoadTextureFromTranscodeResult:gp};Object.defineProperty(mg,"JSModuleURL",{get:function(){return ro.JSModuleURL},set:function(a){ro.JSModuleURL=a}});Object.defineProperty(mg,"WasmModuleURL",{get:function(){return ro.WasmModuleURL},set:function(a){ro.WasmModuleURL=a}});class WN{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};mp(e,o).then(l=>{const h=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;gp(t,l),t.getEngine()._setCubeMapTextureParams(t,h),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}).catch(l=>{const h="Failed to transcode Basis file, transcoding may not be supported on this device";X.Warn(h),t.isReady=!0,r&&r(l)})}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};mp(e,r).then(n=>{const o=n.fileInfo.images[0].levels[0],l=n.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,n.format!==-1,()=>{gp(t,n)})}).catch(n=>{X.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),X.Warn(`Failed to transcode Basis file: ${n}`),i(0,0,!1,!1,()=>{},!0)})}}H._TextureLoaders.push(new WN);class vo extends oi{get isSupported(){var e;return((e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,s,r,n){const o=r&&r.generateMipMaps?r.generateMipMaps:!1,l=r&&r.generateDepthTexture?r.generateDepthTexture:!1,h=r&&r.depthTextureFormat?r.depthTextureFormat:15,c=!r||r.doNotChangeAspectRatio===void 0?!0:r.doNotChangeAspectRatio,u=r&&r.drawOnlyOnFirstAttachmentByDefault?r.drawOnlyOnFirstAttachmentByDefault:!1;if(super(e,t,s,o,c,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported){this.dispose();return}this._textureNames=n;const d=[],f=[],_=[],p=[],g=[],x=[],T=[],S=[];this._initTypes(i,d,f,_,p,g,x,T,S,r);const C=!r||r.generateDepthBuffer===void 0?!0:r.generateDepthBuffer,v=!r||r.generateStencilBuffer===void 0?!1:r.generateStencilBuffer;this._multiRenderTargetOptions={samplingModes:f,generateMipMaps:o,generateDepthBuffer:C,generateStencilBuffer:v,generateDepthTexture:l,depthTextureFormat:h,types:d,textureCount:i,useSRGBBuffers:_,formats:p,targetTypes:g,faceIndex:x,layerIndex:T,layerCounts:S,labels:n,label:e},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=u,i>0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,l,h,c){for(let u=0;u<e;u++)c&&c.types&&c.types[u]!==void 0?t.push(c.types[u]):t.push(c&&c.defaultType?c.defaultType:0),c&&c.samplingModes&&c.samplingModes[u]!==void 0?i.push(c.samplingModes[u]):i.push(k.BILINEAR_SAMPLINGMODE),c&&c.useSRGBBuffers&&c.useSRGBBuffers[u]!==void 0?s.push(c.useSRGBBuffers[u]):s.push(!1),c&&c.formats&&c.formats[u]!==void 0?r.push(c.formats[u]):r.push(5),c&&c.targetTypes&&c.targetTypes[u]!==void 0?n.push(c.targetTypes[u]):n.push(3553),c&&c.faceIndex&&c.faceIndex[u]!==void 0?o.push(c.faceIndex[u]):o.push(0),c&&c.layerIndex&&c.layerIndex[u]!==void 0?l.push(c.layerIndex[u]):l.push(0),c&&c.layerCounts&&c.layerCounts[u]!==void 0?h.push(c.layerCounts[u]):h.push(1)}_createInternaTextureIndexMapping(){const e={},t=[];if(!this._renderTarget)return t;const i=this._renderTarget.textures;for(let s=0;s<i.length;s++){const r=i[s];if(!r)continue;const n=e[r.uniqueId];n!==void 0?t[s]=n:e[r.uniqueId]=s}return t}_rebuild(e=!1,t=!1,i){if(this._count<1||e)return;const s=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),t&&(this._releaseTextures(),this._createTextures(i));const r=this._renderTarget.textures;for(let n=0;n<r.length;n++){const o=this._textures[n];s[n]!==void 0&&this._renderTarget.setTexture(r[s[n]],n),o._texture=r[n],o._texture&&(o._noMipmap=!o._texture.useMipMaps,o._useSRGBBuffer=o._texture._useSRGBBuffer)}this.samples!==1&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){const t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){const s=new k(null,this.getScene());e!=null&&e[i]&&(s.name=e[i]),s._texture=t[i],s._texture&&(s._noMipmap=!s._texture.useMipMaps,s._useSRGBBuffer=s._texture._useSRGBBuffer),this._textures.push(s)}}setInternalTexture(e,t,i=!0){var s;if(this.renderTarget&&(t===0&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new k(null,this.getScene()),this.textures[t].name=((s=this._textureNames)==null?void 0:s[t])??this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&this._multiRenderTargetOptions.targetTypes[t]!==-1)){let r=0;e.is2DArray?r=35866:e.isCube?r=34067:e.is3D?r=32879:r=3553,this._multiRenderTargetOptions.targetTypes[t]=r}}setLayerAndFaceIndex(e,t=-1,i=-1){!this.textures[e]||!this.renderTarget||(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e,!1),this._rebuild(!1,void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;const s=[],r=[],n=[],o=[],l=[],h=[],c=[],u=[];this._textureNames=i,this._initTypes(e,s,r,n,o,l,h,c,u,t),this._multiRenderTargetOptions.types=s,this._multiRenderTargetOptions.samplingModes=r,this._multiRenderTargetOptions.useSRGBBuffers=n,this._multiRenderTargetOptions.formats=o,this._multiRenderTargetOptions.targetTypes=l,this._multiRenderTargetOptions.faceIndex=h,this._multiRenderTargetOptions.layerIndex=c,this._multiRenderTargetOptions.layerCounts=u,this._multiRenderTargetOptions.labels=i,this._rebuild(!1,!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;const e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let s=e.length-1;s>=0;s--)this._textures[s]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}const HN="noisePixelShader",XN=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p)
{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);}
float interpolationNoise(vec2 p)
{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); 
return ym;}
float perlinNoise2D(float x,float y)
{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++)
{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;}
return sum;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);}
`;W.ShadersStore[HN]=XN;class ff extends $n{constructor(e,t=256,i=Ae.LastCreatedScene,s,r){super(e,t,"noise",i,s,r),this.time=0,this.brightness=.2,this.octaves=3,this.persistence=.8,this.animationSpeedFactor=1,this.autoClear=!1,this._updateShaderUniforms()}_updateShaderUniforms(){const e=this.getScene();e&&(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))}_getDefines(){return"#define OCTAVES "+(this.octaves|0)}render(e){this._updateShaderUniforms(),super.render(e)}serialize(){const e={};return e.customType="BABYLON.NoiseProceduralTexture",e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e}clone(){const e=this.getSize(),t=new ff(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.brightness=this.brightness,t.octaves=this.octaves,t.persistence=this.persistence,t.animationSpeedFactor=this.animationSpeedFactor,t.time=this.time,t}static Parse(e,t){const i=new ff(e.name,e.size,t,void 0,e.generateMipMaps);return i.brightness=e.brightness,i.octaves=e.octaves,i.persistence=e.persistence,i.animationSpeedFactor=e.animationSpeedFactor,i.time=e.time??0,i}}V("BABYLON.NoiseProceduralTexture",ff);class gg extends Hi{constructor(e,t,i,s=5,r=0,n=!1,o=!1,l=3,h=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,i,s,r,n,o,l,h)}update(e,t,i,s,r=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,s,r)}updateRGBDAsync(e,t=null,i=.8,s=0){return wI(this._texture,e,t,i,s).then(()=>{})}clone(){return _e.Clone(()=>{const e=this.getScene(),t=this._texture,i=new gg(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===et.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i},this)}}class gi extends Ll{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof gi&&e._blockName===this._blockName?Pr.Compatible:Pr.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class YN extends Pe{constructor(e){super(e,B.Vertex),this.registerInput("matricesIndices",R.Vector4),this.registerInput("matricesWeights",R.Vector4),this.registerInput("matricesIndicesExtra",R.Vector4,!0),this.registerInput("matricesWeightsExtra",R.Vector4,!0),this.registerInput("world",R.Matrix),this.registerOutput("output",R.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="matricesIndices"&&t(s));i||(i=new it("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="matricesWeights"&&t(s));i||(i=new it("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.World&&t(s));i||(i=new it("world"),i.setAsSystemValue(nt.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Ku(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&UE(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0
`,e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName} * ${i};
`,e.compilationString+=`#else
`,e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName};
`,e.compilationString+=`#endif
`,this}}V("BABYLON.BonesBlock",YN);class $N extends Pe{constructor(e){super(e,B.Vertex),this.registerInput("world0",R.Vector4),this.registerInput("world1",R.Vector4),this.registerInput("world2",R.Vector4),this.registerInput("world3",R.Vector4),this.registerInput("world",R.Matrix,!0),this.registerOutput("output",R.Matrix),this.registerOutput("instanceID",R.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world0"&&t(s));i||(i=new it("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world1"&&t(s));i||(i=new it("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world2"&&t(s));i||(i=new it("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world3"&&t(s));i||(i=new it("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world"&&t(s));i||(i=new it("world"),i.setAsSystemValue(nt.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!(r!=null&&r.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(r!=null&&r.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,l=this.world3;return e.compilationString+=`#ifdef INSTANCES
`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${l.associatedVariableName});
`,e.compilationString+=`#ifdef THIN_INSTANCES
`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};
`,e.compilationString+=`#endif
`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(s,e)+` = float(gl_InstanceID);
`:e.compilationString+=this._declareOutput(s,e)+` = 0.0;
`,e.compilationString+=`#else
`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};
`,e.compilationString+=this._declareOutput(s,e)+` = 0.0;
`,e.compilationString+=`#endif
`,this}}V("BABYLON.InstancesBlock",$N);class BS extends Pe{constructor(e){super(e,B.Vertex),this.registerInput("position",R.Vector3),this.registerInput("normal",R.Vector3),this.registerInput("tangent",R.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(R.Color4|R.Vector4|R.Vector3),this.registerInput("uv",R.Vector2),this.registerOutput("positionOutput",R.Vector3),this.registerOutput("normalOutput",R.Vector3),this.registerOutput("tangentOutput",R.Vector4),this.registerOutput("uvOutput",R.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new it("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new it("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&t(s));i||(i=new it("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new it("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const s=e.morphTargetManager;s!=null&&s.isUsingTextureForTargets&&(s.numMaxInfluencers||s.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&VE(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Sa(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,l=this.uv,h=this.positionOutput,c=this.normalOutput,u=this.tangentOutput,d=this.uvOutput,f=e,_=s.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,g=p&&p.supportsNormals&&s.NORMAL,x=p&&p.supportsTangents&&s.TANGENT,T=p&&p.supportsUVs&&s.UV1;let S="";if(p!=null&&p.isUsingTextureForTargets&&_>0&&(S+=`float vertexID;
`),S+=`#ifdef MORPHTARGETS
`,p!=null&&p.isUsingTextureForTargets)S+=`for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) {
`,S+=`if (i >= morphTargetCount) break;
`,S+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;
`,S+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[i];
`,S+=`vertexID += 1.0;
`,g&&(S+=`#ifdef MORPHTARGETS_NORMAL
`,S+=`${c.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[i];
`,S+=`vertexID += 1.0;
`,S+=`#endif
`),T&&(S+=`#ifdef MORPHTARGETS_UV
`,S+=`${d.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${l.associatedVariableName}) * morphTargetInfluences[i];
`,S+=`vertexID += 1.0;
`,S+=`#endif
`),x&&(S+=`#ifdef MORPHTARGETS_TANGENT
`,S+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[i];
`,o.type===R.Vector4?S+=`${u.associatedVariableName}.w = ${o.associatedVariableName}.w;
`:S+=`${u.associatedVariableName}.w = 1.;
`,S+=`#endif
`),S+=`}
`;else for(let C=0;C<_;C++)S+=`${h.associatedVariableName} += (position${C} - ${r.associatedVariableName}) * morphTargetInfluences[${C}];
`,g&&(S+=`#ifdef MORPHTARGETS_NORMAL
`,S+=`${c.associatedVariableName} += (normal${C} - ${n.associatedVariableName}) * morphTargetInfluences[${C}];
`,S+=`#endif
`),T&&(S+=`#ifdef MORPHTARGETS_UV
`,S+=`${d.associatedVariableName}.xy += (uv_${C} - ${l.associatedVariableName}.xy) * morphTargetInfluences[${C}];
`,S+=`#endif
`),x&&(S+=`#ifdef MORPHTARGETS_TANGENT
`,S+=`${u.associatedVariableName}.xyz += (tangent${C} - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${C}];
`,o.type===R.Vector4?S+=`${u.associatedVariableName}.w = ${o.associatedVariableName}.w;
`:S+=`${u.associatedVariableName}.w = 1.;
`,S+=`#endif
`);if(S+=`#endif
`,f.compilationString=f.compilationString.replace(this._repeatableContentAnchor,S),_>0)for(let C=0;C<_;C++)f.attributes.push(y.PositionKind+C),g&&f.attributes.push(y.NormalKind+C),x&&f.attributes.push(y.TangentKind+C),T&&f.attributes.push(y.UVKind+"_"+C)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,l=this.tangentOutput,h=this.uvOutput,c=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetCount"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",c),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",c,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName};
`,e.compilationString+=`#ifdef NORMAL
`,e.compilationString+=`${this._declareOutput(o,e)} = ${i.associatedVariableName};
`,e.compilationString+=`#else
`,e.compilationString+=`${this._declareOutput(o,e)} = vec3(0., 0., 0.);
`,e.compilationString+=`#endif
`,e.compilationString+=`#ifdef TANGENT
`,e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName};
`,e.compilationString+=`#else
`,e.compilationString+=`${this._declareOutput(l,e)} = vec4(0., 0., 0., 0.);
`,e.compilationString+=`#endif
`,e.compilationString+=`#ifdef UV1
`,e.compilationString+=`${this._declareOutput(h,e)} = ${r.associatedVariableName};
`,e.compilationString+=`#else
`,e.compilationString+=`${this._declareOutput(h,e)} = vec2(0., 0.);
`,e.compilationString+=`#endif
`,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}V("BABYLON.MorphTargetsBlock",BS);class KN extends Pe{constructor(e){super(e,B.Vertex),this.registerInput("worldPosition",R.Vector4,!1,B.Vertex),this.registerOutput("direction",R.Vector3),this.registerOutput("color",R.Color3),this.registerOutput("intensity",R.Float),this.registerOutput("shadowBias",R.Float),this.registerOutput("shadowNormalBias",R.Float),this.registerOutput("shadowDepthScale",R.Float),this.registerOutput("shadowDepthRange",R.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const o=s;e.setFloat2(this._lightShadowExtraUniformName,o.getDepthMinZ(r.activeCamera),o.getDepthMinZ(r.activeCamera)+o.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof Pc),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,l=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName}
`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});
`,e.compilationString+=`#else
`,e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName};
`,e.compilationString+=`#endif
`,e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb;
`,e.compilationString+=this._declareOutput(s,e)+` = ${this._lightColorUniformName}.a;
`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${this._lightShadowUniformName}.x;
`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y;
`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}.z;
`)),l.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(l,e)+` = ${this._lightShadowUniformName};
`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}V("BABYLON.LightInformationBlock",KN);class US extends Pe{constructor(e){super(e,B.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",R.AutoDetect),this.registerOutput("output",R.Color4),this.registerOutput("rgb",R.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Color4|R.Vector3|R.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var r;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),(r=t.connectedPoint)!=null&&r.isConnected&&(t.connectedPoint.type===R.Color4||t.connectedPoint.type===R.Vector4?e.compilationString+=`${this._declareOutput(i,e)} = ${t.associatedVariableName};
`:e.compilationString+=`${this._declareOutput(i,e)} = vec4(${t.associatedVariableName}, 1.0);
`,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS
`,this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);
`),e.compilationString+=`#else
`,e.compilationString+=`#ifdef IMAGEPROCESSING
`,this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);
`),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName});
`,e.compilationString+=`#endif
`,e.compilationString+=`#endif
`,this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz;
`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};
`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}E([Le("Convert input to linear space",Ne.Boolean,"ADVANCED")],US.prototype,"convertInputToLinearSpace",void 0);V("BABYLON.ImageProcessingBlock",US);class Mc extends Pe{constructor(e){super(e,B.Fragment,!0),this.registerInput("normal",R.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(R.Color4|R.Vector4|R.Vector3),this.registerInput("tangent",R.Vector4,!1),this.registerInput("world",R.Matrix,!1),this.registerOutput("TBN",R.Object,B.Fragment,new gi("TBN",this,si.Output,Mc,"TBNBlock")),this.registerOutput("row0",R.Vector3,B.Fragment),this.registerOutput("row1",R.Vector3,B.Fragment),this.registerOutput("row2",R.Vector3,B.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return B.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.isSystemValue&&s.systemValue===nt.World&&t(s));i||(i=new it("world"),i.setAsSystemValue(nt.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new it("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&s.type===R.Vector4&&t(s));i||(i=new it("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var h,c,u,d;const s=this.normal,r=this.tangent;let n=s.isConnected;(h=s.connectInputBlock)!=null&&h.isAttribute&&!e.isVerticesDataPresent((c=s.connectInputBlock)==null?void 0:c.name)&&(n=!1);let o=r.isConnected;(u=r.connectInputBlock)!=null&&u.isAttribute&&!e.isVerticesDataPresent((d=r.connectInputBlock)==null?void 0:d.name)&&(o=!1);const l=n&&o;i.setValue("TBNBLOCK",l,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,l=this.row2;return e.target===B.Fragment&&(e.compilationString+=`
                // ${this.name}
                vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;
                vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);
                vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;
                mat3 ${r.associatedVariableName} = mat3(${s.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);
            `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);
`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);
`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = vec3(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);
`),e.sharedData.blocksWithDefines.push(this)),this}}V("BABYLON.TBNBlock",Mc);class id extends Pe{constructor(e){super(e,B.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",R.Vector4,!1),this.registerInput("worldNormal",R.Vector4,!1),this.registerInput("worldTangent",R.Vector4,!0),this.registerInput("uv",R.Vector2,!1),this.registerInput("normalMapColor",R.Color3,!1),this.registerInput("strength",R.Float,!1),this.registerInput("viewDirection",R.Vector3,!0),this.registerInput("parallaxScale",R.Float,!0),this.registerInput("parallaxHeight",R.Float,!0),this.registerInput("TBN",R.Object,!0,B.VertexAndFragment,new gi("TBN",this,si.Input,Mc,"TBNBlock")),this.registerInput("world",R.Matrix,!0),this.registerOutput("output",R.Vector4),this.registerOutput("uvOffset",R.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new it("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new it("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),h=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",c=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`
#if !defined(NORMALXYSCALE)
1.0/
#endif
${e._emitFloat(this.strength.connectInputBlock.value)}`:`
#if !defined(NORMALXYSCALE)
1.0/
#endif
${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d={search:/varying mat3 vTBN;/g,replace:""},f={search:/uniform mat4 normalMatrix;/g,replace:""},_=this.TBN;_.isConnected?e.compilationString+=`
            #ifdef TBNBLOCK
            mat3 vTBN = ${_.associatedVariableName};
            #endif
            `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz);
`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz);
`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};
`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);
`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,d,f]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:`#define inline
vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const p=!l||!o?this.normalMapColor.associatedVariableName:`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`;return e.compilationString+=this._declareOutput(this.output,e)+` = vec4(0.);
`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${p}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${p}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${l&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${l?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:c},{search:/vBumpInfos.z/g,replace:h},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:l?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};
`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};
`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};
`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};
`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}E([Le("Invert X axis",Ne.Boolean,"PROPERTIES",{notifiers:{update:!1}})],id.prototype,"invertX",void 0);E([Le("Invert Y axis",Ne.Boolean,"PROPERTIES",{notifiers:{update:!1}})],id.prototype,"invertY",void 0);E([Le("Use parallax occlusion",Ne.Boolean)],id.prototype,"useParallaxOcclusion",void 0);E([Le("Object Space Mode",Ne.Boolean,"PROPERTIES",{notifiers:{update:!1}})],id.prototype,"useObjectSpaceNormalMap",void 0);V("BABYLON.PerturbNormalBlock",id);class jN extends Pe{constructor(e){super(e,B.Fragment,!0),this.registerInput("value",R.Float,!0),this.registerInput("cutoff",R.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,!(!this.cutoff.isConnected||!this.value.isConnected))return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;
`,this}}V("BABYLON.DiscardBlock",jN);class qN extends Pe{constructor(e){super(e,B.Fragment),this.registerOutput("output",R.Float,B.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===B.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0;
`,this}}V("BABYLON.FrontFacingBlock",qN);class QN extends Pe{constructor(e){super(e,B.Fragment),this.registerInput("input",R.AutoDetect,!1),this.registerOutput("dx",R.BasedOnInput),this.registerOutput("dy",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName});
`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});
`),this}}V("BABYLON.DerivativeBlock",QN);class ZN extends Pe{constructor(e){super(e,B.Fragment),this.registerOutput("xy",R.Vector2,B.Fragment),this.registerOutput("xyz",R.Vector3,B.Fragment),this.registerOutput("xyzw",R.Vector4,B.Fragment),this.registerOutput("x",R.Float,B.Fragment),this.registerOutput("y",R.Float,B.Fragment),this.registerOutput("z",R.Float,B.Fragment),this.registerOutput("w",R.Float,B.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name};
`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===B.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}V("BABYLON.FragCoordBlock",ZN);class JN extends Pe{constructor(e){super(e,B.Fragment),this.registerOutput("xy",R.Vector2,B.Fragment),this.registerOutput("x",R.Float,B.Fragment),this.registerOutput("y",R.Float,B.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};
`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===B.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}V("BABYLON.ScreenSizeBlock",JN);class eF extends Pe{constructor(e){super(e,B.Fragment),this.registerInput("vector",R.AutoDetect),this.registerInput("worldViewProjection",R.Matrix),this.registerOutput("output",R.Vector2),this.registerOutput("x",R.Float),this.registerOutput("y",R.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.WorldViewProjection&&t(s));i||(i=new it("worldViewProjection"),i.setAsSystemValue(nt.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case R.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0);
`;break;case R.Vector4:e.compilationString+=`vec4 ${r} = ${s} * ${t.associatedVariableName};
`;break}return e.compilationString+=`${r}.xy /= ${r}.w;`,e.compilationString+=`${r}.xy = ${r}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r}.xy;
`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;
`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;
`),this}}V("BABYLON.ScreenSpaceBlock",eF);class tF extends Pe{constructor(e){super(e,B.Fragment),this.registerInput("input",R.Vector2),this.registerInput("strength",R.Float),this.registerInput("center",R.Vector2),this.registerInput("offset",R.Vector2),this.registerOutput("output",R.Vector2),this.registerOutput("x",R.Float),this.registerOutput("y",R.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new it("center");e.value=new Z(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new it("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new it("offset");e.value=new Z(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=`
            vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};
            float ${i} = ${this.strength.associatedVariableName} * length(${t});
            float ${s} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;
            float ${r} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;
            vec2 ${n} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);
        `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n};
`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x;
`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y;
`),this}}V("BABYLON.TwirlBlock",tF);class s_ extends Pe{constructor(e){super(e,B.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",R.Float),this.registerInput("worldPosition",R.Vector3),this.registerInput("worldNormal",R.Vector3),this.registerInput("worldTangent",R.AutoDetect,!0),this.registerOutput("output",R.Vector4),this.registerOutput("xyz",R.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];!this.generateInWorldSpace&&!this.worldTangent.isConnected&&O.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":`
            vec3 biTangent = cross(normal, tangent);
            mat3 TBN = mat3(tangent, biTangent, normal);
            `,s=this.generateInWorldSpace?"":`
            result = TBN * result;
            result = result * vec3(0.5) + vec3(0.5);
            `,r=`
            vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {
                ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}
                ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}
                ${i}
                vec3 worlddX = dFdx(position);
                vec3 worlddY = dFdy(position);
                vec3 crossX = cross(normal, worlddX);
                vec3 crossY = cross(normal, worlddY);
                float d = abs(dot(crossY, worlddX));
                vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));
                inToNormal.y *= -1.0;
                vec3 result = normalize((d * normal) - inToNormal);
                ${s}
                return vec4(result, 0.);
            }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",r,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});
`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;
`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};
`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};
`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};
`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}E([Le("Generate in world space instead of tangent space",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],s_.prototype,"generateInWorldSpace",void 0);E([Le("Force normalization for the worldNormal input",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],s_.prototype,"automaticNormalizationNormal",void 0);E([Le("Force normalization for the worldTangent input",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],s_.prototype,"automaticNormalizationTangent",void 0);V("BABYLON.HeightToNormalBlock",s_);class iF extends Pe{constructor(e){super(e,B.Fragment,!0),this.registerInput("depth",R.Float,!0),this.registerInput("worldPos",R.Vector4,!0),this.registerInput("viewProjection",R.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName};
`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`
                vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};
                float v = p.z / p.w;
                #ifndef IS_NDC_HALF_ZRANGE
                    v = v * 0.5 + 0.5;
                #endif
                gl_FragDepth = v;
    
            `:O.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}V("BABYLON.FragDepthBlock",iF);class sF extends Pe{constructor(e){super(e,B.Fragment),this.registerInput("worldPosition",R.Vector4,!1),this.registerInput("viewProjection",R.Matrix,!1),this.registerInput("worldNormal",R.AutoDetect,!0),this.registerOutput("depth",R.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};
`,e.compilationString+=`vec3 vPositionWSM;
`,e.compilationString+=`float vDepthMetricSM = 0.0;
`,e.compilationString+=`float zSM;
`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;
`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;
`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=`
            #if SM_DEPTHTEXTURE == 1
                #ifdef IS_NDC_HALF_ZRANGE
                    gl_FragDepth = (clipPos.z / clipPos.w);
                #else
                    gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;
                #endif
            #endif
        `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);
`,this}}V("BABYLON.ShadowMapBlock",sF);class rF extends Pe{constructor(e){super(e,B.Fragment,!0),this.registerInput("viewDepth",R.Float,!0),this.registerInput("worldPosition",R.AutoDetect,!0),this.registerInput("viewNormal",R.AutoDetect,!0),this.registerInput("reflectivity",R.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4|R.Color3|R.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r
`,e.compilationString+=`#ifdef PREPASS_DEPTH\r
`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r
`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`,e.compilationString+=`#endif\r
`,e.compilationString+=`#ifdef PREPASS_POSITION\r
`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===R.Vector4?t.associatedVariableName+".a":"1.0"});\r
`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`,e.compilationString+=`#endif\r
`,e.compilationString+=`#ifdef PREPASS_NORMAL\r
`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===R.Vector4?i.associatedVariableName+".a":"1.0"});\r
`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`,e.compilationString+=`#endif\r
`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r
`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===R.Vector4?r.associatedVariableName+".a":"1.0"});\r
`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r
`,e.compilationString+=`#endif\r
`,e.compilationString+=`#endif\r
`,this}}V("BABYLON.PrePassOutputBlock",rF);class nF extends Pe{constructor(e){super(e,B.VertexAndFragment,!1),this.registerInput("worldPosition",R.Vector4,!1,B.Vertex),this.registerInput("view",R.Matrix,!1,B.Vertex),this.registerInput("input",R.AutoDetect,!1,B.Fragment),this.registerInput("fogColor",R.AutoDetect,!1,B.Fragment),this.registerOutput("output",R.Color3,B.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.View&&t(s));i||(i=new it("view"),i.setAsSystemValue(nt.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.FogColor&&t(s));i||(i=new it("fogColor",void 0,R.Color3),i.setAsSystemValue(nt.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&BE(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===B.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,s=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const r=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG
`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});
`,e.compilationString+=this._declareOutput(r,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${s.associatedVariableName}.rgb;
`,e.compilationString+=`#else
${this._declareOutput(r,e)} =  ${i.associatedVariableName}.rgb;
`,e.compilationString+=`#endif
`}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;
`}return this}}V("BABYLON.FogBlock",nF);class xp extends Pe{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,O.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?B.Fragment:B.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?B.Fragment:B.Vertex}constructor(e){super(e,B.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",R.Vector4,!1,B.Vertex),this.registerInput("worldNormal",R.Vector4,!1,B.Fragment),this.registerInput("cameraPosition",R.Vector3,!1,B.Fragment),this.registerInput("glossiness",R.Float,!0,B.Fragment),this.registerInput("glossPower",R.Float,!0,B.Fragment),this.registerInput("diffuseColor",R.Color3,!0,B.Fragment),this.registerInput("specularColor",R.Color3,!0,B.Fragment),this.registerInput("view",R.Matrix,!0),this.registerOutput("diffuseOutput",R.Color3,B.Fragment),this.registerOutput("specularOutput",R.Color3,B.Fragment),this.registerOutput("shadow",R.Float,B.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.CameraPosition&&t(s));i||(i=new it("cameraPosition"),i.setAsSystemValue(nt.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(!this.light)qu(s,e,i,!0,t.maxSimultaneousLights);else{const r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};vm(s,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r<t.maxSimultaneousLights&&i["LIGHT"+r];r++){const n=e.uniforms.indexOf("vLightData"+r)>=0;Am(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Em(this.light,this._lightId,s,e,!0):ju(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};
`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};
`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};
`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==B.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let s=i.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${s};
`,t),e.compilationString+=`${s} = ${i.associatedVariableName}.xyz;
`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):s="v_"+s+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${s});
`),e.compilationString+=`lightingInfo info;
`,e.compilationString+=`float shadow = 1.;
`,e.compilationString+=`float aggShadow = 0.;
`,e.compilationString+=`float numLights = 0.;
`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};
`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.);
`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.);
`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;
`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:s+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${s}.xyz`}),this._lightId===0&&(e.compilationString+=`aggShadow = aggShadow / numLights;
`);const r=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(r,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};
`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};
`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow;
`),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}E([Le("Generate only fragment code",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:xp._OnGenerateOnlyFragmentCodeChanged}})],xp.prototype,"generateOnlyFragmentCode",void 0);V("BABYLON.LightBlock",xp);class Cn extends Pe{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Ae.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,B.VertexAndFragment),this.registerOutput("source",R.Object,B.VertexAndFragment,new gi("source",this,si.Output,Cn,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===B.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`),e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ei.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=k.Parse(e.texture,t,i))}}V("BABYLON.ImageSourceBlock",Cn);class _f extends Pe{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)==null?void 0:e.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Ae.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _IsPrePassTextureBlock(e){return(e==null?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return _f._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!_f._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??Ae.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??Ae.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?B.Fragment:B.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",R.AutoDetect,!1,B.VertexAndFragment),this.registerInput("source",R.Object,!0,B.VertexAndFragment,new gi("source",this,si.Input,Cn,"ImageSourceBlock")),this.registerInput("layer",R.Float,!0),this.registerInput("lod",R.Float,!0),this.registerOutput("rgba",R.Color4,B.Neutral),this.registerOutput("rgb",R.Color3,B.Neutral),this.registerOutput("r",R.Float,B.Neutral),this.registerOutput("g",R.Float,B.Neutral),this.registerOutput("b",R.Float,B.Neutral),this.registerOutput("a",R.Float,B.Neutral),this.registerOutput("level",R.Float,B.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector2|R.Vector3|R.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return B.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return B.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===B.Fragment)return B.Fragment;if(e.target===B.Vertex)return B.VertexAndFragment;if(e.target===B.Neutral||e.target===B.VertexAndFragment){const t=e.ownerBlock;if(t.target===B.Fragment)return B.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return B.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===Xs.PostProcess){const i=e.getBlockByPredicate(s=>s.name==="uv"&&t(s));i&&i.connectTo(this)}else{const i=e.mode===Xs.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name===i&&t(r));s||(s=new it("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&this._mainUVDefineName!==void 0&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),i[this._mainUVDefineName]==null&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return this._isSourcePrePass?!0:!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==B.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName}
`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));
`,e.compilationString+=`#elif defined(${this._mainUVDefineName})
`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;
`,e.compilationString+=`#endif
`,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name,!0)}}_getUVW(e){var s,r;let t=e;if(((r=(s=this._texture)==null?void 0:s._texture)==null?void 0:r.is2DArray)??!1){const n=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${n})`}return t}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}
`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});
`,e.compilationString+=`#elif defined(${this._mainUVDefineName})
`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix});
`,e.compilationString+=`#endif
`}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===B.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix});
`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName}
                    ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});
                    #endif
                `),e.compilationString+=`#ifdef ${this._gammaDefineName}
                ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});
                #endif
            `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===B.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`,this._generateConversionCode(e,t,i);return}let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r};
`,this._generateConversionCode(e,t,i)}_buildBlock(e){var i,s,r,n;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===B.Vertex||this._fragmentOnly||e.target===B.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===B.Fragment||this._isMixed&&e.target===B.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(s=(i=this._texture)==null?void 0:i._texture)!=null&&s.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==B.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((n=(r=this._texture)==null?void 0:r._texture)!=null&&n.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const o of this._outputs)o.hasEndpoints&&o.name!=="level"&&this._writeOutput(e,o,o.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};
`,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Ei.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=k.Parse(e.texture,t,i))}}V("BABYLON.TextureBlock",_f);class Mu extends Pe{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Ae.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?B.Fragment:B.VertexAndFragment)}constructor(e){super(e,B.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new it("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.World&&t(s));i||(i=new it("world"),i.setAsSystemValue(nt.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.View&&t(s));i||(i=new it("view"),i.setAsSystemValue(nt.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();!s||!s.getTextureMatrix||(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,s.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,s.coordinatesMode===5,!0),i.setValue(this._defineCubicName,s.coordinatesMode===3||s.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",s.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,s.coordinatesMode===1,!0),i.setValue(this._definePlanarName,s.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,s.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,s.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,s.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,s.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(!(!i||!r)&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const n=r;e.setVector3(this._reflectionPositionName,n.boundingBoxPosition),e.setVector3(this._reflectionSizeName,n.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===B.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};
`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}
`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;
`,t+=`#endif
`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})
`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));
`,t+=`#endif
`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}
`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};
`,e._samplerDeclaration+=`#else
`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};
`,e._samplerDeclaration+=`#endif
`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,l=`${this.cameraPosition.associatedVariableName}`,h=`${this.view.associatedVariableName}`;e+=".xyz";let c=`
            #ifdef ${this._defineMirroredEquirectangularFixedName}
                vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});
            #endif

            #ifdef ${this._defineEquirectangularFixedName}
                vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});
            #endif

            #ifdef ${this._defineEquirectangularName}
                vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${l}.xyz, ${r});
            #endif

            #ifdef ${this._defineSphericalName}
                vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${h}, ${r});
            #endif

            #ifdef ${this._definePlanarName}
                vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${l}.xyz, ${r});
            #endif

            #ifdef ${this._defineCubicName}
                #ifdef ${this._defineLocalCubicName}
                    vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${l}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});
                #else
                vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${l}.xyz, ${r});
                #endif
            #endif

            #ifdef ${this._defineProjectionName}
                vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${h}, ${r});
            #endif

            #ifdef ${this._defineSkyboxName}
                vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});
            #endif

            #ifdef ${this._defineExplicitName}
                vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);
            #endif
`;return s||(c+=`#ifdef ${this._defineOppositeZ}
                ${this._reflectionVectorName}.z *= -1.0;
            #endif
`),i||(c+=`
                #ifdef ${this._define3DName}
                    vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};
                #else
                    vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;
                    #ifdef ${this._defineProjectionName}
                        ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;
                    #endif
                    ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;
                #endif
`),c}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let s=`${"vec"+(t.length===0?"4":t.length-1)} ${this._reflectionColorName};
            #ifdef ${this._define3DName}
`;return e?s+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};
`:s+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};
`,s+=`
            #else
`,e?s+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};
`:s+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};
`,s+=`#endif
`,s}writeOutputs(e,t){let i="";if(e.target===B.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};
`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});
`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);
`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ei.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Hi.Parse(e.texture,t,i):this.texture=k.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}E([Le("Generate only fragment code",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Mu._OnGenerateOnlyFragmentCodeChanged}})],Mu.prototype,"generateOnlyFragmentCode",void 0);V("BABYLON.ReflectionTextureBaseBlock",Mu);class aF extends Mu{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,O.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,O.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?B.Fragment:B.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?B.Fragment:B.Vertex}constructor(e){super(e),this.registerInput("position",R.AutoDetect,!1,B.Vertex),this.registerInput("worldPosition",R.Vector4,!1,B.Vertex),this.registerInput("worldNormal",R.Vector4,!1,B.Fragment),this.registerInput("world",R.Matrix,!1,B.Vertex),this.registerInput("cameraPosition",R.Vector3,!1,B.Fragment),this.registerInput("view",R.Matrix,!1,B.Fragment),this.registerOutput("rgb",R.Color3,B.Fragment),this.registerOutput("rgba",R.Color4,B.Fragment),this.registerOutput("r",R.Float,B.Fragment),this.registerOutput("g",R.Float,B.Fragment),this.registerOutput("b",R.Float,B.Fragment),this.registerOutput("a",R.Float,B.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.CameraPosition&&t(s));i||(i=new it("cameraPosition"),i.setAsSystemValue(nt.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==B.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});
`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}V("BABYLON.ReflectionTextureBlock",aF);class r_ extends Pe{constructor(e){super(e,B.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",R.AutoDetect,!1,B.VertexAndFragment),this.registerOutput("depth",R.Float,B.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector2|R.Vector3|R.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?B.VertexAndFragment:B.Fragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===R.Vector3?"3":t.type===R.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;
`,!!this._outputs.some(i=>i.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===B.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);
`;return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);
`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});
`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===B.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`;return}if(this.uv.ownerBlock.target===B.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};
`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==B.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(t=>t.isConnectedInFragmentShader)){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}E([Le("Use non linear depth",Ne.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],r_.prototype,"useNonLinearDepth",void 0);E([Le("Store Camera space Z",Ne.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],r_.prototype,"storeCameraSpaceZ",void 0);E([Le("Force 32 bits float",Ne.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:a=>a==null?void 0:a.disableDepthRenderer()}})],r_.prototype,"force32itsFloat",void 0);V("BABYLON.SceneDepthBlock",r_);class oF extends Pe{constructor(e){super(e,B.VertexAndFragment,!0),this.registerInput("worldPosition",R.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return B.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),l=!!(t.clipPlane4??s.clipPlane4),h=!!(t.clipPlane5??s.clipPlane5),c=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",l,!0),i.setValue("CLIPPLANE5",h,!0),i.setValue("CLIPPLANE6",c,!0)}bind(e,t,i){if(!i)return;const s=i.getScene();Gr(e,t,s)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==B.Fragment){const i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}V("BABYLON.ClipPlanesBlock",oF);class lF extends Pe{get texture(){return null}set texture(e){}constructor(e,t=B.VertexAndFragment){super(e,t,!1),this.registerOutput("position",R.Object,B.VertexAndFragment,new gi("position",this,si.Output,Cn,"ImageSourceBlock")),this.registerOutput("depth",R.Object,B.VertexAndFragment,new gi("depth",this,si.Output,Cn,"ImageSourceBlock")),this.registerOutput("normal",R.Object,B.VertexAndFragment,new gi("normal",this,si.Output,Cn,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==B.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const s=t.getScene().enablePrePassRenderer();if(!s)return;const r=s.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[s.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[s.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[s.getIndex(6)]))}}V("BABYLON.PrePassTextureBlock",lF);class hF extends Pe{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==B.VertexAndFragment)return t.target;if(e.connectedPoint.target!==B.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,B.Neutral),this._endpoints=[],this.registerInput("input",R.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)t.indexOf(s)===-1&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}V("BABYLON.NodeMaterialTeleportInBlock",hF);class cF extends Pe{constructor(e){super(e,B.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",R.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName};
`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});
`),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}V("BABYLON.NodeMaterialTeleportOutBlock",cF);class uF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(R.Float),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};
`,this}}V("BABYLON.AddBlock",uF);class dF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.AutoDetect),this.registerInput("factor",R.Float),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};
`,this}}V("BABYLON.ScaleBlock",dF);class xg extends Pe{constructor(e){super(e,B.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});
`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};
`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};
`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}E([Le("Minimum",Ne.Float)],xg.prototype,"minimum",void 0);E([Le("Maximum",Ne.Float)],xg.prototype,"maximum",void 0);V("BABYLON.ClampBlock",xg);class fF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[0].excludedConnectionPointTypes.push(R.Vector2),this._inputs[1].excludedConnectionPointTypes.push(R.Float),this._inputs[1].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].excludedConnectionPointTypes.push(R.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);
`,this}}V("BABYLON.CrossBlock",fF);class _F extends Pe{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),this._outputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),e._emitFunction(i,t,""),this._outputs.forEach(r=>{e.compilationString+=this._declareOutput(r,e)+`;
`}),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach((r,n)=>{var o,l;n>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(r.name)!==-1?e.compilationString+=((l=(o=r.connectedPoint)==null?void 0:o.ownerBlock)==null?void 0:l.samplerName)??r.associatedVariableName:e.compilationString+=r.associatedVariableName,s=!0}),this._outputs.forEach((r,n)=>{(n>0||s)&&(e.compilationString+=", "),e.compilationString+=r.associatedVariableName}),e.compilationString+=`);
`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};
`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,s;this._options=e,this._code=e.code.join(`
`)+`
`,this.name=this.name||e.name,this.target=B[e.target],(t=e.inParameters)==null||t.forEach((r,n)=>{const o=R[r.type];r.type==="sampler2D"||r.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(r.name),this.registerInput(r.name,R.Object,!0,B.VertexAndFragment,new gi(r.name,this,si.Input,Cn,"ImageSourceBlock"))):this.registerInput(r.name,o),Object.defineProperty(this,r.name,{get:function(){return this._inputs[n]},enumerable:!0,configurable:!0})}),(i=e.outParameters)==null||i.forEach((r,n)=>{this.registerOutput(r.name,R[r.type]),Object.defineProperty(this,r.name,{get:function(){return this._outputs[n]},enumerable:!0,configurable:!0}),r.type==="BasedOnInput"&&(this._outputs[n]._typeConnectionSource=this._findInputByName(r.typeFromInput)[0])}),(s=e.inLinkedConnectionTypes)==null||s.forEach(r=>{this._linkConnectionTypes(this._findInputByName(r.input1)[1],this._findInputByName(r.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null}}V("BABYLON.CustomBlock",_F);class pF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].excludedConnectionPointTypes.push(R.Float),this._inputs[1].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"DotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`,this}}V("BABYLON.DotBlock",pF);class mF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"NormalizeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${i.associatedVariableName});
`,this}}V("BABYLON.NormalizeBlock",mF);class gF extends Pe{constructor(e){super(e,B.Neutral),this.rSwizzle="r",this.gSwizzle="g",this.bSwizzle="b",this.aSwizzle="a",this.registerInput("rgb ",R.Color3,!0),this.registerInput("r",R.Float,!0),this.registerInput("g",R.Float,!0),this.registerInput("b",R.Float,!0),this.registerInput("a",R.Float,!0),this.registerOutput("rgba",R.Color4),this.registerOutput("rgb",R.Color3)}getClassName(){return"ColorMergerBlock"}get rgbIn(){return this._inputs[0]}get r(){return this._inputs[1]}get g(){return this._inputs[2]}get b(){return this._inputs[3]}get a(){return this._inputs[4]}get rgba(){return this._outputs[0]}get rgbOut(){return this._outputs[1]}get rgb(){return this.rgbOut}_inputRename(e){return e==="rgb "?"rgbIn":e}_buildSwizzle(e){return"."+(this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.r,i=this.g,s=this.b,r=this.a,n=this.rgbIn,o=this._outputs[0],l=this._outputs[1];return n.isConnected?(o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};
`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${n.associatedVariableName}${this._buildSwizzle(3)};
`)):(o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};
`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};
`)),this}serialize(){const e=super.serialize();return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.rSwizzle=e.rSwizzle??"r",this.gSwizzle=e.gSwizzle??"g",this.bSwizzle=e.bSwizzle??"b",this.aSwizzle=e.aSwizzle??"a"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.rSwizzle = "${this.rSwizzle}";
`,e+=`${this._codeVariableName}.gSwizzle = "${this.gSwizzle}";
`,e+=`${this._codeVariableName}.bSwizzle = "${this.bSwizzle}";
`,e+=`${this._codeVariableName}.aSwizzle = "${this.aSwizzle}";
`,e}}V("BABYLON.ColorMergerBlock",gF);class xF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("xyzw",R.Vector4,!0),this.registerInput("xyz ",R.Vector3,!0),this.registerInput("xy ",R.Vector2,!0),this.registerOutput("xyz",R.Vector3),this.registerOutput("xy",R.Vector2),this.registerOutput("zw",R.Vector2),this.registerOutput("x",R.Float),this.registerOutput("y",R.Float),this.registerOutput("z",R.Float),this.registerOutput("w",R.Float),this.inputsAreExclusive=!0}getClassName(){return"VectorSplitterBlock"}get xyzw(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get xyzOut(){return this._outputs[0]}get xyOut(){return this._outputs[1]}get zw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get w(){return this._outputs[6]}_inputRename(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}}_outputRename(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4],l=this._outputs[5],h=this._outputs[6];return i.hasEndpoints&&(t===this.xyIn?e.compilationString+=this._declareOutput(i,e)+` = vec3(${t.associatedVariableName}, 0.0);
`:e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.xyz;
`),r.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(r,e)+` = ${this.xyzw.associatedVariableName}.zw;
`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.xy;
`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.x;
`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.y;
`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${t.associatedVariableName}.z;
`),h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${t.associatedVariableName}.w;
`),this}}V("BABYLON.VectorSplitterBlock",xF);class TF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerInput("gradient",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"LerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});
`,this}}V("BABYLON.LerpBlock",TF);class EF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(R.Float),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"DivideBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};
`,this}}V("BABYLON.DivideBlock",EF);class SF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1,!0),this._inputs[0].acceptedConnectionPointTypes.push(R.Float),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"SubtractBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};
`,this}}V("BABYLON.SubtractBlock",SF);class CF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.Float),this.registerInput("edge",R.Float),this.registerOutput("output",R.Float)}getClassName(){return"StepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});
`,this}}V("BABYLON.StepBlock",CF);class VS extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"OneMinusBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = 1. - ${this.input.associatedVariableName};
`,this}}V("BABYLON.OneMinusBlock",VS);V("BABYLON.OppositeBlock",VS);class kS extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("worldPosition",R.Vector4),this.registerInput("cameraPosition",R.Vector3),this.registerOutput("output",R.Vector3)}getClassName(){return"ViewDirectionBlock"}get worldPosition(){return this._inputs[0]}get cameraPosition(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.CameraPosition&&t(s));i||(i=new it("cameraPosition"),i.setAsSystemValue(nt.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);
`,this}}V("BABYLON.ViewDirectionBlock",kS);class vF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("worldNormal",R.Vector4),this.registerInput("viewDirection",R.Vector3),this.registerInput("bias",R.Float),this.registerInput("power",R.Float),this.registerOutput("fresnel",R.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new kS("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new it("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new it("power");t.value=1,t.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});
`,this}}V("BABYLON.FresnelBlock",vF);class bF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`,this}}V("BABYLON.MaxBlock",bF);class AF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`,this}}V("BABYLON.MinBlock",AF);class yF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].excludedConnectionPointTypes.push(R.Float),this._inputs[1].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});
`,this}}V("BABYLON.DistanceBlock",yF);class RF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerOutput("output",R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName});
`,this}}V("BABYLON.LengthBlock",RF);class IF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName};
`,this}}V("BABYLON.NegateBlock",IF);class PF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerInput("power",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});
`,this}}V("BABYLON.PowBlock",PF);class MF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("seed",R.AutoDetect),this.registerOutput("output",R.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector2|R.Vector3|R.Vector4|R.Color3|R.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy);
`,this}}V("BABYLON.RandomNumberBlock",MF);class DF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("x",R.Float),this.registerInput("y",R.Float),this.registerOutput("output",R.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});
`,this}}V("BABYLON.ArcTan2Block",DF);class OF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerInput("edge0",R.Float),this.registerInput("edge1",R.Float),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});
`,this}}V("BABYLON.SmoothStepBlock",OF);class NF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===R.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});
`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};
`,this}}V("BABYLON.ReciprocalBlock",NF);class FF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerInput("reference",R.AutoDetect),this.registerInput("distance",R.Float),this.registerInput("replacement",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(R.Float),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].excludedConnectionPointTypes.push(R.Float),this._inputs[1].excludedConnectionPointTypes.push(R.Matrix),this._inputs[3].excludedConnectionPointTypes.push(R.Float),this._inputs[3].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`;
`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {
`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};
`,e.compilationString+=`} else {
`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};
`,e.compilationString+=`}
`,this}}V("BABYLON.ReplaceColorBlock",FF);class wF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("value",R.AutoDetect),this.registerInput("steps",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].excludedConnectionPointTypes.push(R.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});
`,this}}V("BABYLON.PosterizeBlock",wF);var Tl;(function(a){a[a.SawTooth=0]="SawTooth",a[a.Square=1]="Square",a[a.Triangle=2]="Triangle"})(Tl||(Tl={}));class LF extends Pe{constructor(e){super(e,B.Neutral),this.kind=Tl.SawTooth,this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(R.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case Tl.SawTooth:{e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});
`;break}case Tl.Square:{e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));
`;break}case Tl.Triangle:{e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;
`;break}}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}V("BABYLON.WaveBlock",LF);class H_{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class BF extends Pe{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,B.Neutral),this.colorSteps=[new H_(0,q.Black()),new H_(1,q.White())],this.onValueChangedObservable=new G,this.registerInput("gradient",R.AutoDetect),this.registerOutput("output",R.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Float|R.Vector2|R.Vector3|R.Vector4|R.Color3|R.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.);
`;return}const i=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};
`,e.compilationString+=`float ${s};
`;let r=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==R.Float&&(r+=".x");for(let n=1;n<this.colorSteps.length;n++){const o=this.colorSteps[n],l=this.colorSteps[n-1];e.compilationString+=`${s} = clamp((${r} - ${e._emitFloat(l.step)}) / (${e._emitFloat(o.step)} -  ${e._emitFloat(l.step)}), 0.0, 1.0) * step(${e._emitFloat(n)}, ${e._emitFloat(this.colorSteps.length-1)});
`,e.compilationString+=`${i} = mix(${i}, ${this._writeColorConstant(n)}, ${s});
`}return e.compilationString+=this._declareOutput(t,e)+` = ${i};
`,this}serialize(){const e=super.serialize();e.colorSteps=[];for(const t of this.colorSteps)e.colorSteps.push({step:t.step,color:{r:t.color.r,g:t.color.g,b:t.color.b}});return e}_deserialize(e,t,i){super._deserialize(e,t,i),this.colorSteps.length=0;for(const s of e.colorSteps)this.colorSteps.push(new H_(s.step,new q(s.color.r,s.color.g,s.color.b)))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();e+=`${this._codeVariableName}.colorSteps = [];
`;for(const t of this.colorSteps)e+=`${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${t.step}, new BABYLON.Color3(${t.color.r}, ${t.color.g}, ${t.color.b})));
`;return e}}V("BABYLON.GradientBlock",BF);class UF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerInput("gradient",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"NLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));
`,this}}V("BABYLON.NLerpBlock",UF);class GS extends Pe{constructor(e){super(e,B.Neutral),this.manhattanDistance=!1,this.registerInput("seed",R.Vector3),this.registerInput("jitter",R.Float),this.registerOutput("output",R.Vector2),this.registerOutput("x",R.Float),this.registerOutput("y",R.Float)}getClassName(){return"WorleyNoise3DBlock"}get seed(){return this._inputs[0]}get jitter(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)return;let t=`vec3 permute(vec3 x){
`;t+=`    return mod((34.0 * x + 1.0) * x, 289.0);
`,t+=`}

`,t+=`vec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){
`,t+=`    return manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z);
`,t+=`}

`,t+=`vec2 worley(vec3 P, float jitter, bool manhattanDistance){
`,t+=`    float K = 0.142857142857; // 1/7
`,t+=`    float Ko = 0.428571428571; // 1/2-K/2
`,t+=`    float  K2 = 0.020408163265306; // 1/(7*7)
`,t+=`    float Kz = 0.166666666667; // 1/6
`,t+=`    float Kzo = 0.416666666667; // 1/2-1/6*2
`,t+=`
`,t+=`    vec3 Pi = mod(floor(P), 289.0);
`,t+=`    vec3 Pf = fract(P) - 0.5;
`,t+=`
`,t+=`    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);
`,t+=`    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);
`,t+=`    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);
`,t+=`
`,t+=`    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));
`,t+=`    vec3 p1 = permute(p + Pi.y - 1.0);
`,t+=`    vec3 p2 = permute(p + Pi.y);
`,t+=`    vec3 p3 = permute(p + Pi.y + 1.0);
`,t+=`
`,t+=`    vec3 p11 = permute(p1 + Pi.z - 1.0);
`,t+=`    vec3 p12 = permute(p1 + Pi.z);
`,t+=`    vec3 p13 = permute(p1 + Pi.z + 1.0);
`,t+=`
`,t+=`    vec3 p21 = permute(p2 + Pi.z - 1.0);
`,t+=`    vec3 p22 = permute(p2 + Pi.z);
`,t+=`    vec3 p23 = permute(p2 + Pi.z + 1.0);
`,t+=`
`,t+=`    vec3 p31 = permute(p3 + Pi.z - 1.0);
`,t+=`    vec3 p32 = permute(p3 + Pi.z);
`,t+=`    vec3 p33 = permute(p3 + Pi.z + 1.0);
`,t+=`
`,t+=`    vec3 ox11 = fract(p11*K) - Ko;
`,t+=`    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;
`,t+=`    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed
`,t+=`
`,t+=`    vec3 ox12 = fract(p12*K) - Ko;
`,t+=`    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;
`,t+=`    vec3 oz12 = floor(p12*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox13 = fract(p13*K) - Ko;
`,t+=`    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;
`,t+=`    vec3 oz13 = floor(p13*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox21 = fract(p21*K) - Ko;
`,t+=`    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;
`,t+=`    vec3 oz21 = floor(p21*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox22 = fract(p22*K) - Ko;
`,t+=`    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;
`,t+=`    vec3 oz22 = floor(p22*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox23 = fract(p23*K) - Ko;
`,t+=`    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;
`,t+=`    vec3 oz23 = floor(p23*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox31 = fract(p31*K) - Ko;
`,t+=`    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;
`,t+=`    vec3 oz31 = floor(p31*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox32 = fract(p32*K) - Ko;
`,t+=`    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;
`,t+=`    vec3 oz32 = floor(p32*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 ox33 = fract(p33*K) - Ko;
`,t+=`    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;
`,t+=`    vec3 oz33 = floor(p33*K2)*Kz - Kzo;
`,t+=`
`,t+=`    vec3 dx11 = Pfx + jitter*ox11;
`,t+=`    vec3 dy11 = Pfy.x + jitter*oy11;
`,t+=`    vec3 dz11 = Pfz.x + jitter*oz11;
`,t+=`
`,t+=`    vec3 dx12 = Pfx + jitter*ox12;
`,t+=`    vec3 dy12 = Pfy.x + jitter*oy12;
`,t+=`    vec3 dz12 = Pfz.y + jitter*oz12;
`,t+=`
`,t+=`    vec3 dx13 = Pfx + jitter*ox13;
`,t+=`    vec3 dy13 = Pfy.x + jitter*oy13;
`,t+=`    vec3 dz13 = Pfz.z + jitter*oz13;
`,t+=`
`,t+=`    vec3 dx21 = Pfx + jitter*ox21;
`,t+=`    vec3 dy21 = Pfy.y + jitter*oy21;
`,t+=`    vec3 dz21 = Pfz.x + jitter*oz21;
`,t+=`
`,t+=`    vec3 dx22 = Pfx + jitter*ox22;
`,t+=`    vec3 dy22 = Pfy.y + jitter*oy22;
`,t+=`    vec3 dz22 = Pfz.y + jitter*oz22;
`,t+=`
`,t+=`    vec3 dx23 = Pfx + jitter*ox23;
`,t+=`    vec3 dy23 = Pfy.y + jitter*oy23;
`,t+=`    vec3 dz23 = Pfz.z + jitter*oz23;
`,t+=`
`,t+=`    vec3 dx31 = Pfx + jitter*ox31;
`,t+=`    vec3 dy31 = Pfy.z + jitter*oy31;
`,t+=`    vec3 dz31 = Pfz.x + jitter*oz31;
`,t+=`
`,t+=`    vec3 dx32 = Pfx + jitter*ox32;
`,t+=`    vec3 dy32 = Pfy.z + jitter*oy32;
`,t+=`    vec3 dz32 = Pfz.y + jitter*oz32;
`,t+=`
`,t+=`    vec3 dx33 = Pfx + jitter*ox33;
`,t+=`    vec3 dy33 = Pfy.z + jitter*oy33;
`,t+=`    vec3 dz33 = Pfz.z + jitter*oz33;
`,t+=`
`,t+=`    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);
`,t+=`    vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);
`,t+=`    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);
`,t+=`    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);
`,t+=`    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);
`,t+=`    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);
`,t+=`    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);
`,t+=`    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);
`,t+=`    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);
`,t+=`
`,t+=`    vec3 d1a = min(d11, d12);
`,t+=`    d12 = max(d11, d12);
`,t+=`    d11 = min(d1a, d13); // Smallest now not in d12 or d13
`,t+=`    d13 = max(d1a, d13);
`,t+=`    d12 = min(d12, d13); // 2nd smallest now not in d13
`,t+=`    vec3 d2a = min(d21, d22);
`,t+=`    d22 = max(d21, d22);
`,t+=`    d21 = min(d2a, d23); // Smallest now not in d22 or d23
`,t+=`    d23 = max(d2a, d23);
`,t+=`    d22 = min(d22, d23); // 2nd smallest now not in d23
`,t+=`    vec3 d3a = min(d31, d32);
`,t+=`    d32 = max(d31, d32);
`,t+=`    d31 = min(d3a, d33); // Smallest now not in d32 or d33
`,t+=`    d33 = max(d3a, d33);
`,t+=`    d32 = min(d32, d33); // 2nd smallest now not in d33
`,t+=`    vec3 da = min(d11, d21);
`,t+=`    d21 = max(d11, d21);
`,t+=`    d11 = min(da, d31); // Smallest now in d11
`,t+=`    d31 = max(da, d31); // 2nd smallest now not in d31
`,t+=`    d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;
`,t+=`    d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest
`,t+=`    d12 = min(d12, d21); // 2nd smallest now not in d21
`,t+=`    d12 = min(d12, d22); // nor in d22
`,t+=`    d12 = min(d12, d31); // nor in d31
`,t+=`    d12 = min(d12, d32); // nor in d32
`,t+=`    d11.yz = min(d11.yz,d12.xy); // nor in d12.yz
`,t+=`    d11.y = min(d11.y,d12.z); // Only two more to go
`,t+=`    d11.y = min(d11.y,d11.z); // Done! (Phew!)
`,t+=`    return sqrt(d11.xy); // F1, F2
`,t+=`}

`,e._emitFunction("worley3D",t,"// Worley3D");const i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`vec2 ${i} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});
`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};
`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${i}.x;
`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${i}.y;
`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};
`}serialize(){const e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}}E([Le("Use Manhattan Distance",Ne.Boolean,"PROPERTIES",{notifiers:{update:!1}})],GS.prototype,"manhattanDistance",void 0);V("BABYLON.WorleyNoise3DBlock",GS);class VF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("seed",R.Vector3),this.registerOutput("output",R.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=`const float SKEWFACTOR = 1.0/3.0;
`;return t+=`const float UNSKEWFACTOR = 1.0/6.0;
`,t+=`const float SIMPLEX_CORNER_POS = 0.5;
`,t+=`const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;
`,t+=`float SimplexPerlin3D( vec3 P ){
`,t+=`    P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;
`,t+=`    P *= SIMPLEX_TETRAHADRON_HEIGHT;
`,t+="    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );",t+=`    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );
`,t+=`    vec3 g = step(x0.yzx, x0.xyz);
`,t+=`    vec3 l = 1.0 - g;
`,t+=`    vec3 Pi_1 = min( g.xyz, l.zxy );
`,t+=`    vec3 Pi_2 = max( g.xyz, l.zxy );
`,t+=`    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;
`,t+=`    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;
`,t+=`    vec3 x3 = x0 - SIMPLEX_CORNER_POS;
`,t+=`    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );
`,t+=`    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );
`,t+=`    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );
`,t+=`    Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;
`,t+=`    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );
`,t+=`    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;
`,t+=`    Pt *= Pt;
`,t+=`    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );
`,t+=`    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );
`,t+=`    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );
`,t+=`    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );
`,t+=`    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );
`,t+=`    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );
`,t+=`    Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;
`,t+=`    Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;
`,t+=`    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;
`,t+=`    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;
`,t+=`    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;
`,t+=`    vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );
`,t+=`    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;
`,t+=`    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;
`,t+=`    kernel_weights = max(0.5 - kernel_weights, 0.0);
`,t+=`    kernel_weights = kernel_weights*kernel_weights*kernel_weights;
`,t+=`    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;
`,t+=`}
`,e._emitFunction("SimplexPerlin3D",t,"// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+` = SimplexPerlin3D(${this.seed.associatedVariableName});
`,this}}V("BABYLON.SimplexPerlin3DBlock",VF);class kF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("normalMap0",R.AutoDetect),this.registerInput("normalMap1",R.AutoDetect),this.registerOutput("output",R.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Color4|R.Vector3|R.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Color4|R.Vector3|R.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0],s=this._inputs[1],r=e._getFreeVariableName("stepR"),n=e._getFreeVariableName("stepG");return e.compilationString+=`float ${r} = step(0.5, ${i.associatedVariableName}.r);
`,e.compilationString+=`float ${n} = step(0.5, ${i.associatedVariableName}.g);
`,e.compilationString+=this._declareOutput(t,e)+`;
`,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${r}) * ${i.associatedVariableName}.r * ${s.associatedVariableName}.r * 2.0 + ${r} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${s.associatedVariableName}.r) * 2.0);
`,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${n}) * ${i.associatedVariableName}.g * ${s.associatedVariableName}.g * 2.0 + ${n} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${s.associatedVariableName}.g) * 2.0);
`,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${s.associatedVariableName}.b;
`,this}}V("BABYLON.NormalBlendBlock",kF);class GF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.Vector2),this.registerInput("angle",R.Float),this.registerOutput("output",R.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new it("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.angle,s=this.input;return e.compilationString+=this._declareOutput(t,e)+` = vec2(cos(${i.associatedVariableName}) * ${s.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${s.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${s.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${s.associatedVariableName}.y);
`,this}}V("BABYLON.Rotate2dBlock",GF);class zF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("incident",R.AutoDetect),this.registerInput("normal",R.AutoDetect),this.registerOutput("output",R.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4|R.Color3|R.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4|R.Color3|R.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);
`,this}}V("BABYLON.ReflectBlock",zF);class WF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("incident",R.AutoDetect),this.registerInput("normal",R.AutoDetect),this.registerInput("ior",R.Float),this.registerOutput("output",R.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4|R.Color3|R.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(R.Vector3|R.Vector4|R.Color3|R.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});
`,this}}V("BABYLON.RefractBlock",WF);class HF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("color",R.Color3),this.registerInput("level",R.Float),this.registerOutput("output",R.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],s=this.color.associatedVariableName,r=e._getFreeVariableName("colorMin"),n=e._getFreeVariableName("colorMax"),o=e._getFreeVariableName("colorMerge");return e.compilationString+=`float ${r} = min(min(${s}.x, ${s}.y), ${s}.z);
`,e.compilationString+=`float ${n} = max(max(${s}.x, ${s}.y), ${s}.z);
`,e.compilationString+=`float ${o} = 0.5 * (${r} + ${n});
`,e.compilationString+=this._declareOutput(t,e)+` = mix(${s}, vec3(${o}, ${o}, ${o}), ${this.level.associatedVariableName});
`,this}}V("BABYLON.DesaturateBlock",HF);class Dc extends Pe{constructor(e){super(e,B.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",R.Float,!0,B.Fragment),this.registerInput("color",R.Color3,!0,B.Fragment),this.registerInput("roughness",R.Float,!0,B.Fragment),this.registerOutput("sheen",R.Object,B.Fragment,new gi("sheen",this,si.Output,Dc,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e){let t="";const i=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",s=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",r=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return t=`#ifdef SHEEN
            sheenOutParams sheenOut;

            vec4 vSheenColor = vec4(${i}, ${s});

            sheenBlock(
                vSheenColor,
            #ifdef SHEEN_ROUGHNESS
                ${r},
            #endif
                roughness,
            #ifdef SHEEN_TEXTURE
                vec4(0.),
                1.0,
            #endif
                reflectance,
            #ifdef SHEEN_LINKWITHALBEDO
                baseColor,
                surfaceAlbedo,
            #endif
            #ifdef ENVIRONMENTBRDF
                NdotV,
                environmentBrdf,
            #endif
            #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
                AARoughnessFactors,
                ${e==null?void 0:e._vReflectionMicrosurfaceInfosName},
                ${e==null?void 0:e._vReflectionInfosName},
                ${e==null?void 0:e.reflectionColor},
                vLightingIntensity,
                #ifdef ${e==null?void 0:e._define3DName}
                    ${e==null?void 0:e._cubeSamplerName},
                #else
                    ${e==null?void 0:e._2DSamplerName},
                #endif
                reflectionOut.reflectionCoords,
                NdotVUnclamped,
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${e==null?void 0:e._define3DName}
                        ${e==null?void 0:e._cubeSamplerName},
                        ${e==null?void 0:e._cubeSamplerName},
                    #else
                        ${e==null?void 0:e._2DSamplerName},
                        ${e==null?void 0:e._2DSamplerName},
                    #endif
                #endif
                #if !defined(${e==null?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION)
                    seo,
                #endif
                #if !defined(${e==null?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${e==null?void 0:e._define3DName})
                    eho,
                #endif
            #endif
                sheenOut
            );

            #ifdef SHEEN_LINKWITHALBEDO
                surfaceAlbedo = sheenOut.surfaceAlbedo;
            #endif
        #endif
`,t}_buildBlock(e){return e.target===B.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.albedoScaling = ${this.albedoScaling};
`,e+=`${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};
`,e}serialize(){const e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}}E([Le("Albedo scaling",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Dc.prototype,"albedoScaling",void 0);E([Le("Link sheen with albedo",Ne.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Dc.prototype,"linkSheenWithAlbedo",void 0);V("BABYLON.SheenBlock",Dc);class n_ extends Pe{constructor(e){super(e,B.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",R.Float,!0,B.Fragment),this.registerInput("direction",R.Vector2,!0,B.Fragment),this.registerInput("uv",R.Vector2,!0),this.registerInput("worldTangent",R.Vector4,!0),this.registerInput("TBN",R.Object,!0,B.VertexAndFragment,new gi("TBN",this,si.Input,Mc,"TBNBlock")),this.registerInput("roughness",R.Float,!0,B.Fragment),this.registerOutput("anisotropy",R.Object,B.Fragment,new gi("anisotropy",this,si.Output,n_,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get roughness(){return this._inputs[5]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="";const i=`//${this.name}`,s=this.uv,r=this.worldPositionConnectionPoint,n=this.worldNormalConnectionPoint,o=this.worldTangent;s.isConnected||O.Error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const l={search:/defined\(TANGENT\)/g,replace:o.isConnected?"defined(TANGENT)":"defined(IGNORE)"},h=this.TBN;return h.isConnected?e.compilationString+=`
            #ifdef TBNBLOCK
            mat3 vTBN = ${h.associatedVariableName};
            #endif
            `:o.isConnected&&(t+=`vec3 tbnNormal = normalize(${n.associatedVariableName}.xyz);
`,t+=`vec3 tbnTangent = normalize(${o.associatedVariableName}.xyz);
`,t+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};
`,t+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);
`),t+=`
            #if defined(${o.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL)
                mat3 TBN = vTBN;
            #else
                mat3 TBN = cotangent_frame(${n.associatedVariableName+".xyz"}, ${"v_"+r.associatedVariableName+".xyz"}, ${s.isConnected?s.associatedVariableName:"vec2(0.)"}, vec2(1., 1.));
            #endif
`,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[l]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));const s=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",r=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",n=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+=`anisotropicOutParams anisotropicOut;
            anisotropicBlock(
                vec3(${r}, ${s}),
                ${n},
            #ifdef ANISOTROPIC_TEXTURE
                vec3(0.),
            #endif
                TBN,
                normalW,
                viewDirectionW,
                anisotropicOut
            );
`,i}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0),i.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_buildBlock(e){return e.target===B.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}}V("BABYLON.AnisotropyBlock",n_);class Oc extends Mu{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,O.Error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?B.Fragment:B.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",R.AutoDetect,!1,B.Vertex),this.registerInput("world",R.Matrix,!1,B.Vertex),this.registerInput("color",R.Color3,!0,B.Fragment),this.registerOutput("reflection",R.Object,B.Fragment,new gi("reflection",this,si.Output,Oc,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("REFLECTION",r,!0),r&&(i.setValue(this._defineLODReflectionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!s.invertZ:s.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",s.gammaSpace,!0),i.setValue("RGBDREFLECTION",s.isRGBD,!0),s&&s.coordinatesMode!==k.SKYBOX_MODE&&s.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,s){super.bind(e,t,i);const r=this._getTexture();if(!r||!s)return;r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r);const n=r.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,r.lodGenerationScale,r.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,ge.Log2(n));const o=s.materialDefines,l=r.sphericalPolynomial;if(o.USESPHERICALFROMREFLECTIONMAP&&l)if(o.SPHERICAL_HARMONICS){const h=l.preScaledHarmonics;e.setVector3("vSphericalL00",h.l00),e.setVector3("vSphericalL1_1",h.l1_1),e.setVector3("vSphericalL10",h.l10),e.setVector3("vSphericalL11",h.l11),e.setVector3("vSphericalL2_2",h.l2_2),e.setVector3("vSphericalL2_1",h.l2_1),e.setVector3("vSphericalL20",h.l20),e.setVector3("vSphericalL21",h.l21),e.setVector3("vSphericalL22",h.l22)}else e.setFloat3("vSphericalX",l.x.x,l.x.y,l.x.z),e.setFloat3("vSphericalY",l.y.x,l.y.y,l.y.z),e.setFloat3("vSphericalZ",l.z.x,l.z.y,l.z.z),e.setFloat3("vSphericalXX_ZZ",l.xx.x-l.zz.x,l.xx.y-l.zz.y,l.xx.z-l.zz.z),e.setFloat3("vSphericalYY_ZZ",l.yy.x-l.zz.x,l.yy.y-l.zz.y,l.yy.z-l.zz.z),e.setFloat3("vSphericalZZ",l.zz.x,l.zz.y,l.zz.z),e.setFloat3("vSphericalXY",l.xy.x,l.xy.y,l.xy.z),e.setFloat3("vSphericalYZ",l.yz.x,l.yz.y,l.yz.z),e.setFloat3("vSphericalZX",l.zx.x,l.zx.y,l.zx.z)}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});const i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
                vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;
                #ifdef ${this._defineOppositeZ}
                    ${i}.z *= -1.0;
                #endif
                ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i});
            #endif
`,t}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",`
            #ifdef ${this._define3DName}
                #define sampleReflection(s, c) textureCube(s, c)
            #else
                #define sampleReflection(s, c) texture2D(s, c)
            #endif
`,`//${this.name}`),e._emitFunction("sampleReflectionLod",`
            #ifdef ${this._define3DName}
                #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)
            #else
                #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)
            #endif
`,`//${this.name}`);const s=`
            vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {
                ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)}
                return ${this._reflectionVectorName};
            }
`;return e._emitFunction("computeReflectionCoordsPBR",s,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION
            vec2 ${this._vReflectionInfosName} = vec2(1., 0.);

            reflectionOutParams reflectionOut;

            reflectionBlock(
                ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz,
                ${t},
                alphaG,
                ${this._vReflectionMicrosurfaceInfosName},
                ${this._vReflectionInfosName},
                ${this.reflectionColor},
            #ifdef ANISOTROPIC
                anisotropicOut,
            #endif
            #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})
                NdotVUnclamped,
            #endif
            #ifdef ${this._defineLinearSpecularReflection}
                roughness,
            #endif
            #ifdef ${this._define3DName}
                ${this._cubeSamplerName},
            #else
                ${this._2DSamplerName},
            #endif
            #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
                ${this._vEnvironmentIrradianceName},
            #endif
            #ifdef USESPHERICALFROMREFLECTIONMAP
                #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                    ${this._reflectionMatrixName},
                #endif
            #endif
            #ifdef USEIRRADIANCEMAP
                irradianceSampler, // ** not handled **
            #endif
            #ifndef LODBASEDMICROSFURACE
                #ifdef ${this._define3DName}
                    ${this._cubeSamplerName},
                    ${this._cubeSamplerName},
                #else
                    ${this._2DSamplerName},
                    ${this._2DSamplerName},
                #endif
            #endif
            #ifdef REALTIME_FILTERING
                ${this._vReflectionFilteringInfoName},
            #endif
                reflectionOut
            );
        #endif
`,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==B.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};
`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};
`,e+=`${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};
`,e}serialize(){var t;const e=super.serialize();return e.useSphericalHarmonics=this.useSphericalHarmonics,e.forceIrradianceInFragment=this.forceIrradianceInFragment,e.gammaSpace=((t=this.texture)==null?void 0:t.gammaSpace)??!0,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}E([Le("Spherical Harmonics",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oc.prototype,"useSphericalHarmonics",void 0);E([Le("Force irradiance in fragment",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],Oc.prototype,"forceIrradianceInFragment",void 0);V("BABYLON.ReflectionBlock",Oc);class Xl extends Pe{constructor(e){super(e,B.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",R.Float,!1,B.Fragment),this.registerInput("roughness",R.Float,!0,B.Fragment),this.registerInput("indexOfRefraction",R.Float,!0,B.Fragment),this.registerInput("normalMapColor",R.Color3,!0,B.Fragment),this.registerInput("uv",R.Vector2,!0,B.Fragment),this.registerInput("tintColor",R.Color3,!0,B.Fragment),this.registerInput("tintAtDistance",R.Float,!0,B.Fragment),this.registerInput("tintThickness",R.Float,!0,B.Fragment),this.registerInput("worldTangent",R.Vector4,!0),this.registerInput("worldNormal",R.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(R.Color4|R.Vector4|R.Vector3),this.registerInput("TBN",R.Object,!0,B.VertexAndFragment,new gi("TBN",this,si.Input,Mc,"TBNBlock")),this.registerOutput("clearcoat",R.Object,B.Fragment,new gi("clearcoat",this,si.Output,Xl,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new it("ClearCoat intensity",B.Fragment,R.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",this.indexOfRefraction.isConnected?this.indexOfRefraction.connectInputBlock.value===ds._DefaultIndexOfRefraction:!0,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var u;super.bind(e,t,i);const s=((u=this.indexOfRefraction.connectInputBlock)==null?void 0:u.value)??ds._DefaultIndexOfRefraction,r=1-s,n=1+s,o=Math.pow(-r/n,2),l=1/s;e.setFloat4("vClearCoatRefractionParams",o,l,r,n);const h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,c=h!=null&&h.perturbedNormal.isConnected?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",c!=null&&c.invertX?1:-1,c!=null&&c.invertY?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",c!=null&&c.invertX?-1:1,c!=null&&c.invertY?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_generateTBNSpace(e,t,i){let s="";const r=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const o={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=`
            #ifdef TBNBLOCK
            mat3 vTBN = ${l.associatedVariableName};
            #endif
            `:n.isConnected&&(s+=`vec3 tbnNormal = normalize(${i}.xyz);
`,s+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz);
`,s+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};
`,s+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);
`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",r,{replaceStrings:[o]}),s}static GetCode(e,t,i,s,r,n,o){let l="";const h=t!=null&&t.intensity.isConnected?t.intensity.associatedVariableName:"1.",c=t!=null&&t.roughness.isConnected?t.roughness.associatedVariableName:"0.",u=t!=null&&t.normalMapColor.isConnected?t.normalMapColor.associatedVariableName:"vec3(0.)",d=t!=null&&t.uv.isConnected?t.uv.associatedVariableName:"vec2(0.)",f=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",_=t!=null&&t.tintThickness.isConnected?t.tintThickness.associatedVariableName:"1.",p=t!=null&&t.tintAtDistance.isConnected?t.tintAtDistance.associatedVariableName:"1.",g="vec4(0.)";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");const x=t.worldNormal;l+=`vec3 vGeometricNormaClearCoatW = ${x.isConnected?"normalize("+x.associatedVariableName+".xyz)":"geometricNormalW"};
`}else l+=`vec3 vGeometricNormaClearCoatW = geometricNormalW;
`;return r&&t&&(l+=t._generateTBNSpace(e,s,o),n=t.worldTangent.isConnected),l+=`clearcoatOutParams clearcoatOut;

        #ifdef CLEARCOAT
            vec2 vClearCoatParams = vec2(${h}, ${c});
            vec4 vClearCoatTintParams = vec4(${f}, ${_});

            clearcoatBlock(
                ${s}.xyz,
                vGeometricNormaClearCoatW,
                viewDirectionW,
                vClearCoatParams,
                specularEnvironmentR0,
            #ifdef CLEARCOAT_TEXTURE
                vec2(0.),
            #endif
            #ifdef CLEARCOAT_TINT
                vClearCoatTintParams,
                ${p},
                vClearCoatRefractionParams,
                #ifdef CLEARCOAT_TINT_TEXTURE
                    ${g},
                #endif
            #endif
            #ifdef CLEARCOAT_BUMP
                vec2(0., 1.),
                vec4(${u}, 0.),
                ${d},
                #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL)
                    vTBN,
                #else
                    vClearCoatTangentSpaceParams,
                #endif
                #ifdef OBJECTSPACE_NORMALMAP
                    normalMatrix,
                #endif
            #endif
            #if defined(FORCENORMALFORWARD) && defined(NORMAL)
                faceNormal,
            #endif
            #ifdef REFLECTION
                ${i==null?void 0:i._vReflectionMicrosurfaceInfosName},
                ${i==null?void 0:i._vReflectionInfosName},
                ${i==null?void 0:i.reflectionColor},
                vLightingIntensity,
                #ifdef ${i==null?void 0:i._define3DName}
                    ${i==null?void 0:i._cubeSamplerName},
                #else
                    ${i==null?void 0:i._2DSamplerName},
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${i==null?void 0:i._define3DName}
                        ${i==null?void 0:i._cubeSamplerName},
                        ${i==null?void 0:i._cubeSamplerName},
                    #else
                        ${i==null?void 0:i._2DSamplerName},
                        ${i==null?void 0:i._2DSamplerName},
                    #endif
                #endif
            #endif
            #if defined(ENVIRONMENTBRDF) && !defined(${i==null?void 0:i._defineSkyboxName})
                #ifdef RADIANCEOCCLUSION
                    ambientMonochrome,
                #endif
            #endif
            #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
                (gl_FrontFacing ? 1. : -1.),
            #endif
                clearcoatOut
            );
        #else
            clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;
        #endif
`,l}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===B.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};
`,e}serialize(){const e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.remapF0OnInterfaceChange=e.remapF0OnInterfaceChange??!0}}E([Le("Remap F0 on interface change",Ne.Boolean,"ADVANCED")],Xl.prototype,"remapF0OnInterfaceChange",void 0);V("BABYLON.ClearCoatBlock",Xl);class Du extends Pe{constructor(e){super(e,B.Fragment),this._isUnique=!0,this.registerInput("intensity",R.Float,!0,B.Fragment),this.registerInput("indexOfRefraction",R.Float,!0,B.Fragment),this.registerInput("thickness",R.Float,!0,B.Fragment),this.registerOutput("iridescence",R.Object,B.Fragment,new gi("iridescence",this,si.Output,Du,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new it("Iridescence intensity",B.Fragment,R.Float);e.value=1,e.output.connectTo(this.intensity);const t=new it("Iridescence ior",B.Fragment,R.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new it("Iridescence thickness",B.Fragment,R.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t="";const i=e!=null&&e.intensity.isConnected?e.intensity.associatedVariableName:"1.",s=e!=null&&e.indexOfRefraction.isConnected?e.indexOfRefraction.associatedVariableName:zs._DefaultIndexOfRefraction,r=e!=null&&e.thickness.isConnected?e.thickness.associatedVariableName:zs._DefaultMaximumThickness;return t+=`iridescenceOutParams iridescenceOut;

        #ifdef IRIDESCENCE
            iridescenceBlock(
                vec4(${i}, ${s}, 1., ${r}),
                NdotV,
                specularEnvironmentR0,
                #ifdef CLEARCOAT
                    NdotVUnclamped,
                #endif
                iridescenceOut
            );

            float iridescenceIntensity = iridescenceOut.iridescenceIntensity;
            specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;
        #endif
`,t}_buildBlock(e){return e.target===B.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}V("BABYLON.IridescenceBlock",Du);class $o extends Pe{constructor(e){super(e,B.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",R.Float,!1,B.Fragment),this.registerInput("tintAtDistance",R.Float,!0,B.Fragment),this.registerInput("volumeIndexOfRefraction",R.Float,!0,B.Fragment),this.registerOutput("refraction",R.Object,B.Fragment,new gi("refraction",this,si.Output,$o,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){const i=new it("Refraction intensity",B.Fragment,R.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.View&&t(s));i||(i=new it("view"),i.setAsSystemValue(nt.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){var l,h;super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=((l=this.volumeIndexOfRefraction.connectInputBlock)==null?void 0:l.value)??((h=this.indexOfRefractionConnectionPoint.connectInputBlock)==null?void 0:h.value)??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,ge.Log2(o)),s.boundingBoxSize){const c=s;e.setVector3("vRefractionPosition",c.boundingBoxPosition),e.setVector3("vRefractionSize",c.boundingBoxSize)}}getCode(e){const t="";return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}
`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};
`,e._samplerDeclaration+=`#else
`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};
`,e._samplerDeclaration+=`#endif
`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`
            #ifdef ${this._define3DName}
                #define sampleRefraction(s, c) textureCube(s, c)
            #else
                #define sampleRefraction(s, c) texture2D(s, c)
            #endif
`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`
            #ifdef ${this._define3DName}
                #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)
            #else
                #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)
            #endif
`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),t}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(this.texture.isCube?e=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");
`:e=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");
`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};
`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};
`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};
`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Hi.Parse(e.texture,t,i):this.texture=k.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}E([Le("Link refraction to transparency",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],$o.prototype,"linkRefractionWithTransparency",void 0);E([Le("Invert refraction Y",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],$o.prototype,"invertRefractionY",void 0);E([Le("Use thickness as depth",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],$o.prototype,"useThicknessAsDepth",void 0);V("BABYLON.RefractionBlock",$o);class Ou extends Pe{constructor(e){super(e,B.Fragment),this._isUnique=!0,this.registerInput("thickness",R.Float,!1,B.Fragment),this.registerInput("tintColor",R.Color3,!0,B.Fragment),this.registerInput("translucencyIntensity",R.Float,!0,B.Fragment),this.registerInput("translucencyDiffusionDist",R.Color3,!0,B.Fragment),this.registerInput("refraction",R.Object,!0,B.Fragment,new gi("refraction",this,si.Input,$o,"RefractionBlock")),this.registerInput("dispersion",R.Float,!0,B.Fragment),this.registerOutput("subsurface",R.Object,B.Fragment,new gi("subsurface",this,si.Output,Ou,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new it("SubSurface thickness",B.Fragment,R.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){var p;let r="";const n=t!=null&&t.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",l=t!=null&&t.translucencyIntensity.isConnected?t==null?void 0:t.translucencyIntensity.associatedVariableName:"1.",h=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",c=t!=null&&t.refraction.isConnected?(p=t==null?void 0:t.refraction.connectedPoint)==null?void 0:p.ownerBlock:null,u=c!=null&&c.tintAtDistance.isConnected?c.tintAtDistance.associatedVariableName:"1.",d=c!=null&&c.intensity.isConnected?c.intensity.associatedVariableName:"1.",f=c!=null&&c.view.isConnected?c.view.associatedVariableName:"",_=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0";return r+=(c==null?void 0:c.getCode(e))??"",r+=`subSurfaceOutParams subSurfaceOut;

        #ifdef SUBSURFACE
            vec2 vThicknessParam = vec2(0., ${n});
            vec4 vTintColor = vec4(${o}, ${u});
            vec3 vSubSurfaceIntensity = vec3(${d}, ${l}, 0.);
            float dispersion = ${_};
            subSurfaceBlock(
                vSubSurfaceIntensity,
                vThicknessParam,
                vTintColor,
                normalW,
                specularEnvironmentReflectance,
            #ifdef SS_THICKNESSANDMASK_TEXTURE
                vec4(0.),
            #endif
            #ifdef REFLECTION
                #ifdef SS_TRANSLUCENCY
                    ${i==null?void 0:i._reflectionMatrixName},
                    #ifdef USESPHERICALFROMREFLECTIONMAP
                        #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                            reflectionOut.irradianceVector,
                        #endif
                        #if defined(REALTIME_FILTERING)
                            ${i==null?void 0:i._cubeSamplerName},
                            ${i==null?void 0:i._vReflectionFilteringInfoName},
                        #endif
                        #endif
                    #ifdef USEIRRADIANCEMAP
                        irradianceSampler,
                    #endif
                #endif
            #endif
            #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
                surfaceAlbedo,
            #endif
            #ifdef SS_REFRACTION
                ${s}.xyz,
                viewDirectionW,
                ${f},
                ${(c==null?void 0:c._vRefractionInfosName)??""},
                ${(c==null?void 0:c._refractionMatrixName)??""},
                ${(c==null?void 0:c._vRefractionMicrosurfaceInfosName)??""},
                vLightingIntensity,
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha,
                #endif
                #ifdef ${(c==null?void 0:c._defineLODRefractionAlpha)??"IGNORE"}
                    NdotVUnclamped,
                #endif
                #ifdef ${(c==null?void 0:c._defineLinearSpecularRefraction)??"IGNORE"}
                    roughness,
                #endif
                alphaG,
                #ifdef ${(c==null?void 0:c._define3DName)??"IGNORE"}
                    ${(c==null?void 0:c._cubeSamplerName)??""},
                #else
                    ${(c==null?void 0:c._2DSamplerName)??""},
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${(c==null?void 0:c._define3DName)??"IGNORE"}
                        ${(c==null?void 0:c._cubeSamplerName)??""},
                        ${(c==null?void 0:c._cubeSamplerName)??""},
                    #else
                        ${(c==null?void 0:c._2DSamplerName)??""},
                        ${(c==null?void 0:c._2DSamplerName)??""},
                    #endif
                #endif
                #ifdef ANISOTROPIC
                    anisotropicOut,
                #endif
                #ifdef REALTIME_FILTERING
                    ${(c==null?void 0:c._vRefractionFilteringInfoName)??""},
                #endif
                #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
                    vRefractionPosition,
                    vRefractionSize,
                #endif
                #ifdef SS_DISPERSION
                    dispersion,
                #endif
            #endif
            #ifdef SS_TRANSLUCENCY
                ${h},
            #endif
                subSurfaceOut
            );

            #ifdef SS_REFRACTION
                surfaceAlbedo = subSurfaceOut.surfaceAlbedo;
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha = subSurfaceOut.alpha;
                #endif
            #endif
        #else
            subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;
        #endif
`,r}_buildBlock(e){return e.target===B.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}V("BABYLON.SubSurfaceBlock",Ou);const XF={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class ss extends Pe{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,O.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?B.Fragment:B.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?B.Fragment:B.Vertex}constructor(e){super(e,B.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=q.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",R.Vector4,!1,B.Vertex),this.registerInput("worldNormal",R.Vector4,!1,B.Fragment),this.registerInput("view",R.Matrix,!1),this.registerInput("cameraPosition",R.Vector3,!1,B.Fragment),this.registerInput("perturbedNormal",R.Vector4,!0,B.Fragment),this.registerInput("baseColor",R.Color3,!0,B.Fragment),this.registerInput("metallic",R.Float,!1,B.Fragment),this.registerInput("roughness",R.Float,!1,B.Fragment),this.registerInput("ambientOcc",R.Float,!0,B.Fragment),this.registerInput("opacity",R.Float,!0,B.Fragment),this.registerInput("indexOfRefraction",R.Float,!0,B.Fragment),this.registerInput("ambientColor",R.Color3,!0,B.Fragment),this.registerInput("reflection",R.Object,!0,B.Fragment,new gi("reflection",this,si.Input,Oc,"ReflectionBlock")),this.registerInput("clearcoat",R.Object,!0,B.Fragment,new gi("clearcoat",this,si.Input,Xl,"ClearCoatBlock")),this.registerInput("sheen",R.Object,!0,B.Fragment,new gi("sheen",this,si.Input,Dc,"SheenBlock")),this.registerInput("subsurface",R.Object,!0,B.Fragment,new gi("subsurface",this,si.Input,Ou,"SubSurfaceBlock")),this.registerInput("anisotropy",R.Object,!0,B.Fragment,new gi("anisotropy",this,si.Input,n_,"AnisotropyBlock")),this.registerInput("iridescence",R.Object,!0,B.Fragment,new gi("iridescence",this,si.Input,Du,"IridescenceBlock")),this.registerOutput("ambientClr",R.Color3,B.Fragment),this.registerOutput("diffuseDir",R.Color3,B.Fragment),this.registerOutput("specularDir",R.Color3,B.Fragment),this.registerOutput("clearcoatDir",R.Color3,B.Fragment),this.registerOutput("sheenDir",R.Color3,B.Fragment),this.registerOutput("diffuseInd",R.Color3,B.Fragment),this.registerOutput("specularInd",R.Color3,B.Fragment),this.registerOutput("clearcoatInd",R.Color3,B.Fragment),this.registerOutput("sheenInd",R.Color3,B.Fragment),this.registerOutput("refraction",R.Color3,B.Fragment),this.registerOutput("lighting",R.Color3,B.Fragment),this.registerOutput("shadow",R.Float,B.Fragment),this.registerOutput("alpha",R.Float,B.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.CameraPosition&&t(s));i||(i=new it("cameraPosition"),i.setAsSystemValue(nt.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===nt.View&&t(s));i||(i=new it("view"),i.setAsSystemValue(nt.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===At.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===At.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&ue.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),!!i._areLightsDirty)if(!this.light)qu(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Pf(r,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};vm(r,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r<t.maxSimultaneousLights&&i["LIGHT"+r];r++){const n=e.uniforms.indexOf("vLightData"+r)>=0;Am(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var u;if(!i)return;const s=i.getScene();this.light?Em(this.light,this._lightId,s,e,!0):ju(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(s._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=1,l=((u=this.indexOfRefraction.connectInputBlock)==null?void 0:u.value)??1.5,h=Math.pow((l-o)/(l+o),2);this._metallicReflectanceColor.scaleToRef(h*this._metallicF0Factor,gt.Color3[0]);const c=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,gt.Color3[0],c),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var n;const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(e.counters.lightCounter!==void 0?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};
`);const r=this.reflection.isConnected?(n=this.reflection.connectedPoint)==null?void 0:n.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=(r==null?void 0:r.handleVertexSide(e))??"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0
`,e._injectAtEnd+=`vClipSpacePosition = gl_Position;
`,e._injectAtEnd+=`#endif
`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};
`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};
`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut;
`;const t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+=`albedoOpacityBlock(
                vec4(${t}, 1.),
            #ifdef ALBEDO
                vec4(1.),
                vec2(1., 1.),
            #endif
            #ifdef OPACITY
                vec4(${i}),
                vec2(1., 1.),
            #endif
                albedoOpacityOut
            );

            vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;
            float alpha = albedoOpacityOut.alpha;
`,e}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut;
`;const t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+=`ambientOcclusionBlock(
            #ifdef AMBIENT
                vec3(${t}),
                vec4(0., 1.0, 1.0, 0.),
            #endif
                aoOut
            );
`,e}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut;
`;const i="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;

            reflectivityBlock(
                vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),
            #ifdef METALLICWORKFLOW
                surfaceAlbedo,
                ${this._vMetallicReflectanceFactorsName},
            #endif
            #ifdef REFLECTIVITY
                vec3(0., 0., ${i}),
                vec4(1.),
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY)  && defined(AOSTOREINMETALMAPRED)
                aoOut.ambientOcclusionColor,
            #endif
            #ifdef MICROSURFACEMAP
                microSurfaceTexel, <== not handled!
            #endif
                reflectivityOut
            );

            float microSurface = reflectivityOut.microSurface;
            float roughness = reflectivityOut.roughness;

            #ifdef METALLICWORKFLOW
                surfaceAlbedo = reflectivityOut.surfaceAlbedo;
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
                aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;
            #endif
`,t}_buildBlock(e){var T,S,C,v,b,A,P,L,w,$,J;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=og(this._scene));const t=this.reflection.isConnected?(T=this.reflection.connectedPoint)==null?void 0:T.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==B.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};
`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;
`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0
`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);
`,e.compilationString+=`#endif
`):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity","vec4"),t!=null&&t.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});
`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);
`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;
`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};
`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+=`#ifdef UNLIT
                vec3 diffuseBase = vec3(1., 1., 1.);
            #else
`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?(S=this.anisotropy.connectedPoint)==null?void 0:S.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(t==null?void 0:t._vReflectionFilteringInfoName)??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?(C=this.sheen.connectedPoint)==null?void 0:C.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"}]});const l=this.iridescence.isConnected?(v=this.iridescence.connectedPoint)==null?void 0:v.ownerBlock:null;e.compilationString+=Du.GetCode(l),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const h=this.clearcoat.isConnected?(b=this.clearcoat.connectedPoint)==null?void 0:b.ownerBlock:null,c=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,u=this.perturbedNormal.isConnected&&((P=((A=this.perturbedNormal.connectedPoint)==null?void 0:A.ownerBlock).worldTangent)==null?void 0:P.isConnected),d=this.anisotropy.isConnected&&((L=this.anisotropy.connectedPoint)==null?void 0:L.ownerBlock).worldTangent.isConnected;let f=u||!this.perturbedNormal.isConnected&&d;e.compilationString+=Xl.GetCode(e,h,t,r,c,f,this.worldNormal.associatedVariableName),c&&(f=(h==null?void 0:h.worldTangent.isConnected)??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:f?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?(w=this.subsurface.connectedPoint)==null?void 0:w.ownerBlock:null,p=this.subsurface.isConnected?(J=(($=this.subsurface.connectedPoint)==null?void 0:$.ownerBlock).refraction.connectedPoint)==null?void 0:J.ownerBlock:null;p&&(p.viewConnectionPoint=this.view,p.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Ou.GetCode(e,_,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(p==null?void 0:p._define3DName)??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(p==null?void 0:p._defineLODRefractionAlpha)??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(p==null?void 0:p._defineLinearSpecularRefraction)??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(p==null?void 0:p._defineOppositeZ)??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+=`#endif
`;const g=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let x=At.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();x.indexOf(".")===-1&&(x+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:g+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:x}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.);
gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);
`}]});for(const ne of this._outputs)if(ne.hasEndpoints){const oe=XF[ne.name];if(oe){const[re,ce]=oe;ce&&(e.compilationString+=`#if ${ce}
`),e.compilationString+=`${this._declareOutput(ne,e)} = ${re};
`,ce&&(e.compilationString+=`#else
`,e.compilationString+=`${this._declareOutput(ne,e)} = vec3(0.);
`,e.compilationString+=`#endif
`)}else O.Error(`There's no remapping for the ${ne.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};
`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};
`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};
`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};
`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};
`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};
`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};
`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};
`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};
`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};
`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};
`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};
`,e+=`${this._codeVariableName}.unlit = ${this.unlit};
`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};
`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};
`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};
`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};
`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}E([Le("Direct lights",Ne.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ss.prototype,"directIntensity",void 0);E([Le("Environment lights",Ne.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ss.prototype,"environmentIntensity",void 0);E([Le("Specular highlights",Ne.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ss.prototype,"specularIntensity",void 0);E([Le("Light falloff",Ne.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:At.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:At.LIGHTFALLOFF_GLTF},{label:"Standard",value:At.LIGHTFALLOFF_STANDARD}]})],ss.prototype,"lightFalloff",void 0);E([Le("Alpha Testing",Ne.Boolean,"OPACITY")],ss.prototype,"useAlphaTest",void 0);E([Le("Alpha CutOff",Ne.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],ss.prototype,"alphaTestCutoff",void 0);E([Le("Alpha blending",Ne.Boolean,"OPACITY")],ss.prototype,"useAlphaBlending",void 0);E([Le("Radiance over alpha",Ne.Boolean,"RENDERING",{notifiers:{update:!0}})],ss.prototype,"useRadianceOverAlpha",void 0);E([Le("Specular over alpha",Ne.Boolean,"RENDERING",{notifiers:{update:!0}})],ss.prototype,"useSpecularOverAlpha",void 0);E([Le("Specular anti-aliasing",Ne.Boolean,"RENDERING",{notifiers:{update:!0}})],ss.prototype,"enableSpecularAntiAliasing",void 0);E([Le("Realtime filtering",Ne.Boolean,"RENDERING",{notifiers:{update:!0}})],ss.prototype,"realTimeFiltering",void 0);E([Le("Realtime filtering quality",Ne.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],ss.prototype,"realTimeFilteringQuality",void 0);E([Le("Energy Conservation",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],ss.prototype,"useEnergyConservation",void 0);E([Le("Radiance occlusion",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],ss.prototype,"useRadianceOcclusion",void 0);E([Le("Horizon occlusion",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],ss.prototype,"useHorizonOcclusion",void 0);E([Le("Unlit",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],ss.prototype,"unlit",void 0);E([Le("Force normal forward",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],ss.prototype,"forceNormalForward",void 0);E([Le("Generate only fragment code",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ss._OnGenerateOnlyFragmentCodeChanged}})],ss.prototype,"generateOnlyFragmentCode",void 0);E([Le("Debug mode",Ne.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],ss.prototype,"debugMode",void 0);E([Le("Split position",Ne.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],ss.prototype,"debugLimit",void 0);E([Le("Output factor",Ne.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],ss.prototype,"debugFactor",void 0);V("BABYLON.PBRMetallicRoughnessBlock",ss);class YF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("left",R.AutoDetect),this.registerInput("right",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(R.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`,this}}V("BABYLON.ModBlock",YF);class $F extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("row0",R.Vector4),this.registerInput("row1",R.Vector4),this.registerInput("row2",R.Vector4),this.registerInput("row3",R.Vector4),this.registerOutput("output",R.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new it("row0");e.value=new we(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new it("row1");e.value=new we(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new it("row2");e.value=new we(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new it("row3");e.value=new we(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});
`,this}}V("BABYLON.MatrixBuilder",$F);var Rr;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(Rr||(Rr={}));class KF extends Pe{constructor(e){super(e,B.Neutral),this.condition=Rr.LessThan,this.registerInput("a",R.Float),this.registerInput("b",R.Float),this.registerInput("true",R.AutoDetect,!0),this.registerInput("false",R.AutoDetect,!0),this.registerOutput("output",R.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=R.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case Rr.Equal:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.NotEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.LessThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.LessOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.GreaterThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.GreaterOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${s};
`;break}case Rr.Xor:{e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${s};
`;break}case Rr.Or:{e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${s};
`;break}case Rr.And:{e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)  ? ${i} : ${s};
`;break}}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${Rr[this.condition]};
`}}V("BABYLON.ConditionalBlock",KF);class zS extends Pe{constructor(e){super(e,B.Neutral),this.octaves=6,this.registerInput("seed",R.AutoDetect),this.registerInput("chaos",R.AutoDetect,!0),this.registerInput("offsetX",R.Float,!0),this.registerInput("offsetY",R.Float,!0),this.registerInput("offsetZ",R.Float,!0),this.registerOutput("output",R.Float),this._inputs[0].acceptedConnectionPointTypes.push(R.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(R.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var l,h;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const t=`

        float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }

        // Based on Morgan McGuire @morgan3d
        // https://www.shadertoy.com/view/4dS3Wd
        float cloudNoise(in vec2 x, in vec2 chaos) {
            vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);

            vec2 i = floor(x);
            vec2 f = fract(x);

            float n = dot(i, step);

            vec2 u = f * f * (3.0 - 2.0 * f);
            return mix(
                    mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),
                    mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),
                    u.y
                );
        }

        float cloudNoise(in vec3 x, in vec3 chaos) {
            vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);

            vec3 i = floor(x);
            vec3 f = fract(x);

            float n = dot(i, step);

            vec3 u = f * f * (3.0 - 2.0 * f);
            return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),
                       mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);
        }`,i=`
        float fbm(in vec2 st, in vec2 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = .5;
            float frequency = 0.;

            // Loop of octaves
            for (int i = 0; i < OCTAVES; i++) {
                value += amplitude * cloudNoise(st, chaos);
                st *= 2.0;
                amplitude *= 0.5;
            }
            return value;
        }

        float fbm(in vec3 x, in vec3 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = 0.5;
            for (int i = 0; i < OCTAVES; ++i) {
                value += amplitude * cloudNoise(x, chaos);
                x = x * 2.0;
                amplitude *= 0.5;
            }
            return value;
        }`,s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=((l=this.seed.connectedPoint)==null?void 0:l.type)===R.Vector2?"vec2":"vec3";e.compilationString+=`${n} ${r} = ${this.seed.associatedVariableName};
`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};
`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};
`),this.offsetZ.isConnected&&n==="vec3"&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};
`);let o="";return this.chaos.isConnected?o=this.chaos.associatedVariableName:o=((h=this.seed.connectedPoint)==null?void 0:h.type)===R.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${s}(${r}, ${o});
`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};
`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}E([Le("Octaves",Ne.Int)],zS.prototype,"octaves",void 0);V("BABYLON.CloudBlock",zS);class jF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("seed",R.Vector2),this.registerInput("offset",R.Float),this.registerInput("density",R.Float),this.registerOutput("output",R.Float),this.registerOutput("cells",R.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){
            mat2 m = mat2(15.27, 47.63, 99.41, 89.98);
            vec2 uv = fract(sin(m * seed) * 46839.32);
            return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);
        }
        `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){
            vec2 g = floor(seed * density);
            vec2 f = fract(seed * density);
            float t = 8.0;
            vec3 res = vec3(8.0, 0.0, 0.0);

            for(int y=-1; y<=1; y++)
            {
                for(int x=-1; x<=1; x++)
                {
                    vec2 lattice = vec2(x,y);
                    vec2 randomOffset = voronoiRandom(lattice + g, offset);
                    float d = distance(lattice + randomOffset, f);
                    if(d < res.x)
                    {
                        res = vec3(d, randomOffset.x, randomOffset.y);
                        outValue = res.x;
                        cells = res.y;
                    }
                }
            }
        }
        `,e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),s=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;
`,e.compilationString+=`float ${s} = 0.0;
`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${s});
`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};
`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${s};
`),this}}V("BABYLON.VoronoiNoiseBlock",jF);class qF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==B.VertexAndFragment)return t.target;if(e.connectedPoint.target!==B.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName};
`,this}}V("BABYLON.ElbowBlock",qF);class Tg extends Pe{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)==null?void 0:e.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??Ae.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this._texture)),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,i=>i.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)==null?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(e=this.sourceZ)!=null&&e.isConnected?((t=this.sourceY.connectedPoint)==null?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return e!=null&&e.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e;return((e=this._getImageSourceBlock(this.sourceY))==null?void 0:e.samplerName)??null}get samplerZName(){var e;return((e=this._getImageSourceBlock(this.sourceZ))==null?void 0:e.samplerName)??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const t=this.texture.getScene()??Ae.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const t=this.texture.getScene()??Ae.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,B.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",R.AutoDetect,!1),this.registerInput("normal",R.AutoDetect,!1),this.registerInput("sharpness",R.Float,!0),this.registerInput("source",R.Object,!0,B.VertexAndFragment,new gi("source",this,si.Input,Cn,"ImageSourceBlock")),this.registerInput("sourceY",R.Object,!0,B.VertexAndFragment,new gi("sourceY",this,si.Input,Cn,"ImageSourceBlock")),t||this.registerInput("sourceZ",R.Object,!0,B.VertexAndFragment,new gi("sourceZ",this,si.Input,Cn,"ImageSourceBlock")),this.registerOutput("rgba",R.Color4,B.Neutral),this.registerOutput("rgb",R.Color3,B.Neutral),this.registerOutput("r",R.Float,B.Neutral),this.registerOutput("g",R.Float,B.Neutral),this.registerOutput("b",R.Float,B.Neutral),this.registerOutput("a",R.Float,B.Neutral),this.registerOutput("level",R.Float,B.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(R.Color3|R.Vector3|R.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),l=e._getFreeVariableName("z"),h=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),u=e._getFreeVariableName("uvx"),d=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=`
            vec3 ${c} = ${this.normal.associatedVariableName}.xyz;

            vec2 ${u} = ${this.position.associatedVariableName}.yz;
            vec2 ${d} = ${this.position.associatedVariableName}.zx;
            vec2 ${f} = ${this.position.associatedVariableName}.xy;
        `,this.projectAsCube&&(e.compilationString+=`
                ${u}.xy = ${u}.yx;

                if (${c}.x >= 0.0) {
                    ${u}.x = -${u}.x;
                }
                if (${c}.y < 0.0) {
                    ${d}.y = -${d}.y;
                }
                if (${c}.z < 0.0) {
                    ${f}.x = -${f}.x;
                }
            `),e.compilationString+=`
            vec4 ${n} = texture2D(${t}, ${u});
            vec4 ${o} = texture2D(${i}, ${d});
            vec4 ${l} = texture2D(${s}, ${f});
           
            // blend weights
            vec3 ${h} = pow(abs(${c}), vec3(${r}));

            // blend and return
            vec4 ${this._tempTextureRead} = (${n}*${h}.x + ${o}*${h}.y + ${l}*${h}.z) / (${h}.x + ${h}.y + ${h}.z);        
        `}_generateConversionCode(e,t,i){i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName}
                    ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});
                    #endif
                `),e.compilationString+=`#ifdef ${this._gammaDefineName}
                ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});
                #endif
            `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};
`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};
`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};
`,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Ei.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=k.Parse(e.texture,t,i))}}E([Le("Project as cube",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],Tg.prototype,"projectAsCube",void 0);V("BABYLON.TriPlanarBlock",Tg);class QF extends Tg{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),f=e._getFreeVariableName("y");e.compilationString+=`
            // grab coord derivatives for texturing
            vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);
            vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz);
            vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz);
        
            // determine major axis (in x; yz are following axis)
            ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) :
                    (${o}.y>${o}.z)            ? ivec3(1,2,0) :
                                            ivec3(2,0,1) ;
            // determine minor axis (in x; yz are following axis)
            ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) :
                    (${o}.y<${o}.z)            ? ivec3(1,2,0) :
                                            ivec3(2,0,1) ;
            // determine median axis (in x;  yz are following axis)
            ivec3 ${c} = ivec3(3) - ${h} - ${l};
            
            // project+fetch
            vec4 ${u} = textureGrad( ${t}, vec2(   ${this.position.associatedVariableName}[${l}.y],   ${this.position.associatedVariableName}[${l}.z]), 
                                    vec2(${r}[${l}.y],${r}[${l}.z]), 
                                    vec2(${n}[${l}.y],${n}[${l}.z]) );
            vec4 ${d} = textureGrad( ${i}, vec2(   ${this.position.associatedVariableName}[${c}.y],   ${this.position.associatedVariableName}[${c}.z]), 
                                    vec2(${r}[${c}.y],${r}[${c}.z]),
                                    vec2(${n}[${c}.y],${n}[${c}.z]) );
            
            // blend factors
            vec2 ${f} = vec2(${o}[${l}.x],${o}[${c}.x]);
            // make local support
            ${f} = clamp( (${f}-0.5773)/(1.0-0.5773), 0.0, 1.0 );
            // shape transition
            ${f} = pow( ${f}, vec2(${s}/8.0) );
            // blend and return
            vec4 ${this._tempTextureRead} = (${u}*${f}.x + ${d}*${f}.y) / (${f}.x + ${f}.y);
        `}}V("BABYLON.BiPlanarBlock",QF);class ZF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.Matrix),this.registerOutput("output",R.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName});
`,this}}V("BABYLON.MatrixDeterminantBlock",ZF);class JF extends Pe{constructor(e){super(e,B.Neutral),this.registerInput("input",R.Matrix),this.registerOutput("output",R.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName});
`,this}}V("BABYLON.MatrixTransposeBlock",JF);var Ht;(function(a){a[a.None=0]="None",a[a.Normal=1]="Normal",a[a.Tangent=2]="Tangent",a[a.VertexColor=3]="VertexColor",a[a.UV1=4]="UV1",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6"})(Ht||(Ht={}));class WS extends Pe{constructor(e){super(e,B.Neutral),this.attributeType=Ht.None,this.registerInput("input",R.AutoDetect),this.registerInput("fallback",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var s;if(this.attributeType)return;const i=t.ownerBlock;if(i instanceof it&&i.isAttribute)switch(i.name){case"color":this.attributeType=Ht.VertexColor;break;case"normal":this.attributeType=Ht.Normal;break;case"tangent":this.attributeType=Ht.Tangent;break;case"uv":this.attributeType=Ht.UV1;break;case"uv2":this.attributeType=Ht.UV2;break;case"uv3":this.attributeType=Ht.UV3;break;case"uv4":this.attributeType=Ht.UV4;break;case"uv5":this.attributeType=Ht.UV5;break;case"uv6":this.attributeType=Ht.UV6;break}else if(i instanceof BS)switch((s=this.input.connectedPoint)==null?void 0:s.name){case"normalOutput":this.attributeType=Ht.Normal;break;case"tangentOutput":this.attributeType=Ht.Tangent;break;case"uvOutput":this.attributeType=Ht.UV1;break}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case Ht.VertexColor:t="VERTEXCOLOR_NME";break;case Ht.Normal:t="NORMAL";break;case Ht.Tangent:t="TANGENT";break;case Ht.UV1:t="UV1";break;case Ht.UV2:t="UV2";break;case Ht.UV3:t="UV3";break;case Ht.UV4:t="UV4";break;case Ht.UV5:t="UV5";break;case Ht.UV6:t="UV6";break}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}
`),e.compilationString+=`${i} = ${this.input.associatedVariableName};
`,t&&(e.compilationString+=`#else
`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName};
`,e.compilationString+=`#endif
`),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??Ht.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};
`,e}}E([Le("Attribute lookup",Ne.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:Ht.None},{label:"Normal",value:Ht.Normal},{label:"Tangent",value:Ht.Tangent},{label:"Vertex Color",value:Ht.VertexColor},{label:"UV1",value:Ht.UV1},{label:"UV2",value:Ht.UV2},{label:"UV3",value:Ht.UV3},{label:"UV4",value:Ht.UV4},{label:"UV5",value:Ht.UV5},{label:"UV6",value:Ht.UV6}]})],WS.prototype,"attributeType",void 0);V("BABYLON.MeshAttributeExistsBlock",WS);var ei;(function(a){a[a.EaseInSine=0]="EaseInSine",a[a.EaseOutSine=1]="EaseOutSine",a[a.EaseInOutSine=2]="EaseInOutSine",a[a.EaseInQuad=3]="EaseInQuad",a[a.EaseOutQuad=4]="EaseOutQuad",a[a.EaseInOutQuad=5]="EaseInOutQuad",a[a.EaseInCubic=6]="EaseInCubic",a[a.EaseOutCubic=7]="EaseOutCubic",a[a.EaseInOutCubic=8]="EaseInOutCubic",a[a.EaseInQuart=9]="EaseInQuart",a[a.EaseOutQuart=10]="EaseOutQuart",a[a.EaseInOutQuart=11]="EaseInOutQuart",a[a.EaseInQuint=12]="EaseInQuint",a[a.EaseOutQuint=13]="EaseOutQuint",a[a.EaseInOutQuint=14]="EaseInOutQuint",a[a.EaseInExpo=15]="EaseInExpo",a[a.EaseOutExpo=16]="EaseOutExpo",a[a.EaseInOutExpo=17]="EaseInOutExpo",a[a.EaseInCirc=18]="EaseInCirc",a[a.EaseOutCirc=19]="EaseOutCirc",a[a.EaseInOutCirc=20]="EaseInOutCirc",a[a.EaseInBack=21]="EaseInBack",a[a.EaseOutBack=22]="EaseOutBack",a[a.EaseInOutBack=23]="EaseInOutBack",a[a.EaseInElastic=24]="EaseInElastic",a[a.EaseOutElastic=25]="EaseOutElastic",a[a.EaseInOutElastic=26]="EaseInOutElastic"})(ei||(ei={}));class ew extends Pe{constructor(e){super(e,B.Neutral),this.type=ei.EaseInOutSine,this.registerInput("input",R.AutoDetect),this.registerOutput("output",R.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(R.Matrix),this._inputs[0].excludedConnectionPointTypes.push(R.Object),this._inputs[0].excludedConnectionPointTypes.push(R.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if(t==="float")return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let s=`
            vec${i} ret = vec${i}(0.0);
        `;for(let r=1;r<=i;r++)s+=this._duplicateEntry(e,r===1?"x":r===2?"y":r===3?"z":"w")+`;
`;return s+=`return ret;
`,s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="",r="";switch(this.input.type){case R.Float:r="float";break;case R.Vector2:r="vec2";break;case R.Vector3:case R.Color3:r="vec3";break;case R.Vector4:case R.Color4:r="vec4";break}switch(s=ei[this.type]+"_"+r,this.type){case ei.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case ei.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case ei.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case ei.EaseInQuad:i="return v * v";break;case ei.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case ei.EaseInOutQuad:{const n="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInCubic:i="return v * v * v";break;case ei.EaseOutCubic:{const n="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(n,r);break}case ei.EaseInOutCubic:{const n="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInQuart:i="return v * v * v * v";break;case ei.EaseOutQuart:{const n="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(n,r);break}case ei.EaseInOutQuart:{const n="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInQuint:i="return v * v * v * v * v";break;case ei.EaseOutQuint:{const n="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(n,r);break}case ei.EaseInOutQuint:{const n="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInExpo:{const n="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(n,r);break}case ei.EaseOutExpo:{const n="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(n,r);break}case ei.EaseInOutExpo:{const n="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInCirc:{const n="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(n,r);break}case ei.EaseOutCirc:{const n="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(n,r);break}case ei.EaseInOutCirc:{const n="VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case ei.EaseOutBack:{const n="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(n,r);break}case ei.EaseInOutBack:{const n="VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0";i=this._duplicateVector(n,r);break}case ei.EaseInElastic:{const n="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))";i=this._duplicateVector(n,r);break}case ei.EaseOutElastic:{const n="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0";i=this._duplicateVector(n,r);break}case ei.EaseInOutElastic:{const n="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0";i=this._duplicateVector(n,r);break}}return e._emitFunction(s,`${r} ${s}(${r} v) {${i};}
`,""),e.compilationString+=this._declareOutput(t,e)+` = ${s}(${this.input.associatedVariableName});
`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${ei[this.type]};
`}}V("BABYLON.CurveBlock",ew);class tw extends Vs{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class sd extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new tw,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;return!this._isEnabled||!(r!=null&&r.texture)||!ue.DecalMapEnabled||!t.texturesEnabled?!0:r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;!this._isEnabled||!(s!=null&&s.texture)||!ue.DecalMapEnabled||!t.texturesEnabled?(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1):((!e.DECAL||e.GAMMADECAL!==s.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=s.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,qt(s.texture,e,"DECAL"))}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!this._isEnabled||!(r!=null&&r.texture)||!ue.DecalMapEnabled||!t.texturesEnabled)return;const n=this._material.isFrozen,o=r.texture;(!e.useUbo||!n||!e.isSync)&&(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),Gt(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}E([I(),te("_markAllSubMeshesAsTexturesDirty")],sd.prototype,"isEnabled",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],sd.prototype,"smoothAlpha",void 0);V("BABYLON.DecalMapConfiguration",sd);var TT;(function(a){a[a.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",a[a.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",a[a.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(TT||(TT={}));var Nr;(function(a){a[a.COLOR_MODE_SET=0]="COLOR_MODE_SET",a[a.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",a[a.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(Nr||(Nr={}));var la;(function(a){a[a.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",a[a.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(la||(la={}));class Ls{}Ls.DEFAULT_COLOR=q.White();Ls.DEFAULT_WIDTH_ATTENUATED=1;Ls.DEFAULT_WIDTH=.1;class Ot{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&typeof e[0]=="number")return[e];if(e.length&&Array.isArray(e[0])&&typeof e[0][0]=="number")return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof m){const t=[];for(let i=0;i<e.length;i++){const s=e[i];t.push(s.x,s.y,s.z)}return[t]}else if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof m){const t=[];return e.forEach(s=>{t.push(s.flatMap(r=>[r.x,r.y,r.z]))}),t}else{if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach(i=>{t.push(Array.from(i))}),t}}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),s.length===0?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return Ot._SearchInPoints(e,t,s)||r.push([e,t]),Ot._SearchInPoints(t,i,s)||r.push([t,i]),Ot._SearchInPoints(i,e,s)||r.push([i,e]),r.length===0?null:r}static _SearchInPoints(e,t,i){var s,r,n;for(const o of i)for(let l=0;l<o.length;l++)if((s=o[l])!=null&&s.equals(e)&&((r=o[l+1])!=null&&r.equals(t)||(n=o[l-1])!=null&&n.equals(t)))return!0;return!1}static MeshesToLines(e,t){const i=[];return e.forEach((s,r)=>{const n=s.getVerticesData(y.PositionKind),o=s.getIndices();if(n&&o)for(let l=0,h=0;l<o.length;l++){const c=o[h++]*3,u=o[h++]*3,d=o[h++]*3,f=new m(n[c],n[c+1],n[c+2]),_=new m(n[u],n[u+1],n[u+2]),p=new m(n[d],n[d+1],n[d+2]);if(t){const g=t(f,_,p,i,l,c,s,r,n,o);if(g)for(const x of g)i.push(x)}else i.push([f,_],[_,p],[p,f])}}),i}static ToVector3Array(e){if(Array.isArray(e[0])){const s=[],r=e;for(const n of r){const o=[];for(let l=0;l<n.length;l+=3)o.push(new m(n[l],n[l+1],n[l+2]));s.push(o)}return s}const t=e,i=[];for(let s=0;s<t.length;s+=3)i.push(new m(t[s],t[s+1],t[s+2]));return i}static ToNumberArray(e){return e.flatMap(t=>[t.x,t.y,t.z])}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=Ot.ToVector3Array(e):t=e;const i=U.Vector3[0];let s=0;for(let r=0;r<t.length-1;r++){const n=t[r],o=t[r+1];s+=o.subtractToRef(n,i).length()}return s}static SegmentizeSegmentByCount(e,t,i){const s=[],r=t.subtract(e),n=U.Vector3[0];n.setAll(i);const o=U.Vector3[1];r.divideToRef(n,o);let l=e.clone();s.push(l);for(let h=0;h<i;h++)l=l.clone(),s.push(l.addInPlace(o));return s}static SegmentizeLineBySegmentLength(e,t){const i=e[0]instanceof m?Ot.GetLineSegments(e):typeof e[0]=="number"?Ot.GetLineSegments(Ot.ToVector3Array(e)):e,s=[];return i.forEach(r=>{r.length>t?Ot.SegmentizeSegmentByCount(r.point1,r.point2,Math.ceil(r.length/t)).forEach(o=>{s.push(o)}):(s.push(r.point1),s.push(r.point2))}),s}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?Ot.ToVector3Array(e):e,s=Ot.GetLineLength(i)/t;return Ot.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;i<e.length-1;i++){const s=e[i],r=e[i+1],n=r.subtract(s).length();t.push({point1:s,point2:r,length:n})}return t}static GetMinMaxSegmentLength(e){const i=Ot.GetLineSegments(e).sort(s=>s.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const l=e.length;for(let c=0;c<l;c++){if(r<=n+e[c].length){o=c;break}n+=e[c].length}const h=(r-n)/e[o].length;return e[o].point2.subtractToRef(e[o].point1,U.Vector3[0]),U.Vector3[1]=U.Vector3[0].multiplyByFloats(h,h,h),s||U.Vector3[1].addInPlace(e[o].point1),U.Vector3[1].clone()}static GetCircleLinePoints(e,t,i=0,s=e,r=Math.PI*2/t){const n=[];for(let o=0;o<=t;o++)n.push(new m(Math.cos(o*r)*e,Math.sin(o*r)*s,i));return n}static GetBezierLinePoints(e,t,i,s){return On.CreateQuadraticBezier(e,t,i,s).getPoints().flatMap(r=>[r.x,r.y,r.z])}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],l=SI(e,t,i,s);for(const h of l){for(const c of h.paths){const u=[],d=c.getPoints();for(const f of d)u.push(f.x,f.y,r);o.push(u)}if(n)for(const c of h.holes){const u=[],d=c.getPoints();for(const f of d)u.push(f.x,f.y,r);o.push(u)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;i<e.length;i++)t[s++]=e[i].r*255,t[s++]=e[i].g*255,t[s++]=e[i].b*255,t[s++]=255;return t}static CreateColorsTexture(e,t,i,s){const r=Ot.Color3toRGBAUint8(t),n=new Fi(r,t.length,1,H.TEXTUREFORMAT_RGBA,s,!1,!0,i);return n.name=e,n}static PrepareEmptyColorsTexture(e){if(!Ls.EmptyColorsTexture){const t=new Uint8Array(4);Ls.EmptyColorsTexture=new Fi(t,1,1,H.TEXTUREFORMAT_RGBA,e,!1,!1,Fi.NEAREST_NEAREST),Ls.EmptyColorsTexture.name="grlEmptyColorsTexture"}return Ls.EmptyColorsTexture}static DisposeEmptyColorsTexture(){var e;(e=Ls.EmptyColorsTexture)==null||e.dispose(),Ls.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class iw extends Vs{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class Vo extends Zs{constructor(e,t,i){i=i||{color:Ls.DEFAULT_COLOR};const s=new iw;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===la.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,Vo.GREASED_LINE_MATERIAL_NAME,200,s),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?Ls.DEFAULT_WIDTH_ATTENUATED:Ls.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??Nr.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??la.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Fi.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new Z(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=Ot.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??Ls.DEFAULT_COLOR,Ot.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{Ot.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?`
                uniform vec4 grl_aspect_resolution_lineWidth;
                uniform mat4 grl_projection;
                `:"",fragment:`
                uniform vec4 grl_dashOptions;
                uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;
                uniform vec3 grl_singleColor;
                `}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const s=this._scene.activeCamera;if(s){const n=s.getProjectionMatrix();e.updateMatrix("grl_projection",n)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const r=U.Vector4[0];r.x=this._aspect,r.y=this._resolution.x,r.z=this._resolution.y,r.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",r)}const t=U.Vector4[0];t.x=Ot.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=U.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=Ot.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",this.colorsTexture??Ls.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===la.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Vo.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if(e==="vertex"){const t={CUSTOM_VERTEX_DEFINITIONS:`
                attribute float grl_widths;
                attribute vec3 grl_offsets;
                attribute float grl_colorPointers;

                varying float grlCounters;
                varying float grlColorPointer;

                #ifdef GREASED_LINE_CAMERA_FACING
                    attribute vec4 grl_previousAndSide;
                    attribute vec4 grl_nextAndCounters;

                    vec2 grlFix( vec4 i, float aspect ) {
                        vec2 res = i.xy / i.w;
                        res.x *= aspect;
                        return res;
                    }
                #else
                    attribute vec3 grl_slopes;
                    attribute float grl_counters;
                #endif
                `,CUSTOM_VERTEX_UPDATE_POSITION:`
                #ifdef GREASED_LINE_CAMERA_FACING
                    vec3 grlPositionOffset = grl_offsets;
                    positionUpdated += grlPositionOffset;
                #else
                    positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);
                #endif
                `,CUSTOM_VERTEX_MAIN_END:`
                grlColorPointer = grl_colorPointers;

                #ifdef GREASED_LINE_CAMERA_FACING

                    float grlAspect = grl_aspect_resolution_lineWidth.x;
                    float grlBaseWidth = grl_aspect_resolution_lineWidth.w;


                    vec3 grlPrevious = grl_previousAndSide.xyz;
                    float grlSide = grl_previousAndSide.w;

                    vec3 grlNext = grl_nextAndCounters.xyz;
                    grlCounters = grl_nextAndCounters.w;

                    mat4 grlMatrix = viewProjection * finalWorld;
                    vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );
                    vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );
                    vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );

                    vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );
                    vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );
                    vec2 grlNextP = grlFix( grlNextPos, grlAspect );

                    float grlWidth = grlBaseWidth * grl_widths;

                    vec2 grlDir;
                    if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );
                    else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );
                    else {
                        vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );
                        vec2 grlDir2 = normalize( grlNextP - grlCurrentP );
                        grlDir = normalize( grlDir1 + grlDir2 );
                    }
                    vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );
                    #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM
                        grlNormal.xy *= -.5 * grlWidth;
                    #else
                        grlNormal.xy *= .5 * grlWidth;
                    #endif

                    grlNormal *= grl_projection;

                    #ifdef GREASED_LINE_SIZE_ATTENUATION
                        grlNormal.xy *= grlFinalPosition.w;
                        grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;
                    #endif

                    grlFinalPosition.xy += grlNormal.xy * grlSide;
                    gl_Position = grlFinalPosition;

                    vPositionW = vec3(grlFinalPosition);
                #else
                    grlCounters = grl_counters;
                #endif
                `};return this._cameraFacing&&(t["!gl_Position\\=viewProjection\\*worldPos;"]="//"),t}return e==="fragment"?{CUSTOM_FRAGMENT_DEFINITIONS:`
                    varying float grlCounters;
                    varying float grlColorPointer;
                    uniform sampler2D grl_colors;
                `,CUSTOM_FRAGMENT_MAIN_END:`
                    float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;
                    float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;
                    float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;
                    float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;

                    float grlUseDash = grl_dashOptions.x;
                    float grlDashArray = grl_dashOptions.y;
                    float grlDashOffset = grl_dashOptions.z;
                    float grlDashRatio = grl_dashOptions.w;

                    gl_FragColor.a *= step(grlCounters, grlVisibility);
                    if( gl_FragColor.a == 0. ) discard;

                    if(grlUseDash == 1.){
                        gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));
                        if (gl_FragColor.a == 0.) discard;
                    }

                    #ifdef GREASED_LINE_HAS_COLOR
                        if (grlColorMode == ${Nr.COLOR_MODE_SET}.) {
                            gl_FragColor.rgb = grl_singleColor;
                        } else if (grlColorMode == ${Nr.COLOR_MODE_ADD}.) {
                            gl_FragColor.rgb += grl_singleColor;
                        } else if (grlColorMode == ${Nr.COLOR_MODE_MULTIPLY}.) {
                            gl_FragColor.rgb *= grl_singleColor;
                        }
                    #else
                        if (grlUseColors == 1.) {
                            #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE
                                vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);
                            #else
                                vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);
                            #endif
                            if (grlColorMode == ${Nr.COLOR_MODE_SET}.) {
                                gl_FragColor = grlColor;
                            } else if (grlColorMode == ${Nr.COLOR_MODE_ADD}.) {
                                gl_FragColor += grlColor;
                            } else if (grlColorMode == ${Nr.COLOR_MODE_MULTIPLY}.) {
                                gl_FragColor *= grlColor;
                            }
                        }
                    #endif

                `}:null}dispose(){var e;(e=this.colorsTexture)==null||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,n,o;const s=((r=this._colors)==null?void 0:r.length)??0;if(this._colors=e,e===null||e.length===0){(n=this.colorsTexture)==null||n.dispose();return}if(!(t&&!i))if(this.colorsTexture&&s===e.length&&!i){const l=Ot.Color3toRGBAUint8(e);this.colorsTexture.update(l)}else(o=this.colorsTexture)==null||o.dispose(),this.colorsTexture=Ot.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){this._color===null&&e!==null||this._color!==null&&e===null?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);const s=e.greasedLineMaterialOptions;(r=this.colorsTexture)==null||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=Ot.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Ot.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var i;const t=e;(i=t.colorsTexture)==null||i.dispose(),this._colors&&(t.colorsTexture=Ot.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}Vo.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";V(`BABYLON.${Vo.GREASED_LINE_MATERIAL_NAME}`,Vo);const sw="greasedLinePixelShader",rw=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}
if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { 
textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}
if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}
`;W.ShadersStore[sw]=rw;const nw="greasedLineVertexShader",aw=`precision highp float;
#include<instancesDeclaration>
attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;
#ifdef GREASED_LINE_CAMERA_FACING
attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}
#else
attribute vec3 grl_slopes;attribute float grl_counters;
#endif
void main() {
#include<instancesVertex>
grlColorPointer=grl_colorPointers;
#ifdef GREASED_LINE_CAMERA_FACING
float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}
vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );
#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM
grlNormal.xy*=-.5*grlWidth;
#else
grlNormal.xy*=.5*grlWidth;
#endif
grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}
grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;
#else
grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;
#endif
}
`;W.ShadersStore[nw]=aw;class ow extends Qs{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${la.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${la.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${Nr.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${Nr.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${Nr.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=q.White(),this._colorsDistributionType=la.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:Ls.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?Ls.DEFAULT_WIDTH_ATTENUATED:Ls.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??q.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??la.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Fi.NEAREST_NEAREST,this.colorMode=i.colorMode??Nr.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new Z(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Ot.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add(()=>{Ot.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)==null||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new Z(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,n,o;const s=((r=this._colors)==null?void 0:r.length)??0;if(this._colors=e,e===null||e.length===0){(n=this._colorsTexture)==null||n.dispose();return}if(!(t&&!i))if(this._colorsTexture&&s===e.length&&!i){const l=Ot.Color3toRGBAUint8(e);this._colorsTexture.update(l)}else(o=this._colorsTexture)==null||o.dispose(),this.colorsTexture=Ot.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",Ot.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",Ot.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",Ot.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Ls.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;const s=e.greasedLineMaterialOptions;(r=this._colorsTexture)==null||r.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=Ot.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Ot.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const lw=`#if defined(DBG_ENABLED)
attribute float dbg_initialPass;
varying vec3 dbg_vBarycentric;
flat varying vec3 dbg_vVertexWorldPos;
flat varying float dbg_vPass;
#endif`,hw=`#if defined(DBG_ENABLED)
float dbg_vertexIndex = mod(float(gl_VertexID), 3.);
if (dbg_vertexIndex == 0.0) { 
    dbg_vBarycentric = vec3(1.,0.,0.); 
}
else if (dbg_vertexIndex == 1.0) { 
    dbg_vBarycentric = vec3(0.,1.,0.); 
}
else { 
    dbg_vBarycentric = vec3(0.,0.,1.); 
}

dbg_vVertexWorldPos = vPositionW;
dbg_vPass = dbg_initialPass;
#endif`,cw=`#if defined(DBG_ENABLED)
uniform vec3 dbg_shadedDiffuseColor;
uniform vec4 dbg_shadedSpecularColorPower;
uniform vec3 dbg_thicknessRadiusScale;

#if DBG_MODE == 2 || DBG_MODE == 3
    uniform vec3 dbg_vertexColor;
#endif

#if DBG_MODE == 1
    uniform vec3 dbg_wireframeTrianglesColor;
#elif DBG_MODE == 3
    uniform vec3 dbg_wireframeVerticesColor;
#elif DBG_MODE == 4 || DBG_MODE == 5
    uniform vec3 dbg_uvPrimaryColor;
    uniform vec3 dbg_uvSecondaryColor;
#elif DBG_MODE == 7
    uniform vec3 dbg_materialColor;
#endif
#endif`,uw=`#if defined(DBG_ENABLED)
varying vec3 dbg_vBarycentric;
flat varying vec3 dbg_vVertexWorldPos;
flat varying float dbg_vPass;

#if !defined(DBG_MULTIPLY)
    vec3 dbg_applyShading(vec3 color) {
        vec3 N = vNormalW.xyz;
        vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);
        vec3 H = normalize(L + L);
        float LdotN = clamp(dot(L,N), 0., 1.);
        float HdotN = clamp(dot(H,N), 0., 1.);
        float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);
        color *= (LdotN / PI);
        color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);
        return color;
    }
#endif

#if DBG_MODE == 1 || DBG_MODE == 3
    float dbg_edgeFactor() {
        vec3 d = fwidth(dbg_vBarycentric);
        vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);
        return min(min(a3.x, a3.y), a3.z);
    }
#endif

#if DBG_MODE == 2 || DBG_MODE == 3
    float dbg_cornerFactor() {
        vec3 worldPos = vPositionW;
        float dist = length(worldPos - dbg_vVertexWorldPos);
        float camDist = length(worldPos - vEyePosition.xyz);
        float d = sqrt(camDist) * .001;
        return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);
    }
#endif

#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))
    float dbg_checkerboardFactor(vec2 uv) {
        vec2 f = fract(uv * dbg_thicknessRadiusScale.z);
        f -= .5;
        return (f.x * f.y) > 0. ? 1. : 0.;
    }
#endif
#endif`,dw=`#if defined(DBG_ENABLED)
vec3 dbg_color = vec3(1.);
#if DBG_MODE == 1
    dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());
#elif DBG_MODE == 2 || DBG_MODE == 3
    float dbg_cornerFactor = dbg_cornerFactor();
    if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;
    dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);
    #if DBG_MODE == 3
        dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());
    #endif
#elif DBG_MODE == 4 && defined(UV1)
    dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));
#elif DBG_MODE == 5 && defined(UV2)
    dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));
#elif DBG_MODE == 6 && defined(VERTEXCOLOR)
    dbg_color = vColor.rgb;
#elif DBG_MODE == 7
    dbg_color = dbg_materialColor;
#endif

#if defined(DBG_MULTIPLY)
    gl_FragColor *= vec4(dbg_color, 1.);
#else
    #if DBG_MODE != 6
        gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);
    #else
        gl_FragColor = vec4(dbg_color, 1.);
    #endif
#endif
#endif`,HS=[new q(.98,.26,.38),new q(.47,.75,.3),new q(0,.26,.77),new q(.97,.6,.76),new q(.19,.63,.78),new q(.98,.8,.6),new q(.65,.43,.15),new q(.15,.47,.22),new q(.67,.71,.86),new q(.09,.46,.56),new q(.8,.98,.02),new q(.39,.29,.13),new q(.53,.63,.06),new q(.95,.96,.41),new q(1,.72,.94),new q(.63,.08,.31),new q(.66,.96,.95),new q(.22,.14,.19),new q(.14,.65,.59),new q(.93,1,.68),new q(.93,.14,.44),new q(.47,.86,.67),new q(.85,.07,.78),new q(.53,.64,.98),new q(.43,.37,.56),new q(.71,.65,.25),new q(.66,.19,.01),new q(.94,.53,.12),new q(.41,.44,.44),new q(.24,.71,.96),new q(.57,.28,.56),new q(.44,.98,.42)];var Il;(function(a){a[a.NONE=0]="NONE",a[a.TRIANGLES=1]="TRIANGLES",a[a.VERTICES=2]="VERTICES",a[a.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",a[a.UV0=4]="UV0",a[a.UV1=5]="UV1",a[a.VERTEXCOLORS=6]="VERTEXCOLORS",a[a.MATERIALIDS=7]="MATERIALIDS"})(Il||(Il={}));class fw extends Vs{constructor(){super(...arguments),this.DBG_MODE=Il.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class fs extends Zs{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new fw;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new q(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new q(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new q(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new q(.8,.8,.8),this.vertexColor=t.vertexColor??new q(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new q(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new q(.5,.5,.5),this._materialColor=fs.MaterialColors[fs._PluginCount++%fs.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&this._material.getScene().getEngine().webGLVersion==1){O.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==Il.VERTICES||this._mode==Il.TRIANGLES||this._mode==Il.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&O.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:cw}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:lw,CUSTOM_VERTEX_MAIN_END:hw}:{CUSTOM_FRAGMENT_DEFINITIONS:uw,CUSTOM_FRAGMENT_MAIN_END:dw}}static Reset(){this._PluginCount=0,this.MaterialColors=HS}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(e.getTotalIndices()==0)return i;if(t){const c=e.getVerticesDataKinds(),u=e.getIndices(),d={};for(const f of c)d[f]=e.getVerticesData(f);i=function(){e.setIndices(u);for(const f of c){const _=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,_)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let c=0;c<s.length;c+=3)r.push(s[c+1],s[c+2],s[c+0]);e.setIndices(s.concat(r)),e.convertToUnIndexedMesh(),e.isUnIndexed=!1,s=Array.from(e.getIndices());const n=[];for(let c=s.length/2;c<s.length;c+=3)n.push(s[c+1],s[c+2],s[c+0]);e.setIndices(s.concat(n));const o=e.getTotalVertices(),l=o/2,h=new Array(o).fill(1,0,l).fill(0,l,o);return e.setVerticesData("dbg_initialPass",h,!1,1),i}}fs._PluginCount=0;fs.MaterialColors=HS;E([li()],fs.prototype,"_materialColor",void 0);E([I()],fs.prototype,"_isEnabled",void 0);E([I(),te("_markAllDefinesAsDirty")],fs.prototype,"mode",void 0);E([I(),te("_markAllDefinesAsDirty")],fs.prototype,"multiply",void 0);E([li()],fs.prototype,"shadedDiffuseColor",void 0);E([li()],fs.prototype,"shadedSpecularColor",void 0);E([I()],fs.prototype,"shadedSpecularPower",void 0);E([I()],fs.prototype,"wireframeThickness",void 0);E([li()],fs.prototype,"wireframeTrianglesColor",void 0);E([li()],fs.prototype,"wireframeVerticesColor",void 0);E([li()],fs.prototype,"vertexColor",void 0);E([I()],fs.prototype,"vertexRadius",void 0);E([I()],fs.prototype,"uvScale",void 0);E([li()],fs.prototype,"uvPrimaryColor",void 0);E([li()],fs.prototype,"uvSecondaryColor",void 0);V("BABYLON.MeshDebugPluginMaterial",fs);const _w="gaussianSplattingPixelShader",pw=`#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
varying vec4 vColor;varying vec2 vPosition;void main () { 
#include<clipPlaneFragment>
float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*vColor.a;
#include<logDepthFragment>
vec3 color=vColor.rgb;
#ifdef FOG
#include<fogFragment>
#endif
gl_FragColor=vec4(color,B);}
`;W.ShadersStore[_w]=pw;const mw="gaussianSplattingVertexDeclaration",gw=`uniform mat4 world;uniform mat4 view;uniform mat4 projection;
`;W.IncludesShadersStore[mw]=gw;const xw="gaussianSplattingUboDeclaration",Tw=`#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;W.IncludesShadersStore[xw]=Tw;const Ew="gaussianSplattingVertexShader",Sw=`#include<__decl__gaussianSplattingVertex>
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
attribute vec2 position;attribute float splatIndex;uniform vec2 viewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition;
#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)
mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],
matrix[0][1],matrix[1][1],matrix[2][1],
matrix[0][2],matrix[1][2],matrix[2][2]);}
#endif
vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);}
void main () {vec2 splatUV=getDataUV(splatIndex,dataTextureSize);vec3 center=texture2D(centersTexture,splatUV).xyz;vec4 color=texture2D(colorsTexture,splatUV);vec3 covA=texture2D(covariancesATexture,splatUV).xyz;vec3 covB=texture2D(covariancesBTexture,splatUV).xyz;vec4 worldPos=world*vec4(center,1.0);mat4 modelView=view*world;vec4 camspace=view*worldPos;vec4 pos2d=projection*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds
|| pos2d.y<-bounds || pos2d.y>bounds) {gl_Position=vec4(0.0,0.0,2.0,1.0);return;}
mat3 Vrk=mat3(
covA.x,covA.y,covA.z,
covA.y,covB.x,covB.y,
covA.z,covB.y,covB.z
);mat3 J=mat3(
focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),
0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),
0.,0.,0.
);mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float lambda1=mid+radius,lambda2=mid-radius;if (lambda2<0.0) return;vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vColor=color;vPosition=position;vec2 vCenter=vec2(pos2d);gl_Position=vec4(
vCenter 
+ (position.x*majorAxis*1./viewport 
+ position.y*minorAxis*1./viewport)*pos2d.w,pos2d.zw);
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}
`;W.ShadersStore[Ew]=Sw;class Cw extends Vs{constructor(){super(),this.FOG=!1,this.THIN_INSTANCES=!0,this.LOGARITHMICDEPTH=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.rebuild()}}class Nu extends vc{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===!0)return!0;t.materialDefines||(t.materialDefines=new Cw);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(yf(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,n),Rf(r,o,this,n,!0,null,!0),If(e,n,!1,!1),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const l=[y.PositionKind,"splatIndex"];Af(l,n);const h=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","viewport","dataTextureSize","focal"],c=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],u=["Scene","Mesh"];Mf({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:n}),sn(h);const d=n.toString(),f=r.getEngine().createEffect("gaussianSplatting",{attributes:l,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:d,onCompiled:this.onCompiled,onError:this.onError},o);t.setEffect(f,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;if(this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._mustRebind(s,n,i,t.visibility)){this.bindView(n),this.bindViewProjection(n);const l=s.getEngine(),h=this.getScene().activeCamera,c=l.getRenderWidth(),u=l.getRenderHeight();this._activeEffect.setFloat2("viewport",c,u);let d=1e3;h&&(h.fovMode==ve.FOVMODE_VERTICAL_FIXED?d=u/2/Math.tan(h.fov/2):d=c/2/Math.tan(h.fov/2)),this._activeEffect.setFloat2("focal",d,d);const f=t;if(f.covariancesATexture){const _=f.covariancesATexture.getSize();n.setFloat2("dataTextureSize",_.width,_.height),n.setTexture("covariancesATexture",f.covariancesATexture),n.setTexture("covariancesBTexture",f.covariancesBTexture),n.setTexture("centersTexture",f.centersTexture),n.setTexture("colorsTexture",f.colorsTexture)}Gr(n,this,s)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);Go(s,t,n),this.useLogarithmicDepth&&ao(r,n,s),this._afterBind(t,this._activeEffect,i)}clone(e){return _e.Clone(()=>new Nu(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return _e.Parse(()=>new Nu(e.name,t),e,t,i)}}V("BABYLON.GaussianSplattingMaterial",Nu);Object.defineProperty(de.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new sd(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(At.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new sd(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(ut.prototype,"decalMap",{get:function(){return this._decalMap},set:function(a){this._decalMap=a},enumerable:!0,configurable:!0});class vw{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=this._numSamples*2&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function bw(a,e){return`{X: ${a.x.toFixed(e)} Y: ${a.y.toFixed(e)}}`}function Aw(a,e){return`{X: ${a._x.toFixed(e)} Y: ${a._y.toFixed(e)} Z: ${a._z.toFixed(e)}}`}function yw(a,e){return`{X: ${a.x.toFixed(e)} Y: ${a.y.toFixed(e)} Z: ${a.z.toFixed(e)} W: ${a.w.toFixed(e)}}`}function Tp(a,e,t,i,s){let r=null,n=null,o=null;try{r=new a.Decoder,n=new a.DecoderBuffer,n.Init(e,e.byteLength);let l;const h=r.GetEncodedGeometryType(n);switch(h){case a.TRIANGULAR_MESH:{const d=new a.Mesh;if(l=r.DecodeBufferToMesh(n,d),!l.ok()||d.ptr===0)throw new Error(l.error_msg());const _=d.num_faces()*3,p=_*4,g=a._malloc(p);try{r.GetTrianglesUInt32Array(d,p,g);const x=new Uint32Array(_);x.set(new Uint32Array(a.HEAPF32.buffer,g,_)),i(x)}finally{a._free(g)}o=d;break}case a.POINT_CLOUD:{const d=new a.PointCloud;if(l=r.DecodeBufferToPointCloud(n,d),!l.ok()||!d.ptr)throw new Error(l.error_msg());o=d;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=o.num_points(),u=(d,f,_,p)=>{const g=p.data_type(),x=p.num_components(),T=p.normalized(),S=p.byte_stride(),C=p.byte_offset(),b={[a.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:a.HEAPF32},[a.DT_INT8]:{typedArrayConstructor:Int8Array,heap:a.HEAP8},[a.DT_INT16]:{typedArrayConstructor:Int16Array,heap:a.HEAP16},[a.DT_INT32]:{typedArrayConstructor:Int32Array,heap:a.HEAP32},[a.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:a.HEAPU8},[a.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:a.HEAPU16},[a.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:a.HEAPU32}}[g];if(!b)throw new Error(`Invalid data type ${g}`);const A=c*x,P=A*b.typedArrayConstructor.BYTES_PER_ELEMENT,L=a._malloc(P);try{d.GetAttributeDataArrayForAllPoints(f,p,g,P,L);const w=new b.typedArrayConstructor(b.heap.buffer,L,A);s(_,w.slice(),x,C,S,T)}finally{a._free(L)}};if(t)for(const d in t){const f=t[d],_=r.GetAttributeByUniqueId(o,f);u(r,o,d,_)}else{const d={position:a.POSITION,normal:a.NORMAL,color:a.COLOR,uv:a.TEX_COORD};for(const f in d){const _=r.GetAttributeId(o,d[f]);if(_!==-1){const p=r.GetAttribute(o,_);u(r,o,f,p)}}}return c}finally{o&&a.destroy(o),n&&a.destroy(n),r&&a.destroy(r)}}function Rw(){let a;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&importScripts(i.url),a=DracoDecoderModule({wasmBinary:i.wasmBinary}),postMessage({id:"initDone"});break}case"decodeMesh":{if(!a)throw new Error("Draco decoder module is not available");a.then(i=>{const s=Tp(i,t.dataView,t.attributes,r=>{postMessage({id:"indices",data:r},[r.buffer])},(r,n,o,l,h,c)=>{postMessage({id:"attribute",kind:r,data:n,size:o,byteOffset:l,byteStride:h,normalized:c},[n.buffer])});postMessage({id:"decodeMeshDone",totalVertices:s})});break}}}}function Iw(a,e,t){return new Promise((i,s)=>{const r=l=>{a.removeEventListener("error",r),a.removeEventListener("message",n),s(l)},n=l=>{l.data.id==="initDone"&&(a.removeEventListener("error",r),a.removeEventListener("message",n),i(a))};a.addEventListener("error",r),a.addEventListener("message",n);const o=e.slice(0);a.postMessage({id:"init",decoder:{url:t,wasmBinary:o}},[o])})}function Pw(a,e){return new Promise(t=>{(e||DracoDecoderModule)({wasmBinary:a}).then(i=>{t({module:i})})})}class Cr{static get DecoderAvailable(){const e=Cr.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&typeof WebAssembly=="object"||e.fallbackUrl)}static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static get Default(){return Cr._Default||(Cr._Default=new Cr),Cr._Default}constructor(e=Cr.DefaultNumWorkers){const t=Cr.Configuration.decoder;if(t.workerPool||typeof e=="object"&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||typeof e=="object"&&e.wasmBinary,s=typeof e=="number"?e:e.numWorkers,r=s&&typeof Worker=="function"&&typeof URL=="function",n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:n?X.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):X.LoadFileAsync(X.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?X.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then(l=>{const h=`${Tp}(${Rw})()`,c=URL.createObjectURL(new Blob([h],{type:"application/javascript"}));return new ed(s,()=>{const u=new Worker(c);return Iw(u,l,o.url)})}):this._decoderModulePromise=o.wasmBinaryPromise.then(async l=>{if(typeof DracoDecoderModule>"u"&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await X.LoadBabylonScriptAsync(o.url)}return await Pw(l,t.jsModule)})}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){if(this._workerPoolPromise){await this._workerPoolPromise;return}if(this._decoderModulePromise){await this._decoderModulePromise;return}}_decodeMeshAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),r=(n,o)=>i&&i[n]!==void 0?(o!==i[n]&&O.Warn(`Normalized flag from Draco data (${o}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):o;if(this._workerPoolPromise)return this._workerPoolPromise.then(n=>new Promise((o,l)=>{n.push((h,c)=>{let u=null;const d=[],f=g=>{h.removeEventListener("error",f),h.removeEventListener("message",_),l(g),c()},_=g=>{const x=g.data;switch(x.id){case"decodeMeshDone":{h.removeEventListener("error",f),h.removeEventListener("message",_),o({indices:u,attributes:d,totalVertices:x.totalVertices}),c();break}case"indices":{u=x.data;break}case"attribute":{d.push({kind:x.kind,data:x.data,size:x.size,byteOffset:x.byteOffset,byteStride:x.byteStride,normalized:r(x.kind,x.normalized)});break}}};h.addEventListener("error",f),h.addEventListener("message",_);const p=s.slice();h.postMessage({id:"decodeMesh",dataView:p,attributes:t},[p.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(n=>{let o=null;const l=[],h=Tp(n.module,s,t,c=>{o=c},(c,u,d,f,_,p)=>{l.push({kind:c,data:u,size:d,byteOffset:f,byteStride:_,normalized:p})});return{indices:o,attributes:l,totalVertices:h}});throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this._decodeMeshAsync(i,s),n=new zi(e,t);r.indices&&n.setIndices(r.indices);for(const o of r.attributes)n.setVerticesBuffer(new y(t.getEngine(),o.data,o.kind,!1,void 0,o.byteStride,void 0,o.byteOffset,o.size,void 0,o.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this._decodeMeshAsync(i,s,r),o=new zi(e,t);n.indices&&o.setIndices(n.indices);for(const l of n.attributes)o.setVerticesBuffer(new y(t.getEngine(),l.data,l.kind,!1,void 0,l.byteStride,void 0,l.byteOffset,l.size,void 0,l.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this._decodeMeshAsync(e,t),s=new le;i.indices&&(s.indices=i.indices);for(const r of i.attributes){const n=y.GetFloatData(r.data,r.size,y.GetDataType(r.data),r.byteOffset,r.byteStride,r.normalized,i.totalVertices);s.set(n,r.kind)}return s}}Cr.Configuration={decoder:{wasmUrl:`${X._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${X._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${X._DefaultCdnUrl}/draco_decoder_gltf.js`}};Cr.DefaultNumWorkers=Cr.GetDefaultNumWorkers();Cr._Default=null;class na{static get Default(){return na._Default||(na._Default=new na),na._Default}constructor(){const e=na.Configuration.decoder;this._decoderModulePromise=X.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then(()=>{const n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,s,r),n})}}na.Configuration={decoder:{url:`${X._DefaultCdnUrl}/meshopt_decoder.js`}};na._Default=null;let Ld=0;class Fu{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){var e,t;return new Fu(this.pos.clone(),this.normal.clone(),(e=this.uv)==null?void 0:e.clone(),(t=this.vertColor)==null?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Fu(m.Lerp(this.pos,e.pos,t),m.Lerp(this.normal,e.normal,t),this.uv&&e.uv?Z.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?xe.Lerp(this.vertColor,e.vertColor,t):void 0)}}class Io{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(s.lengthSquared()===0||r.lengthSquared()===0)return null;const n=m.Normalize(m.Cross(s,r));return new Io(n,m.Dot(n,e))}clone(){return new Io(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let c=0;const u=[];let d,f;for(d=0;d<e.vertices.length;d++){f=m.Dot(this.normal,e.vertices[d].pos)-this.w;const _=f<-Io.EPSILON?2:f>Io.EPSILON?1:0;c|=_,u.push(_)}switch(c){case 0:(m.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const _=[],p=[];for(d=0;d<e.vertices.length;d++){const x=(d+1)%e.vertices.length,T=u[d],S=u[x],C=e.vertices[d],v=e.vertices[x];if(T!==2&&_.push(C),T!==1&&p.push(T!==2?C.clone():C),(T|S)===3){f=(this.w-m.Dot(this.normal,C.pos))/m.Dot(this.normal,v.pos.subtract(C.pos));const b=C.interpolate(v,f);_.push(b),p.push(b.clone())}}let g;_.length>=3&&(g=new Yl(_,e.shared),g.plane&&s.push(g)),p.length>=3&&(g=new Yl(p,e.shared),g.plane&&r.push(g));break}}}}Io.EPSILON=1e-5;class Yl{constructor(e,t){this.vertices=e,this.shared=t,this.plane=Io.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new Yl(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let jr=class Yd{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new Yd;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(t=>t.clone()),e}invert(){for(let t=0;t<this._polygons.length;t++)this._polygons[t].flip();this._plane&&this._plane.flip(),this._front&&this._front.invert(),this._back&&this._back.invert();const e=this._front;this._front=this._back,this._back=e}clipPolygons(e){if(!this._plane)return e.slice();let t=[],i=[];for(let s=0;s<e.length;s++)this._plane.splitPolygon(e[s],t,i,t,i);return this._front&&(t=this._front.clipPolygons(t)),this._back?i=this._back.clipPolygons(i):i=[],t.concat(i)}clipTo(e){this._polygons=e.clipPolygons(this._polygons),this._front&&this._front.clipTo(e),this._back&&this._back.clipTo(e)}allPolygons(){let e=this._polygons.slice();return this._front&&(e=e.concat(this._front.allPolygons())),this._back&&(e=e.concat(this._back.allPolygons())),e}build(e){if(!e.length)return;this._plane||(this._plane=e[0].plane.clone());const t=[],i=[];for(let s=0;s<e.length;s++)this._plane.splitPolygon(e[s],this._polygons,this._polygons,t,i);t.length&&(this._front||(this._front=new Yd),this._front.build(t)),i.length&&(this._back||(this._back=new Yd),this._back.build(i))}};class wn{constructor(){this._polygons=new Array}static FromVertexData(e){let t,i,s;const r=[],n=e.indices,o=e.positions,l=e.normals,h=e.uvs,c=e.colors;if(!n||!o)throw"BABYLON.CSG: VertexData must at least contain positions and indices";for(let d=0;d<n.length;d+=3){s=[];for(let f=0;f<3;f++){const _=d+f,p=n[_],g=l?m.FromArray(l,p*3):m.Zero(),x=h?Z.FromArray(h,p*2):void 0,T=c?xe.FromArray(c,p*4):void 0,S=m.FromArray(o,p*3);t=new Fu(S,g,x,T),s.push(t)}i=new Yl(s,{subMeshId:0,meshId:Ld,materialIndex:0}),i.plane&&r.push(i)}const u=wn._FromPolygons(r);return u.matrix=D.Identity(),u.position=m.Zero(),u.rotation=m.Zero(),u.scaling=m.One(),u.rotationQuaternion=Q.Identity(),Ld++,u}static FromMesh(e,t=!1){let i,s,r,n,o,l,h;const c=[];let u,d,f,_=null,p,g=!1;if(e instanceof z)e.computeWorldMatrix(!0),u=e.getWorldMatrix(),d=e.position.clone(),f=e.rotation.clone(),e.rotationQuaternion&&(_=e.rotationQuaternion.clone()),p=e.scaling.clone(),e.material&&t&&(g=e.material.sideOrientation===0);else throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";const x=e.getIndices(),T=e.getVerticesData(y.PositionKind),S=e.getVerticesData(y.NormalKind),C=e.getVerticesData(y.UVKind),v=e.getVerticesData(y.ColorKind),b=e.subMeshes;for(let P=0,L=b.length;P<L;P++)for(let w=b[P].indexStart,$=b[P].indexCount+b[P].indexStart;w<$;w+=3){h=[];for(let J=0;J<3;J++){const ne=J===0?w+J:g?w+3-J:w+J,oe=new m(S[x[ne]*3],S[x[ne]*3+1],S[x[ne]*3+2]);C&&(r=new Z(C[x[ne]*2],C[x[ne]*2+1])),v&&(o=new xe(v[x[ne]*4],v[x[ne]*4+1],v[x[ne]*4+2],v[x[ne]*4+3]));const re=new m(T[x[ne]*3],T[x[ne]*3+1],T[x[ne]*3+2]);n=m.TransformCoordinates(re,u),s=m.TransformNormal(oe,u),i=new Fu(n,s,r,o),h.push(i)}l=new Yl(h,{subMeshId:P,meshId:Ld,materialIndex:b[P].materialIndex}),l.plane&&c.push(l)}const A=wn._FromPolygons(c);return A.matrix=t?D.Identity():u,A.position=t?m.Zero():d,A.rotation=t?m.Zero():f,A.scaling=t?m.One():p,A.rotationQuaternion=t&&_?Q.Identity():_,Ld++,A}static _FromPolygons(e){const t=new wn;return t._polygons=e,t}clone(){const e=new wn;return e._polygons=this._polygons.map(t=>t.clone()),e.copyTransformAttributes(this),e}union(e){const t=new jr(this.clone()._polygons),i=new jr(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),wn._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new jr(this._polygons),i=new jr(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new jr(this.clone()._polygons),i=new jr(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),wn._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new jr(this._polygons),i=new jr(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new jr(this.clone()._polygons),i=new jr(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),wn._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new jr(this._polygons),i=new jr(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let l=null,h=null;const c=m.Zero(),u=m.Zero(),d=Z.Zero(),f=new xe(0,0,0,0),_=[0,0,0],p={};let g;for(let T=0,S=s.length;T<S;T++){const C=s[T];e&&e(C);for(let v=2,b=C.vertices.length;v<b;v++){_[0]=0,_[1]=v-1,_[2]=v;for(let A=0;A<3;A++){c.copyFrom(C.vertices[_[A]].pos),u.copyFrom(C.vertices[_[A]].normal),C.vertices[_[A]].uv&&(l||(l=[]),d.copyFrom(C.vertices[_[A]].uv)),C.vertices[_[A]].vertColor&&(h||(h=[]),f.copyFrom(C.vertices[_[A]].vertColor));const P=m.TransformCoordinates(c,i),L=m.TransformNormal(u,i);g=p[P.x+","+P.y+","+P.z];let w=!1;l&&!(l[g*2]===d.x||l[g*2+1]===d.y)&&(w=!0);let $=!1;h&&!(h[g*4]===f.r||h[g*4+1]===f.g||h[g*4+2]===f.b||h[g*4+3]===f.a)&&($=!0),(!(typeof g<"u"&&o[g*3]===L.x&&o[g*3+1]===L.y&&o[g*3+2]===L.z)||w||$)&&(r.push(P.x,P.y,P.z),l&&l.push(d.x,d.y),o.push(u.x,u.y,u.z),h&&h.push(f.r,f.g,f.b,f.a),g=p[P.x+","+P.y+","+P.z]=r.length/3-1),n.push(g),t&&t()}}}const x=new le;return x.positions=r,x.normals=o,l&&(x.uvs=l),h&&(x.colors=h),x.indices=n,x}buildMeshGeometry(e,t,i){const s=new z(e,t),r=this._polygons;let n=0;const o={};let l;if(i&&r.sort((c,u)=>c.shared.meshId===u.shared.meshId?c.shared.subMeshId-u.shared.subMeshId:c.shared.meshId-u.shared.meshId),this.toVertexData(c=>{o[c.shared.meshId]||(o[c.shared.meshId]={}),o[c.shared.meshId][c.shared.subMeshId]||(o[c.shared.meshId][c.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:c.shared.materialIndex}),l=o[c.shared.meshId][c.shared.subMeshId]},()=>{l.indexStart=Math.min(n,l.indexStart),l.indexEnd=Math.max(n,l.indexEnd),n++}).applyToMesh(s),i){let c=0,u;s.subMeshes=[];for(const d in o){u=-1;for(const f in o[d])l=o[d][f],Ss.CreateFromIndices(l.materialIndex+c,l.indexStart,l.indexEnd-l.indexStart+1,s),u=Math.max(l.materialIndex,u);c+=++u}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}const Mw="meshUVSpaceRendererVertexShader",Dw=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vNormalW=normalize(normWorldSM*normalUpdated);
#endif
vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;W.ShadersStore[Mw]=Dw;const Ow="meshUVSpaceRendererPixelShader",Nw=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}
gl_FragColor=texture2D(textureSampler,vDecalTC);}
`;W.ShadersStore[Ow]=Nw;const Fw="meshUVSpaceRendererMaskerVertexShader",ww="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";W.ShadersStore[Fw]=ww;const Lw="meshUVSpaceRendererMaskerPixelShader",Bw=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}
`;W.ShadersStore[Lw]=Bw;const Uw="meshUVSpaceRendererFinaliserPixelShader",Vw=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}
if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}
if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}
if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}
if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}
`;W.ShadersStore[Uw]=Vw;const kw="meshUVSpaceRendererFinaliserVertexShader",Gw=`precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}
`;W.ShadersStore[kw]=Gw;z._TrailMeshParser=(a,e)=>pf.Parse(a,e);class pf extends z{constructor(e,t,i,s=1,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=s,this._length=r,this._sectionVectors=[],this._sectionNormalVectors=[];for(let o=0;o<=this._sectionPolygonPointsCount;o++)this._sectionVectors[o]=m.Zero(),this._sectionNormalVectors[o]=m.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new le,t=[],i=[],s=[],r=[];let n=m.Zero();this._generator instanceof ut&&this._generator.hasBoundingInfo?n=this._generator.getBoundingInfo().boundingBox.centerWorld:n=this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let l=0;l<=this._sectionPolygonPointsCount;l++){const h=l!==this._sectionPolygonPointsCount?l*o:0;t.push(n.x+Math.cos(h)*this.diameter,n.y+Math.sin(h)*this.diameter,n.z),r.push(l/this._sectionPolygonPointsCount,0)}for(let l=1;l<=this._length;l++){for(let c=0;c<=this._sectionPolygonPointsCount;c++){const u=c!==this._sectionPolygonPointsCount?c*o:0;t.push(n.x+Math.cos(u)*this.diameter,n.y+Math.sin(u)*this.diameter,n.z),r.push(c/this._sectionPolygonPointsCount,l/this._length)}const h=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let c=0;c<=this._sectionPolygonPointsCount;c++)s.push(h+c,h+c+this._sectionPolygonPointsCount,h+c+this._sectionPolygonPointsCount+1),s.push(h+c,h+c+this._sectionPolygonPointsCount+1,h+c+1)}le.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(y.PositionKind),t=this.getVerticesData(y.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let n=3*(this._sectionPolygonPointsCount+1);n<e.length;n++)e[n-3*(this._sectionPolygonPointsCount+1)]=e[n]-t[n]/this._length*this.diameter;for(let n=3*(this._sectionPolygonPointsCount+1);n<t.length;n++)t[n-3*(this._sectionPolygonPointsCount+1)]=t[n];const s=e.length-3*(this._sectionPolygonPointsCount+1),r=2*Math.PI/this._sectionPolygonPointsCount;for(let n=0;n<=this._sectionPolygonPointsCount;n++){const o=n!==this._sectionPolygonPointsCount?n*r:0;this._sectionVectors[n].copyFromFloats(Math.cos(o)*this.diameter,Math.sin(o)*this.diameter,0),this._sectionNormalVectors[n].copyFromFloats(Math.cos(o),Math.sin(o),0),m.TransformCoordinatesToRef(this._sectionVectors[n],i,this._sectionVectors[n]),m.TransformNormalToRef(this._sectionNormalVectors[n],i,this._sectionNormalVectors[n])}for(let n=0;n<=this._sectionPolygonPointsCount;n++)e[s+3*n]=this._sectionVectors[n].x,e[s+3*n+1]=this._sectionVectors[n].y,e[s+3*n+2]=this._sectionVectors[n].z,t[s+3*n]=this._sectionNormalVectors[n].x,t[s+3*n+1]=this._sectionNormalVectors[n].y,t[s+3*n+2]=this._sectionNormalVectors[n].z;this.updateVerticesData(y.PositionKind,e,!0,!1),this.updateVerticesData(y.NormalKind,t,!0,!1)}}clone(e="",t){return new pf(e,t??this._generator,this.getScene(),this.diameter,this._length,this._autoStart)}serialize(e){super.serialize(e),e.generatorId=this._generator.id}static Parse(e,t){const i=t.getLastMeshById(e.generatorId)??t.getLastTransformNodeById(e.generatorId);if(!i)throw new Error("TrailMesh: generator not found with ID "+e.generatorId);return new pf(e.name,i,t,e.diameter??e._diameter,e._length,e._autoStart)}}class zw{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){const e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach(t=>{this._getSimplifier(e).simplify(t,s=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,s),s.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(s,r)=>{t.simplify(s,n=>{s.distance!==void 0&&e.mesh.addLODLevel(s.distance,n),n.isVisible=!0,r()})};Jr.Run(e.settings.length,s=>{i(e.settings[s.index],()=>{s.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case mf.QUADRATIC:default:return new Yw(e.mesh)}}}var mf;(function(a){a[a.QUADRATIC=0]="QUADRATIC"})(mf||(mf={}));class Ww{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class Hw{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new Pl,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class Pl{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,l,h){return this.data[e]*this.data[r]*this.data[h]+this.data[i]*this.data[s]*this.data[l]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[l]-this.data[t]*this.data[s]*this.data[h]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new Pl;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new Pl(Pl.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class Xw{constructor(e,t){this.vertexId=e,this.triangleId=t}}class Yw{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=rt}simplify(e,t){this._initDecimatedMesh(),Jr.Run(this._mesh.subMeshes.length,i=>{this._initWithMesh(i.index,()=>{this._runDecimation(e,i.index,()=>{i.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(l,h)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let d=0;d<this._triangles.length;++d)this._triangles[d].isDirty=!1;const c=1e-9*Math.pow(l+3,this.aggressiveness),u=d=>{const f=~~((this._triangles.length/2+d)%this._triangles.length),_=this._triangles[f];if(_&&!(_.error[3]>c||_.deleted||_.isDirty)){for(let p=0;p<3;++p)if(_.error[p]<c){const g=[],x=[],T=_._vertices[p],S=_._vertices[(p+1)%3];if(T.isBorder||S.isBorder)continue;const C=m.Zero();this._calculateError(T,S,C);const v=[];if(this._isFlipped(T,S,C,g,v)||this._isFlipped(S,T,C,x,v)||g.indexOf(!0)<0||x.indexOf(!0)<0)continue;const b=[];if(v.forEach(L=>{b.indexOf(L)===-1&&(L.deletePending=!0,b.push(L))}),b.length%2!==0)continue;T.q=S.q.add(T.q),T.updatePosition(C);const A=this._references.length;r=this._updateTriangles(T,T,g,r),r=this._updateTriangles(T,S,x,r);const P=this._references.length-A;if(P<=T.triangleCount){if(P)for(let L=0;L<P;L++)this._references[T.triangleStart+L]=this._references[A+L]}else T.triangleStart=A;T.triangleCount=P;break}}};Jr.SyncAsyncForLoop(this._triangles.length,this.syncIterations,u,h,()=>n-r<=s)},0)};Jr.Run(this.decimationIterations,l=>{n-r<=s?l.breakLoop():o(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(y.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=u=>{if(i){for(let d=0;d<this._vertices.length;++d)if(this._vertices[d].position.equalsWithEpsilon(u,1e-4))return this._vertices[d]}return null},l=[],h=u=>{if(!s)return;const d=u+n.verticesStart,f=m.FromArray(s,d*3),_=o(f)||new Hw(f,this._vertices.length);_.originalOffsets.push(d),_.id===this._vertices.length&&this._vertices.push(_),l.push(_.id)},c=n.verticesCount;Jr.SyncAsyncForLoop(c,this.syncIterations/4>>0,h,()=>{const u=d=>{if(!r)return;const _=(n.indexStart/3+d)*3,p=r[_+0],g=r[_+1],x=r[_+2],T=this._vertices[l[p-n.verticesStart]],S=this._vertices[l[g-n.verticesStart]],C=this._vertices[l[x-n.verticesStart]],v=new Ww([T,S,C]);v.originalOffset=_,this._triangles.push(v)};Jr.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const s=this._triangles[i];s.normal=m.Cross(s._vertices[1].position.subtract(s._vertices[0].position),s._vertices[2].position.subtract(s._vertices[0].position)).normalize();for(let r=0;r<3;r++)s._vertices[r].q.addArrayInPlace(Pl.DataFromNumbers(s.normal.x,s.normal.y,s.normal.z,-m.Dot(s.normal,s._vertices[0].position)))};Jr.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=s=>{const r=this._triangles[s];for(let n=0;n<3;++n)r.error[n]=this._calculateError(r._vertices[n],r._vertices[(n+1)%3]);r.error[3]=Math.min(r.error[0],r.error[1],r.error[2])};Jr.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i<this._vertices.length;++i)this._vertices[i].triangleCount=0;let s,r;for(i=0;i<this._triangles.length;++i)if(!this._triangles[i].deleted){for(s=this._triangles[i],r=0;r<3;++r)s._vertices[r].triangleCount=1;t.push(s)}const n=this._reconstructedMesh.getVerticesData(y.PositionKind)||[],o=this._reconstructedMesh.getVerticesData(y.NormalKind)||[],l=this._reconstructedMesh.getVerticesData(y.UVKind)||[],h=this._reconstructedMesh.getVerticesData(y.ColorKind)||[],c=this._mesh.getVerticesData(y.NormalKind),u=this._mesh.getVerticesData(y.UVKind),d=this._mesh.getVerticesData(y.ColorKind);let f=0;for(i=0;i<this._vertices.length;++i){const C=this._vertices[i];C.id=f,C.triangleCount&&C.originalOffsets.forEach(v=>{n.push(C.position.x),n.push(C.position.y),n.push(C.position.z),c&&c.length&&(o.push(c[v*3]),o.push(c[v*3+1]),o.push(c[v*3+2])),u&&u.length&&(l.push(u[v*2]),l.push(u[v*2+1])),d&&d.length&&(h.push(d[v*4]),h.push(d[v*4+1]),h.push(d[v*4+2]),h.push(d[v*4+3])),++f})}const _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const x=this._reconstructedMesh.getIndices(),T=this._mesh.getIndices();for(i=0;i<t.length;++i)s=t[i],[0,1,2].forEach(C=>{const v=T[s.originalOffset+C];let b=s._vertices[C].originalOffsets.indexOf(v);b<0&&(b=0),x.push(s._vertices[C].id+b+p)});this._reconstructedMesh.setIndices(x),this._reconstructedMesh.setVerticesData(y.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(y.NormalKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(y.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(y.ColorKind,h);const S=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],g.forEach(C=>{Ss.AddToMesh(C.materialIndex,C.verticesStart,C.verticesCount,C.indexStart,C.indexCount,C.getMesh())}),Ss.AddToMesh(S.materialIndex,p,f,_,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new z(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n<e.triangleCount;++n){const o=this._triangles[this._references[e.triangleStart+n].triangleId];if(o.deleted)continue;const l=this._references[e.triangleStart+n].vertexId,h=o._vertices[(l+1)%3],c=o._vertices[(l+2)%3];if(h===t||c===t){s[n]=!0,r.push(o);continue}let u=h.position.subtract(i);u=u.normalize();let d=c.position.subtract(i);if(d=d.normalize(),Math.abs(m.Dot(u,d))>.999)return!0;const f=m.Cross(u,d).normalize();if(s[n]=!1,m.Dot(f,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let n=0;n<t.triangleCount;++n){const o=this._references[t.triangleStart+n],l=this._triangles[o.triangleId];if(!l.deleted){if(i[n]&&l.deletePending){l.deleted=!0,r++;continue}l._vertices[o.vertexId]=e,l.isDirty=!0,l.error[0]=this._calculateError(l._vertices[0],l._vertices[1])+l.borderFactor/2,l.error[1]=this._calculateError(l._vertices[1],l._vertices[2])+l.borderFactor/2,l.error[2]=this._calculateError(l._vertices[2],l._vertices[0])+l.borderFactor/2,l.error[3]=Math.min(l.error[0],l.error[1],l.error[2]),this._references.push(o)}}return r}_identifyBorder(){for(let e=0;e<this._vertices.length;++e){const t=[],i=[],s=this._vertices[e];let r;for(r=0;r<s.triangleCount;++r){const n=this._triangles[this._references[s.triangleStart+r].triangleId];for(let o=0;o<3;o++){let l=0;const h=n._vertices[o];for(;l<t.length&&i[l]!==h.id;)++l;l===t.length?(t.push(1),i.push(h.id)):t[l]++}}for(r=0;r<t.length;++r)t[r]===1?this._vertices[i[r]].isBorder=!0:this._vertices[i[r]].isBorder=!1}}_updateMesh(e=!1){let t;if(!e){const l=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||l.push(this._triangles[t]);this._triangles=l}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;let i,s,r;for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],s=0;s<3;++s)r=i._vertices[s],r.triangleCount++;let n=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=n,n+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;const o=new Array(this._triangles.length*3);for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],s=0;s<3;++s)r=i._vertices[s],o[r.triangleStart+r.triangleCount]=new Xw(s,t),r.triangleCount++;this._references=o,e&&this._identifyBorder()}_vertexError(e,t){const i=t.x,s=t.y,r=t.z;return e.data[0]*i*i+2*e.data[1]*i*s+2*e.data[2]*i*r+2*e.data[3]*i+e.data[4]*s*s+2*e.data[5]*s*r+2*e.data[6]*s+e.data[7]*r*r+2*e.data[8]*r+e.data[9]}_calculateError(e,t,i){const s=e.q.add(t.q),r=e.isBorder&&t.isBorder;let n=0;const o=s.det(0,1,2,1,4,5,2,5,7);if(o!==0&&!r)i||(i=m.Zero()),i.x=-1/o*s.det(1,2,3,4,5,6,5,7,8),i.y=1/o*s.det(0,2,3,1,5,6,2,7,8),i.z=-1/o*s.det(0,1,3,1,4,6,2,5,8),n=this._vertexError(s,i);else{const l=e.position.add(t.position).divide(new m(2,2,2)),h=this._vertexError(s,e.position),c=this._vertexError(s,t.position),u=this._vertexError(s,l);n=Math.min(h,c,u),n===h?i&&i.copyFrom(e.position):n===c?i&&i.copyFrom(t.position):i&&i.copyFrom(l)}return n}}Object.defineProperty(Ee.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new zw;let a=this._getComponent(he.NAME_SIMPLIFICATIONQUEUE);a||(a=new $w(this),this._addComponent(a))}return this._simplificationQueue},set:function(a){this._simplificationQueue=a},enumerable:!0,configurable:!0});z.prototype.simplify=function(a,e=!0,t=mf.QUADRATIC,i){return this.getScene().simplificationQueue.addTask({settings:a,parallelProcessing:e,mesh:this,simplificationType:t,successCallback:i}),this};class $w{constructor(e){this.name=he.NAME_SIMPLIFICATIONQUEUE,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(he.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)}rebuild(){}dispose(){}_beforeCameraUpdate(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()}}var ta;(function(a){a[a.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",a[a.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"})(ta||(ta={}));var Ep;(function(a){a[a.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",a[a.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",a[a.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"})(Ep||(Ep={}));var tu;(function(a){a[a.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",a[a.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",a[a.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",a[a.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"})(tu||(tu={}));class XS extends z{constructor(e,t,i){super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=i.lazy??!1,this._updatable=i.updatable??!1,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=i.colorPointers??[],this._widths=i.widths??new Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(const s of this._points)t+=s.length;const i=t/3*2-this._widths.length;for(let s=0;s<i;s++)this._widths.push(e)}updateLazy(){var e,t;this._setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers((e=this._options.ribbonOptions)==null?void 0:e.smoothShading),this.refreshBoundingInfo(),(t=this.greasedLineMaterial)==null||t.updateLazy()}addPoints(e,t){for(const i of e)this._points.push(i);this._lazy||this.setPoints(this._points,t)}dispose(e,t=!1){super.dispose(e,t)}isLazy(){return this._lazy}get offsets(){return this._offsets}set offsets(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}get widths(){return this._widths}set widths(e){this._widths=e,this._lazy||this._widthsBuffer&&this._widthsBuffer.update(e)}get colorPointers(){return this._colorPointers}set colorPointers(e){this._colorPointers=e,this._lazy||this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var t,i;if(this.material&&this.material instanceof ow)return this.material;const e=(i=(t=this.material)==null?void 0:t.pluginManager)==null?void 0:i.getPlugin(Vo.GREASED_LINE_MATERIAL_NAME);if(e)return e}get points(){const e=[];return Cs.DeepCopy(this._points,e),e}setPoints(e,t){this._points=e,this._updateWidths(),t!=null&&t.colorPointers||this._updateColorPointers(),this._setPoints(e,t)}_initGreasedLine(){this._vertexPositions=[],this._indices=[],this._uvs=[]}_createLineOptions(){return{points:this._points,colorPointers:this._colorPointers,lazy:this._lazy,updatable:this._updatable,uvs:this._uvs,widths:this._widths,ribbonOptions:this._options.ribbonOptions}}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}_createVertexBuffers(e=!1){const t=new le;return t.positions=this._vertexPositions,t.indices=this._indices,t.uvs=this._uvs,e&&(t.normals=[],le.ComputeNormals(this._vertexPositions,this._indices,t.normals)),t.applyToMesh(this,this._options.updatable),t}_createOffsetsBuffer(e){const t=this._scene.getEngine(),i=new Ji(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}}z._GreasedLineMeshParser=(a,e)=>Oi.Parse(a,e);class Oi extends XS{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Ot.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i<t.length;i+=3)this._colorPointers.push(e),this._colorPointers.push(e++)})}_updateWidths(){super._updateWidthsWithValue(0)}_setPoints(e){this._points=e,this._options.points=e,this._initGreasedLine();let t=0;e.forEach(i=>{const s=[],r=[],n=[],o=Ot.GetLineLength(i);for(let d=0,f=0;f<i.length;d++,f+=3){const _=i.slice(0,f+3),g=Ot.GetLineLength(_)/o;if(r.push(i[f],i[f+1],i[f+2]),r.push(i[f],i[f+1],i[f+2]),s.push(g),s.push(g),f<i.length-3){const x=d*2+t;n.push(x,x+1,x+2),n.push(x+2,x+1,x+3)}}t+=i.length/3*2;const l=[],h=[],c=[];let u=[];this._preprocess(r,l,h,c,u);for(const d of r)this._vertexPositions.push(d);for(const d of n)this._indices.push(d);for(let d=0;d<c.length;d++)this._previousAndSide.push(l[d*3],l[d*3+1],l[d*3+2],c[d]),this._nextAndCounters.push(h[d*3],h[d*3+1],h[d*3+2],s[d]);u=this._options.uvs??u;for(const d of u)this._uvs.push(d)}),this._lazy||(this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo())}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={};Cs.DeepCopy(i,s,["instance"],void 0,!0);const r=new Oi(e,this._scene,s);return t&&(r.parent=t),r.material=this.material,r}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}static Parse(e,t){const i=e.lineOptions,s=e.name;return new Oi(s,t,i)}_initGreasedLine(){super._initGreasedLine(),this._previousAndSide=[],this._nextAndCounters=[]}intersects(e,t,i,s=!1,r,n=!1){const o=new es,l=this.findAllIntersections(e,t,i,s,r,n,!0);if((l==null?void 0:l.length)===1){const h=l[0];o.hit=!0,o.distance=h.distance,o.ray=e,o.pickedMesh=this,o.pickedPoint=h.point}return o}findAllIntersections(e,t,i,s=!1,r,n=!1,o=!1){var f;if(s&&!n&&e.intersectsSphere(this._boundingSphere,this.intersectionThreshold)===!1)return;const l=this.getIndices(),h=this.getVerticesData(y.PositionKind),c=this._widths,u=((f=this.greasedLineMaterial)==null?void 0:f.width)??1,d=[];if(l&&h&&c){let _=0,p=0;for(_=0,p=l.length-1;_<p;_+=3){const g=l[_],x=l[_+1];Oi._V_START.fromArray(h,g*3),Oi._V_END.fromArray(h,x*3),this._offsets&&(Oi._V_OFFSET_START.fromArray(this._offsets,g*3),Oi._V_OFFSET_END.fromArray(this._offsets,x*3),Oi._V_START.addInPlace(Oi._V_OFFSET_START),Oi._V_END.addInPlace(Oi._V_OFFSET_END));const T=Math.floor(_/3),S=c[T]!==void 0?c[T]:1,C=this.intersectionThreshold*(u*S)/2,v=e.intersectionSegment(Oi._V_START,Oi._V_END,C);if(v!==-1&&(d.push({distance:v,point:e.direction.normalize().multiplyByFloats(v,v,v).add(e.origin)}),o))return d}_=p}return d}get _boundingSphere(){return this.getBoundingInfo().boundingSphere}static _CompareV3(e,t,i){const s=e*6,r=t*6;return i[s]===i[r]&&i[s+1]===i[r+1]&&i[s+2]===i[r+2]}static _CopyV3(e,t){const i=e*6;return[t[i],t[i+1],t[i+2]]}_preprocess(e,t,i,s,r){const n=e.length/6;let o=[];Oi._CompareV3(0,n-1,e)?o=Oi._CopyV3(n-2,e):o=Oi._CopyV3(0,e),t.push(o[0],o[1],o[2]),t.push(o[0],o[1],o[2]);for(let l=0;l<n;l++)s.push(1),s.push(-1),this._options.uvs||(r.push(l/(n-1),0),r.push(l/(n-1),1)),l<n-1&&(o=Oi._CopyV3(l,e),t.push(o[0],o[1],o[2]),t.push(o[0],o[1],o[2])),l>0&&(o=Oi._CopyV3(l,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]));return Oi._CompareV3(n-1,0,e)?o=Oi._CopyV3(1,e):o=Oi._CopyV3(n-1,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]),{previous:t,next:i,uvs:r,side:s}}_createVertexBuffers(){const e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new Ji(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const s=new Ji(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(s.createVertexBuffer("grl_nextAndCounters",0,4));const r=new Ji(t,this._widths,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=r;const n=new Ji(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}}Oi._V_START=new m;Oi._V_END=new m;Oi._V_OFFSET_START=new m;Oi._V_OFFSET_END=new m;z._GreasedLineRibbonMeshParser=(a,e)=>ki.Parse(a,e);class ki extends XS{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(Ot.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t<this._pathsOptions.length;t++){const{options:i,pathCount:s}=this._pathsOptions[t],r=this._points[t];if(i.ribbonOptions.pointsMode===ta.POINTS_MODE_POINTS)for(let n=0;n<s;n++)for(let o=0;o<r.length;o+=3)this._colorPointers.push(e),this._colorPointers.push(e++);else for(let n=0;n<r.length;n+=3){for(let o=0;o<s;o++)this._colorPointers.push(e);e++}}}_updateWidths(){super._updateWidthsWithValue(1)}_setPoints(e,t){var r,n;if(!this._options.ribbonOptions)throw"No 'GreasedLineMeshOptions.ribbonOptions' provided.";this._points=e,this._options.points=e,this._initGreasedLine();let i=0,s;for(let o=0,l=0;o<this._pathsOptions.length;o++){const{options:h,pathCount:c}=this._pathsOptions[o],u=e.slice(l,l+c);if(l+=c,((r=h.ribbonOptions)==null?void 0:r.pointsMode)===ta.POINTS_MODE_PATHS)i=this._preprocess(Ot.ToVector3Array(u),i,h);else{if(((n=h.ribbonOptions)==null?void 0:n.directionsAutoMode)===tu.AUTO_DIRECTIONS_NONE){if(!h.ribbonOptions.directions)throw"In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined.";s=ki._GetDirectionPlanesFromDirectionsOption(u.length,h.ribbonOptions.directions)}u.forEach((d,f)=>{const _=ki._ConvertToRibbonPath(d,h.ribbonOptions,this._scene.useRightHandedSystem,s&&s[f]);i=this._preprocess(_,i,h)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var c,u;const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let d=0;d<n.length;d++)for(let f=0;f<e.length;f++){const _=e[f][d];s.push(_.x,_.y,_.z)}const o=[1,0,i],l=((c=t.ribbonOptions)==null?void 0:c.facesMode)===Ep.FACES_MODE_DOUBLE_SIDED,h=((u=t.ribbonOptions)==null?void 0:u.pointsMode)===ta.POINTS_MODE_PATHS&&t.ribbonOptions.closePath;if(i>2)for(let d=0;d<n.length-1;d++){o[0]=1+i*d,o[1]=i*d,o[2]=(d+1)*i;for(let f=0;f<(i-1)*2;f++)f%2!==0&&(o[2]+=1),f%2===0&&f>0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(f%2!==0?i:0),o[0],o[2]),l&&r.push(o[0],o[1]+(f%2!==0?i:0),o[2])}else for(let d=0;d<s.length/3-3;d+=2)r.push(d,d+1,d+2),r.push(d+2,d+1,d+3),l&&(r.push(d+1,d,d+2),r.push(d+1,d+2,d+3));if(h){let d=i*(n.length-1);for(let f=0;f<i-1;f++)r.push(d,f+1,f),r.push(d+1,f+1,d),l&&(r.push(f,f+1,d),r.push(d,f+1,d+1)),d++}return{positions:s,indices:r}}_preprocess(e,t,i){var c,u;this._paths=e;const s=ki._CreateRibbonVertexData(e,i),r=s.positions;if(!this._options.widths)throw"No 'GreasedLineMeshOptions.widths' table is specified.";for(const d of r)this._vertexPositions.push(d);let n=e;if(((c=i.ribbonOptions)==null?void 0:c.pointsMode)===ta.POINTS_MODE_PATHS&&i.ribbonOptions.closePath){n=[];for(let d=0;d<e.length;d++){const f=e[d].slice();f.push(e[d][0].clone()),n.push(f)}}this._calculateSegmentLengths(n);const o=n.length,l=new Array(o).fill(0);for(let d=0;d<n[0].length;d++){let f=0;for(let _=0;_<o;_++){const p=l[_]+this._vSegmentLengths[_][d]/this._vTotalLengths[_];this._counters.push(p),this._uvs.push(p,f),l[_]=p,f+=this._uSegmentLengths[d][_]/this._uTotalLengths[d]}}for(let d=0,f=0;d<n[0].length;d++){const _=this._uSegmentLengths[d][0]/2,p=this._uSegmentLengths[d][o-1]/2;this._ribbonWidths.push(((this._widths[f++]??1)-1)*_);for(let g=0;g<o-2;g++)this._ribbonWidths.push(0);this._ribbonWidths.push(((this._widths[f++]??1)-1)*p)}const h=((u=i.ribbonOptions)==null?void 0:u.pointsMode)===ta.POINTS_MODE_PATHS?new Array(n[0].length*n.length*6).fill(0):ki._CalculateSlopes(n);for(const d of h)this._slopes.push(d);if(s.indices)for(let d=0;d<s.indices.length;d++)this._indices.push(s.indices[d]+t);return t+=r.length/3,t}static _ConvertToRibbonPath(e,t,i,s){if(t.pointsMode===ta.POINTS_MODE_POINTS&&!t.width)throw"'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS.";const r=[],n=[];if(t.pointsMode===ta.POINTS_MODE_POINTS){const o=t.width/2,l=Ot.ToVector3Array(e);let h=null,c=null;t.directionsAutoMode===tu.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT&&(s=ki._GetDirectionFromPoints(l[0],l[1],null));for(let u=0;u<l.length-(s?0:1);u++){const d=l[u],f=l[u+1];if(s)h=s;else if(t.directionsAutoMode===tu.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS)h=ki._GetDirectionFromPoints(d,f,h);else{const _=f.subtract(d);_.applyRotationQuaternionInPlace(_.x>_.y&&_.x>_.z?i?ki._RightHandedForwardReadOnlyQuaternion:ki._LeftHandedForwardReadOnlyQuaternion:ki._LeftReadOnlyQuaternion),h=_.normalize()}c=h.multiplyByFloats(o,o,o),r.push(d.add(c)),n.push(d.subtract(c))}s||(r.push(l[l.length-1].add(c)),n.push(l[l.length-1].subtract(c)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x===t.x&&(!i||(i==null?void 0:i.x)===1)?ki.DIRECTION_YZ:e.y===t.y?ki.DIRECTION_XZ:e.z===t.z?ki.DIRECTION_XY:ki.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Cs.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Cs.DeepCopy(i,s,["instance"],void 0,!0);const n=new ki(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new ki(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let n=0;n<t;n++){const o=e[n];this._vSegmentLengths[n]=[0],i=0;for(let l=0;l<o.length-1;l++){const h=Math.abs(o[l].subtract(o[l+1]).lengthSquared());i+=h,this._vSegmentLengths[n].push(h)}this._vTotalLengths[n]=i}const s=e[0].length;this._uSegmentLengths=new Array(s).fill([]),this._uTotalLengths=new Array(s).fill([]);const r=new m;for(let n=0;n<s;n++){i=0;for(let o=1;o<t;o++){e[o][n].subtractToRef(e[o-1][n],r);const l=r.length();i+=l,this._uSegmentLengths[n].push(l)}this._uTotalLengths[n]=i}}static _CalculateSlopes(e){const t=e[0],i=e.length===2?e[1]:e[e.length-1],s=[],r=new m;for(let n=0;n<t.length;n++)for(let o=0;o<e.length;o++)o===0||o===e.length-1?(t[n].subtract(i[n]).normalizeToRef(r),s.push(r.x,r.y,r.z),s.push(-r.x,-r.y,-r.z)):s.push(0,0,0,0,0,0);return s}_createVertexBuffers(){var n;this._uvs=this._options.uvs??this._uvs;const e=super._createVertexBuffers((n=this._options.ribbonOptions)==null?void 0:n.smoothShading),t=new Ji(this._engine,this._counters,this._updatable,1);this.setVerticesBuffer(t.createVertexBuffer("grl_counters",0,1));const i=new Ji(this._engine,this._colorPointers,this._updatable,1);this.setVerticesBuffer(i.createVertexBuffer("grl_colorPointers",0,1));const s=new Ji(this._engine,this._slopes,this._updatable,3);this.setVerticesBuffer(s.createVertexBuffer("grl_slopes",0,3));const r=new Ji(this._engine,this._ribbonWidths,this._updatable,1);return this.setVerticesBuffer(r.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=r,e}}ki.DEFAULT_WIDTH=.1;ki._RightHandedForwardReadOnlyQuaternion=Q.RotationAxis(m.RightHandedForwardReadOnly,Math.PI/2);ki._LeftHandedForwardReadOnlyQuaternion=Q.RotationAxis(m.LeftHandedForwardReadOnly,Math.PI/2);ki._LeftReadOnlyQuaternion=Q.RotationAxis(m.LeftReadOnly,Math.PI/2);ki.DIRECTION_XY=m.LeftHandedForwardReadOnly;ki.DIRECTION_XZ=m.UpReadOnly;ki.DIRECTION_YZ=m.LeftReadOnly;var ET;(function(a){a[a.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",a[a.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",a[a.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",a[a.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",a[a.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",a[a.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END"})(ET||(ET={}));var ST;(function(a){a[a.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",a[a.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",a[a.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",a[a.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",a[a.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",a[a.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END"})(ST||(ST={}));z.prototype.thinInstanceAdd=function(a,e=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return O.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(a)?a.length:1);const t=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(a))for(let i=0;i<a.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,a[i],i===a.length-1&&e);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,a,e);return t};z.prototype.thinInstanceAddSelf=function(a=!0){return this.thinInstanceAdd(D.IdentityReadOnly,a)};z.prototype.thinInstanceRegisterAttribute=function(a,e){a===y.ColorKind&&(a=y.ColorInstanceKind),this.removeVerticesData(a),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[a]=e,this._userThinInstanceBuffersStorage.sizes[a]=e*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[a]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[a]),this._userThinInstanceBuffersStorage.vertexBuffers[a]=new y(this.getEngine(),this._userThinInstanceBuffersStorage.data[a],a,!0,!1,e,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])};z.prototype.thinInstanceSetMatrixAt=function(a,e,t=!0){if(!this._thinInstanceDataStorage.matrixData||a>=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,a*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[a]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};z.prototype.thinInstanceSetAttributeAt=function(a,e,t,i=!0){return a===y.ColorKind&&(a=y.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[a]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(a,0),this._userThinInstanceBuffersStorage.data[a].set(t,e*this._userThinInstanceBuffersStorage.strides[a]),i&&this.thinInstanceBufferUpdated(a),!0)};Object.defineProperty(z.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(a){var i;const e=this._thinInstanceDataStorage.matrixData??((i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData),t=e?e.length/16:0;a<=t&&(this._thinInstanceDataStorage.instancesCount=a)},enumerable:!0,configurable:!0});z.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!0){const i=new Ji(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(a+s,s*4,4));return i};z.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!0){var s,r,n;t=t||16,a==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)==null||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=e?e.length:32*t,this._thinInstanceDataStorage.matrixData=e,this._thinInstanceDataStorage.worldMatrices=null,e!==null?(this._thinInstanceDataStorage.instancesCount=e.length/t,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",e,i),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):a==="previousMatrix"?((r=this._thinInstanceDataStorage.previousMatrixBuffer)==null||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(a===y.ColorKind&&(a=y.ColorInstanceKind),e===null?(n=this._userThinInstanceBuffersStorage)!=null&&n.data[a]&&(this.removeVerticesData(a),delete this._userThinInstanceBuffersStorage.data[a],delete this._userThinInstanceBuffersStorage.strides[a],delete this._userThinInstanceBuffersStorage.sizes[a],delete this._userThinInstanceBuffersStorage.vertexBuffers[a]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[a]=e,this._userThinInstanceBuffersStorage.strides[a]=t,this._userThinInstanceBuffersStorage.sizes[a]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[a]=new y(this.getEngine(),e,a,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])))};z.prototype.thinInstanceBufferUpdated=function(a){var e,t,i;a==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):a==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(a===y.ColorKind&&(a=y.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[a].isUpdatable()&&this._thinInstanceRecreateBuffer(a),this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0)))};z.prototype.thinInstancePartialBufferUpdate=function(a,e,t){var i;a==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(a===y.ColorKind&&(a=y.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};z.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const a=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e)this._thinInstanceDataStorage.worldMatrices[e]=D.FromArray(a,e*16)}return this._thinInstanceDataStorage.worldMatrices};z.prototype.thinInstanceRefreshBoundingInfo=function(a=!1,e=!1,t=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;const i=this._thinInstanceDataStorage.boundingVectors;if(a||!this.rawBoundingInfo){i.length=0,this.refreshBoundingInfo(e,t);const n=this.getBoundingInfo();this.rawBoundingInfo=new or(n.minimum,n.maximum)}const s=this.getBoundingInfo(),r=this._thinInstanceDataStorage.matrixData;if(i.length===0)for(let n=0;n<s.boundingBox.vectors.length;++n)i.push(s.boundingBox.vectors[n].clone());U.Vector3[0].setAll(Number.POSITIVE_INFINITY),U.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let n=0;n<this._thinInstanceDataStorage.instancesCount;++n){D.FromArrayToRef(r,n*16,U.Matrix[0]);for(let o=0;o<i.length;++o)m.TransformCoordinatesToRef(i[o],U.Matrix[0],U.Vector3[2]),U.Vector3[0].minimizeInPlace(U.Vector3[2]),U.Vector3[1].maximizeInPlace(U.Vector3[2])}s.reConstruct(U.Vector3[0],U.Vector3[1]),this._updateBoundingInfo()};z.prototype._thinInstanceRecreateBuffer=function(a,e=!0){var t,i,s;a==="matrix"?((t=this._thinInstanceDataStorage.matrixBuffer)==null||t.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",this._thinInstanceDataStorage.matrixData,e)):a==="previousMatrix"?this._scene.needsPreviousWorldMatrices&&((i=this._thinInstanceDataStorage.previousMatrixBuffer)==null||i.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.previousMatrixData??this._thinInstanceDataStorage.matrixData,e)):(a===y.ColorKind&&(a=y.ColorInstanceKind),(s=this._userThinInstanceBuffersStorage.vertexBuffers[a])==null||s.dispose(),this._userThinInstanceBuffersStorage.vertexBuffers[a]=new y(this.getEngine(),this._userThinInstanceBuffersStorage.data[a],a,!e,!1,this._userThinInstanceBuffersStorage.strides[a],!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a]))};z.prototype._thinInstanceUpdateBufferSize=function(a,e=1){var l,h,c;a===y.ColorKind&&(a=y.ColorInstanceKind);const t=a==="matrix";if(!t&&(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.strides[a]))return;const i=t?16:this._userThinInstanceBuffersStorage.strides[a],s=t?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[a];let r=t?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[a];const n=(this._thinInstanceDataStorage.instancesCount+e)*i;let o=s;for(;o<n;)o*=2;if(!r||s!=o){if(!r)r=new Float32Array(o);else{const u=new Float32Array(o);u.set(r,0),r=u}t?((l=this._thinInstanceDataStorage.matrixBuffer)==null||l.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",r,!1),this._thinInstanceDataStorage.matrixData=r,this._thinInstanceDataStorage.matrixBufferSize=o,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&((h=this._thinInstanceDataStorage.previousMatrixBuffer)==null||h.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",r,!1))):((c=this._userThinInstanceBuffersStorage.vertexBuffers[a])==null||c.dispose(),this._userThinInstanceBuffersStorage.data[a]=r,this._userThinInstanceBuffersStorage.sizes[a]=o,this._userThinInstanceBuffersStorage.vertexBuffers[a]=new y(this.getEngine(),r,a,!0,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a]))}};z.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})};z.prototype._disposeThinInstanceSpecificData=function(){var a;(a=this._thinInstanceDataStorage)!=null&&a.matrixBuffer&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)};var M;(function(a){a[a.Int=1]="Int",a[a.Float=2]="Float",a[a.Vector2=4]="Vector2",a[a.Vector3=8]="Vector3",a[a.Vector4=16]="Vector4",a[a.Matrix=32]="Matrix",a[a.Geometry=64]="Geometry",a[a.Texture=128]="Texture",a[a.AutoDetect=1024]="AutoDetect",a[a.BasedOnInput=2048]="BasedOnInput",a[a.Undefined=4096]="Undefined",a[a.All=4095]="All"})(M||(M={}));var Na;(function(a){a[a.Compatible=0]="Compatible",a[a.TypeIncompatible=1]="TypeIncompatible",a[a.HierarchyIssue=2]="HierarchyIssue"})(Na||(Na={}));var wu;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(wu||(wu={}));class CT{get direction(){return this._direction}get type(){if(this._type===M.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===M.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return this.connectedPoint!==null||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return this._endpoints.length===0?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){var t;return this.isConnected?(t=this._connectedPoint)!=null&&t._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=M.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new G,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===Na.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==M.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?Na.Compatible:Na.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Na.TypeIncompatible;let s=i,r=t;return this.direction===wu.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Na.HierarchyIssue:Na.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<M.All;)e&t||this.excludedConnectionPointTypes.push(t),t=t<<1}serialize(e=!0){const t={};return t.name=this.name,t.displayName=this.displayName,this.value!==void 0&&this.value!==null&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name),t}dispose(){this.onConnectionObservable.clear()}}class qe{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints){for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const s=i.ownerBlock.getDescendantOfPredicate(e);if(s)return s}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new G,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Yu.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new CT(e,this,wu.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return i=i??new CT(e,this,wu.Output),i.type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some(i=>i.hasEndpoints)&&!this.isDebug)return!1;this.outputs.forEach(i=>i._resetCounters())}this._buildId=e.buildId;for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.notConnectedNonOptionalInputs.push(i);continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&s.build(e)}this._customBuildStep(e),e.verbose&&O.Log(`Building ${this.name} [${this.getClassName()}]`);const t=Zi.Now;this._buildBlock(e),this._buildExecutionTime=Zi.Now-t;for(const i of this._outputs)for(const s of i.endpoints){const r=s.ownerBlock;r&&r.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter(i=>i.name===e);return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter(i=>i.name===e);return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(s=>{const r=this.inputs.find(n=>n.name===s.name);if(r&&(s.displayName&&(r.displayName=s.displayName),s.isExposedOnFrame&&(r.isExposedOnFrame=s.isExposedOnFrame,r.exposedPortPosition=s.exposedPortPosition),s.value!==void 0&&s.value!==null))if(s.valueType==="number")r.value=s.value;else{const n=Si(s.valueType);n&&(r.value=n.FromArray(s.value))}}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.exposedPortPosition)})}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};
`}_dumpCodeForOutputConnections(e){let t="";if(e.indexOf(this)!==-1)return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});
`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,e.indexOf(this._codeVariableName)!==-1){let n=0;do n++,this._codeVariableName=i+n;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=`
// ${this.getClassName()}
`;this.comments&&(s+=`// ${this.comments}
`);const r=this.getClassName();if(r==="GeometryInputBlock"){const o=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${o});
`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");
`;s+=this._dumpPropertiesCode();for(const n of this.inputs){if(!n.isConnected)continue;const l=n.connectedPoint.ownerBlock;t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}for(const n of this.outputs)if(n.hasEndpoints)for(const o of n.endpoints){const l=o.ownerBlock;l&&t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=Si(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}E([I("comment")],qe.prototype,"comments",void 0);class YS extends qe{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",M.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}V("BABYLON.GeometryOutputBlock",YS);var bt;(function(a){a[a.None=0]="None",a[a.Positions=1]="Positions",a[a.Normals=2]="Normals",a[a.Tangents=3]="Tangents",a[a.UV=4]="UV",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6",a[a.Colors=10]="Colors",a[a.VertexID=11]="VertexID",a[a.FaceID=12]="FaceID",a[a.GeometryID=13]="GeometryID",a[a.CollectionID=14]="CollectionID",a[a.LoopID=15]="LoopID",a[a.InstanceID=16]="InstanceID"})(bt||(bt={}));class Kw{constructor(){this._rotationMatrix=new D,this._scalingMatrix=new D,this._positionMatrix=new D,this._scalingRotationMatrix=new D,this._transformMatrix=new D,this._tempVector3=new m,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case bt.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?m.Zero():m.FromArray(this.geometryContext.positions,i*3);case bt.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?m.Zero():m.FromArray(this.geometryContext.normals,i*3);case bt.Colors:return!this.geometryContext||!this.geometryContext.colors?we.Zero():we.FromArray(this.geometryContext.colors,i*4);case bt.Tangents:return!this.geometryContext||!this.geometryContext.tangents?we.Zero():we.FromArray(this.geometryContext.tangents,i*4);case bt.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?Z.Zero():Z.FromArray(this.geometryContext.uvs,i*2);case bt.UV2:return!this.geometryContext||!this.geometryContext.uvs2?Z.Zero():Z.FromArray(this.geometryContext.uvs2,i*2);case bt.UV3:return!this.geometryContext||!this.geometryContext.uvs3?Z.Zero():Z.FromArray(this.geometryContext.uvs3,i*2);case bt.UV4:return!this.geometryContext||!this.geometryContext.uvs4?Z.Zero():Z.FromArray(this.geometryContext.uvs4,i*2);case bt.UV5:return!this.geometryContext||!this.geometryContext.uvs5?Z.Zero():Z.FromArray(this.geometryContext.uvs5,i*2);case bt.UV6:return!this.geometryContext||!this.geometryContext.uvs6?Z.Zero():Z.FromArray(this.geometryContext.uvs6,i*2);case bt.VertexID:return i;case bt.FaceID:return this.executionContext.getExecutionFaceIndex();case bt.LoopID:return this.executionContext.getExecutionLoopIndex();case bt.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case bt.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case bt.CollectionID:return!this.geometryContext||!this.geometryContext.metadata?0:this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case M.Vector2:return new Z(i,i);case M.Vector3:return new m(i,i,i);case M.Vector4:return new we(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(((r=e._connectedPoint)==null?void 0:r.type)===t)return s;switch(t){case M.Vector2:return new Z(s,s);case M.Vector3:return new m(s,s,s);case M.Vector4:return new we(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.
`;for(const t of this.noContextualData)e+=`Contextual input ${bt[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).
`;if(e)throw`Build of NodeGeometry failed:
`+e}_instantiate(e,t,i,s,r){D.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),D.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),D.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let n=0;n<e.positions.length;n+=3)this._tempVector3.fromArray(e.positions,n),m.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,n),e.normals&&(this._tempVector3.fromArray(e.normals,n),m.TransformNormalToRef(this._tempVector3,this._scalingRotationMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,n));r.push(e)}_instantiateWithMatrix(e,t,i){for(let s=0;s<e.positions.length;s+=3)this._tempVector3.fromArray(e.positions,s),m.TransformCoordinatesToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.positions,s),e.normals&&(this._tempVector3.fromArray(e.normals,s),m.TransformNormalToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.normals,s));i.push(e)}_instantiateWithPositionAndMatrix(e,t,i,s){D.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),i.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let r=0;r<e.positions.length;r+=3)this._tempVector3.fromArray(e.positions,r),m.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,r),e.normals&&(this._tempVector3.fromArray(e.normals,r),m.TransformNormalToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,r));s.push(e)}}class Ui extends qe{get type(){if(this._type===M.AutoDetect&&this.value!=null){if(!isNaN(this.value))return this._type=M.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=M.Vector2,this._type;case"Vector3":return this._type=M.Vector3,this._type;case"Vector4":return this._type=M.Vector4,this._type;case"Matrix":return this._type=M.Matrix,this._type}}return this._type}get isContextual(){return this._contextualSource!==bt.None}get contextualValue(){return this._contextualSource}set contextualValue(e){switch(this._contextualSource=e,e){case bt.Positions:case bt.Normals:this._type=M.Vector3;break;case bt.Colors:case bt.Tangents:this._type=M.Vector4;break;case bt.UV:case bt.UV2:case bt.UV3:case bt.UV4:case bt.UV5:case bt.UV6:this._type=M.Vector2;break;case bt.VertexID:case bt.GeometryID:case bt.CollectionID:case bt.FaceID:case bt.LoopID:case bt.InstanceID:this._type=M.Int;break}this.output&&(this.output.type=this._type)}constructor(e,t=M.AutoDetect){super(e),this._type=M.Undefined,this._contextualSource=bt.None,this.min=0,this.max=0,this.groupInInspector="",this.onValueChangedObservable=new G,this._type=t,this._isInput=!0,this.setDefaultValue(),this.registerOutput("output",t)}get value(){return this._storedValue}set value(e){this.type===M.Float&&this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e)),this._storedValue=e,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e}getClassName(){return"GeometryInputBlock"}get output(){return this._outputs[0]}setDefaultValue(){switch(this.contextualValue=bt.None,this.type){case M.Int:case M.Float:this.value=0;break;case M.Vector2:this.value=Z.Zero();break;case M.Vector3:this.value=m.Zero();break;case M.Vector4:this.value=we.Zero();break;case M.Matrix:this.value=D.Identity();break}}_buildBlock(e){super._buildBlock(e),this.isContextual?(this.output._storedValue=null,this.output._storedFunction=t=>t.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${bt[this._contextualSource]};
`;const t=[];let i="";switch(this.type){case M.Float:case M.Int:i=`${this.value}`;break;case M.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case M.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case M.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break}return t.push(`${e}.value = ${i}`),(this.type===M.Float||this.type===M.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(`;
`)}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,this._storedValue!==null&&!this.isContextual&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const t=Si(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}V("BABYLON.GeometryInputBlock",Ui);class Eg extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",M.Float,!0,1),this.registerInput("width",M.Float,!0,0),this.registerInput("height",M.Float,!0,0),this.registerInput("depth",M.Float,!0,0),this.registerInput("subdivisions",M.Int,!0,1),this.registerInput("subdivisionsX",M.Int,!0,0),this.registerInput("subdivisionsY",M.Int,!0,0),this.registerInput("subdivisionsZ",M.Int,!0,0),this.registerOutput("geometry",M.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new Ui("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Ui("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ui("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Ui("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=s=>{t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.depth=this.depth.getConnectedValue(s);const r=this.subdivisions.getConnectedValue(s),n=this.subdivisionsX.getConnectedValue(s),o=this.subdivisionsY.getConnectedValue(s),l=this.subdivisionsZ.getConnectedValue(s);return r&&(t.segments=r),n&&(t.widthSegments=n),o&&(t.heightSegments=o),l&&(t.depthSegments=l),jR(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Eg.prototype,"evaluateContext",void 0);V("BABYLON.BoxBlock",Eg);class Sr{_getGlobalNodeGeometryEditor(){if(typeof NODEGEOMETRYEDITOR<"u")return NODEGEOMETRYEDITOR;if(typeof BABYLON<"u"&&typeof BABYLON.NodeGeometryEditor<"u")return BABYLON}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=Sr._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new G,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return X.Warn("More than one block was found with the name `"+e+"`"),t;return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),typeof this.BJSNODEGEOMETRYEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:Sr.EditorURL;X.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(e==null?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=Zi.Now;this._initializeBlock(this.outputBlock,i);const r=new Kw;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=Sr._BuildIdGenerator++),this._buildExecutionTime=Zi.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new z(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),this._vertexData?(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e):!1}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._initializeBlock(r,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const s of e.blocks){const r=Si(s.customType);if(r){const n=new r;n._deserialize(s),i[s.id]=n,this.attachedBlocks.push(n)}}for(const s of this.attachedBlocks)if(s.isTeleportOut){const r=s,n=r._tempEntryPointUniqueId;if(n){const o=i[n];o&&o.attachToEndpoint(r)}}for(let s=0;s<e.blocks.length;s++){const r=e.blocks[s],n=i[r.id];n&&(n.inputs.length&&r.inputs.some(o=>o.targetConnectionName)&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const n of s)i[n.blockId]&&(n.blockId=i[n.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const n in i)r[n]=i[n].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");
`;for(const r of t)r.isInput&&e.indexOf(r)===-1&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+=`// Connections
`,s+=this.outputBlock._dumpCodeForOutputConnections(e),s+=`// Output nodes
`,s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};
`,s+=`nodeGeometry.build();
`),s}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Eg("Box");e.autoConfigure();const t=new YS("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=_e.Clone(()=>new Sr(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:_e.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const s of i)t.blocks.push(s.serialize());if(!e)for(const s of this.attachedBlocks)i.indexOf(s)===-1&&t.blocks.push(s.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Sr(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=_e.Parse(()=>new Sr(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Sr.CreateDefault("blank")):new Promise((s,r)=>{const n=new yi;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.nodeGeometry);t||(t=_e.Parse(()=>new Sr(e),l,null)),t.parseSerializedObject(l),t.snippetId=e;try{i||t.build(),s(t)}catch(h){r(h)}}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}Sr._BuildIdGenerator=0;Sr.EditorURL=`${X._DefaultCdnUrl}/v${H.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;Sr.SnippetUrl="https://snippet.babylonjs.com";E([I()],Sr.prototype,"name",void 0);E([I("comment")],Sr.prototype,"comment",void 0);class Sg extends qe{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=rt,this.registerInput("geometry",M.Geometry),this.registerOutput("output",M.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(!this.geometry.isConnected)return null;const s=this.geometry.getConnectedValue(i),r=[],n={};for(let l=0;l<s.positions.length;l+=3){const h=s.positions[l],c=s.positions[l+1],u=s.positions[l+2];let d=!1;for(let f=0;f<r.length;f+=3)if(ge.WithinEpsilon(h,r[f],this.epsilon)&&ge.WithinEpsilon(c,r[f+1],this.epsilon)&&ge.WithinEpsilon(u,r[f+2],this.epsilon)){n[l/3]=f/3,d=!0;continue}d||(n[l/3]=r.length/3,r.push(h,c,u))}const o=new le;return o.positions=r,o.indices=s.indices.map(l=>n[l]),o};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};
`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Sg.prototype,"evaluateContext",void 0);E([Le("Epsilon",Ne.Float,"ADVANCED",{notifiers:{rebuild:!0}})],Sg.prototype,"epsilon",void 0);V("BABYLON.GeometryOptimizeBlock",Sg);class $S extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",M.Float,!0,1),this.registerInput("width",M.Float,!0,0),this.registerInput("height",M.Float,!0,0),this.registerOutput("geometry",M.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new Ui("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Ui("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ui("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=s=>(t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),Rm(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$S.prototype,"evaluateContext",void 0);V("BABYLON.PlaneBlock",$S);class KS extends qe{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",M.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}const e=le.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;t<e.indices.length;t+=3){const i=e.indices[t];e.indices[t]=e.indices[t+2],e.indices[t+2]=i}this.geometry._storedFunction=()=>e.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=le.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=le.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}E([Le("Serialize cached data",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],KS.prototype,"serializedCachedData",void 0);V("BABYLON.MeshBlock",KS);class jS extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",M.Float,!0,1),this.registerInput("radiusX",M.Float,!0,0),this.registerInput("radiusY",M.Float,!0,0),this.registerInput("radiusZ",M.Float,!0,0),this.registerInput("subdivisions",M.Int,!0,4),this.registerOutput("geometry",M.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Ui("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.radiusX=this.radiusX.getConnectedValue(s),t.radiusY=this.radiusY.getConnectedValue(s),t.radiusZ=this.radiusZ.getConnectedValue(s),Mm(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jS.prototype,"evaluateContext",void 0);V("BABYLON.IcoSphereBlock",jS);class qS extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",M.Int,!0,32),this.registerInput("diameter",M.Float,!0,1),this.registerInput("diameterX",M.Float,!0,0),this.registerInput("diameterY",M.Float,!0,0),this.registerInput("diameterZ",M.Float,!0,0),this.registerInput("arc",M.Float,!0,1),this.registerInput("slice",M.Float,!0,1),this.registerOutput("geometry",M.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ui("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.segments=this.segments.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterX=this.diameterX.getConnectedValue(s),t.diameterY=this.diameterY.getConnectedValue(s),t.diameterZ=this.diameterZ.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),t.slice=this.slice.getConnectedValue(s),$m(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qS.prototype,"evaluateContext",void 0);V("BABYLON.SphereBlock",qS);class QS extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",M.Float,!0,1),this.registerInput("height",M.Float,!0,1),this.registerInput("subdivisions",M.Int,!0,1),this.registerInput("subdivisionsX",M.Int,!0,0),this.registerInput("subdivisionsY",M.Int,!0,0),this.registerOutput("geometry",M.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new Ui("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Ui("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.subdivisionsX=this.subdivisionsX.getConnectedValue(s),t.subdivisionsY=this.subdivisionsY.getConnectedValue(s),ia(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],QS.prototype,"evaluateContext",void 0);V("BABYLON.GridBlock",QS);class ZS extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",M.Float,!0,1),this.registerInput("thickness",M.Float,!0,.5),this.registerInput("tessellation",M.Int,!0,16),this.registerOutput("geometry",M.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ui("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.thickness=this.thickness.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),Gm(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ZS.prototype,"evaluateContext",void 0);V("BABYLON.TorusBlock",ZS);class JS extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",M.Float,!0,25),this.registerInput("diameter",M.Float,!0,1),this.registerInput("diameterTop",M.Float,!0,-1),this.registerInput("diameterBottom",M.Float,!0,-1),this.registerInput("subdivisions",M.Int,!0,1),this.registerInput("tessellation",M.Int,!0,24),this.registerInput("arc",M.Float,!0,1),this.registerOutput("geometry",M.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Ui("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Ui("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterTop=this.diameterTop.getConnectedValue(s),t.diameterBottom=this.diameterBottom.getConnectedValue(s),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),Wm(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],JS.prototype,"evaluateContext",void 0);V("BABYLON.CylinderBlock",JS);class eC extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",M.Float,!0,1),this.registerInput("radius",M.Float,!0,.25),this.registerInput("tessellation",M.Int,!0,16),this.registerInput("subdivisions",M.Int,!0,2),this.registerOutput("geometry",M.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new Ui("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Ui("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),Km(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],eC.prototype,"evaluateContext",void 0);V("BABYLON.CapsuleBlock",eC);class tC extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",M.Float,!0,.5),this.registerInput("tessellation",M.Int,!0,64),this.registerInput("arc",M.Float,!0,1),this.registerOutput("geometry",M.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Ui("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),jm(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tC.prototype,"evaluateContext",void 0);V("BABYLON.DiscBlock",tC);class jw extends qe{constructor(e){super(e),this.registerOutput("geometry",M.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}V("BABYLON.NullBlock",jw);class iC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("positions",M.Vector3),this.registerOutput("output",M.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}const s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const r=this.positions.getConnectedValue(i);r&&r.toArray(this._vertexData.positions,this._currentIndex*3)}return i.restoreGeometryContext(),i.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iC.prototype,"evaluateContext",void 0);V("BABYLON.SetPositionsBlock",iC);class sC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("normals",M.Vector3),this.registerOutput("output",M.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetNormalsBlock"}get geometry(){return this._inputs[0]}get normals(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);const s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const r=this.normals.getConnectedValue(i);r&&r.toArray(this._vertexData.normals,this._currentIndex*3)}return i.restoreGeometryContext(),i.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],sC.prototype,"evaluateContext",void 0);V("BABYLON.SetNormalsBlock",sC);class Cg extends qe{constructor(e){super(e),this.evaluateContext=!0,this.textureCoordinateIndex=0,this.registerInput("geometry",M.Geometry),this.registerInput("uvs",M.Vector2),this.registerOutput("output",M.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetUVsBlock"}get geometry(){return this._inputs[0]}get uvs(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}const s=[],r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<r;this._currentIndex++){const n=this.uvs.getConnectedValue(i);n&&n.toArray(s,this._currentIndex*2)}switch(this.textureCoordinateIndex){case 0:this._vertexData.uvs=s;break;case 1:this._vertexData.uvs2=s;break;case 2:this._vertexData.uvs3=s;break;case 3:this._vertexData.uvs4=s;break;case 4:this._vertexData.uvs5=s;break;case 5:this._vertexData.uvs6=s;break}return i.restoreGeometryContext(),i.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.textureCoordinateIndex};
`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.textureCoordinateIndex=this.textureCoordinateIndex,e}_deserialize(e){super._deserialize(e),this.textureCoordinateIndex=e.textureCoordinateIndex,e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Cg.prototype,"evaluateContext",void 0);E([Le("Texture coordinates index",Ne.List,"ADVANCED",{notifiers:{update:!0},options:[{label:"UV1",value:0},{label:"UV2",value:1},{label:"UV3",value:2},{label:"UV4",value:3},{label:"UV5",value:4},{label:"UV6",value:5}]})],Cg.prototype,"textureCoordinateIndex",void 0);V("BABYLON.SetUVsBlock",Cg);class rC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("colors",M.AutoDetect),this.registerOutput("output",M.Geometry),this._inputs[1].excludedConnectionPointTypes.push(M.Int),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Vector2),this._inputs[1].excludedConnectionPointTypes.push(M.Texture),this._inputs[1].excludedConnectionPointTypes.push(M.Texture)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetColorsBlock"}get geometry(){return this._inputs[0]}get colors(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{var r;if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);const s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++)if(((r=this.colors.connectedPoint)==null?void 0:r.type)===M.Vector3){const n=this.colors.getConnectedValue(i);n&&(n.toArray(this._vertexData.colors,this._currentIndex*4),this._vertexData.colors[this._currentIndex*4+3]=1,this._vertexData.hasVertexAlpha=!1)}else{const n=this.colors.getConnectedValue(i);n&&(n.toArray(this._vertexData.colors,this._currentIndex*4),this._vertexData.hasVertexAlpha=!0)}return i.restoreGeometryContext(),i.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rC.prototype,"evaluateContext",void 0);V("BABYLON.SetColorsBlock",rC);class nC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("tangents",M.Vector4),this.registerOutput("output",M.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetTangentsBlock"}get geometry(){return this._inputs[0]}get tangents(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(i),this._vertexData&&(this._vertexData=this._vertexData.clone()),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){i.restoreGeometryContext(),i.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);const s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const r=this.tangents.getConnectedValue(i);r&&r.toArray(this._vertexData.tangents,this._currentIndex*4)}return i.restoreGeometryContext(),i.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],nC.prototype,"evaluateContext",void 0);V("BABYLON.SetTangentsBlock",nC);var $s;(function(a){a[a.Add=0]="Add",a[a.Subtract=1]="Subtract",a[a.Multiply=2]="Multiply",a[a.Divide=3]="Divide",a[a.Max=4]="Max",a[a.Min=5]="Min"})($s||($s={}));class aC extends qe{constructor(e){super(e),this.operation=$s.Add,this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Geometry),this._inputs[1].excludedConnectionPointTypes.push(M.Texture),this._inputs[1].acceptedConnectionPointTypes.push(M.Float),this._linkConnectionTypes(0,1)}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const s=t.type===M.Float||t.type===M.Int;switch(this.operation){case $s.Add:{s?e=r=>t.getConnectedValue(r)+i.getConnectedValue(r):e=r=>t.getConnectedValue(r).add(r.adapt(i,t.type));break}case $s.Subtract:{s?e=r=>t.getConnectedValue(r)-i.getConnectedValue(r):e=r=>t.getConnectedValue(r).subtract(r.adapt(i,t.type));break}case $s.Multiply:{s?e=r=>t.getConnectedValue(r)*i.getConnectedValue(r):e=r=>t.getConnectedValue(r).multiply(r.adapt(i,t.type));break}case $s.Divide:{s?e=r=>t.getConnectedValue(r)/i.getConnectedValue(r):e=r=>t.getConnectedValue(r).divide(r.adapt(i,t.type));break}case $s.Min:{if(s)e=r=>Math.min(t.getConnectedValue(r),i.getConnectedValue(r));else switch(t.type){case M.Vector2:{e=r=>Z.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case M.Vector3:{e=r=>m.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case M.Vector4:{e=r=>we.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}case $s.Max:if(s)e=r=>Math.max(t.getConnectedValue(r),i.getConnectedValue(r));else{switch(t.type){case M.Vector2:{e=r=>Z.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case M.Vector3:{e=r=>m.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case M.Vector4:{e=r=>we.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}}this.output._storedFunction=r=>t.type===M.Int?e(r)|0:e(r)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${$s[this.operation]};
`}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}E([Le("Operation",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:$s.Add},{label:"Subtract",value:$s.Subtract},{label:"Multiply",value:$s.Multiply},{label:"Divide",value:$s.Divide},{label:"Max",value:$s.Max},{label:"Min",value:$s.Min}]})],aC.prototype,"operation",void 0);V("BABYLON.MathBlock",aC);class qw extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("fromMin",M.Float,!0,0),this.registerInput("fromMax",M.Float,!0,1),this.registerInput("toMin",M.Float,!0,0),this.registerInput("toMax",M.Float,!0,1),this.registerOutput("output",M.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(M.Vector2),this._inputs[0].excludedConnectionPointTypes.push(M.Vector3),this._inputs[0].excludedConnectionPointTypes.push(M.Vector4),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e),o=(t-i)/(s-i)*(n-r)+r;return this.output.type===M.Int?Math.floor(o):o}}}V("BABYLON.MapRangeBlock",qw);var os;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(os||(os={}));class oC extends qe{constructor(e){super(e),this.test=os.Equal,this.registerInput("left",M.Float),this.registerInput("right",M.Float,!0,0),this.registerInput("ifTrue",M.AutoDetect,!0,1),this.registerInput("ifFalse",M.AutoDetect,!0,0),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=M.Float,this._inputs[0].acceptedConnectionPointTypes.push(M.Int),this._inputs[1].acceptedConnectionPointTypes.push(M.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);let r=!1;switch(this.test){case os.Equal:r=ge.WithinEpsilon(i,s,rt);break;case os.NotEqual:r=i!==s;break;case os.LessThan:r=i<s;break;case os.GreaterThan:r=i>s;break;case os.LessOrEqual:r=i<=s;break;case os.GreaterOrEqual:r=i>=s;break;case os.Xor:r=!!i&&!s||!i&&!!s;break;case os.Or:r=!!i||!!s;break;case os.And:r=!!i&&!!s;break}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${os[this.test]};
`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}E([Le("Test",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:os.Equal},{label:"NotEqual",value:os.NotEqual},{label:"LessThan",value:os.LessThan},{label:"GreaterThan",value:os.GreaterThan},{label:"LessOrEqual",value:os.LessOrEqual},{label:"GreaterOrEqual",value:os.GreaterOrEqual},{label:"Xor",value:os.Xor},{label:"Or",value:os.Or},{label:"And",value:os.And}]})],oC.prototype,"test",void 0);V("BABYLON.ConditionBlock",oC);var _n;(function(a){a[a.None=0]="None",a[a.LoopID=1]="LoopID",a[a.InstanceID=2]="InstanceID"})(_n||(_n={}));class lC extends qe{constructor(e){super(e),this._currentLockId=-1,this.lockMode=_n.None,this.registerInput("min",M.AutoDetect),this.registerInput("max",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Geometry),this._inputs[1].excludedConnectionPointTypes.push(M.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new Ui("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Ui("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case M.Int:case M.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,s=this.max.getConnectedValue(t)||0;return i+Math.random()*(s-i)};break}case M.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||Z.Zero(),s=this.max.getConnectedValue(t)||Z.Zero();return new Z(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y))};break}case M.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||m.Zero(),s=this.max.getConnectedValue(t)||m.Zero();return new m(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z))};break}case M.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||we.Zero(),s=this.max.getConnectedValue(t)||we.Zero();return new we(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z),i.w+Math.random()*(s.w-i.w))};break}}this.lockMode===_n.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case _n.InstanceID:i=t.getContextualValue(bt.InstanceID,!0)||0;break;case _n.LoopID:i=t.getContextualValue(bt.LoopID,!0)||0;break}return(this._currentLockId!==i||this.lockMode===_n.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${_n[this.lockMode]};
`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}E([Le("LockMode",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:_n.None},{label:"LoopID",value:_n.LoopID},{label:"InstanceID",value:_n.InstanceID}]})],lC.prototype,"lockMode",void 0);V("BABYLON.RandomBlock",lC);class Qw extends qe{constructor(e){super(e),this.registerInput("offset",M.Vector3,!0,m.Zero()),this.registerInput("scale",M.Float,!0,1),this.registerInput("octaves",M.Float,!0,2,0,16),this.registerInput("roughness",M.Float,!0,.5,0,1),this.registerOutput("output",M.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return t!==0?-e:e}_noiseGrad(e,t,i,s){const r=e&15,n=r<8?t:i,o=r===12||r==14?t:s,l=r<4?i:o;return this._negateIf(n,r&n)+this._negateIf(l,r&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<<t|e>>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928559+12+13,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,l,h,c,u){const d=1-h,f=1-c;return(1-u)*(f*(e*d+t*h)+c*(i*d+s*h))+u*(f*(r*d+n*h)+c*(o*d+l*h))}_perlinNoise(e){const t=(e.x|0)-(e.x<0?1:0),i=(e.y|0)-(e.y<0?1:0),s=(e.z|0)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,l=this._fade(r),h=this._fade(n),c=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),l,h,c)}_perlinSigned(e){return this._perlinNoise(e)*.982}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new m(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,l=1,h=0,c=0;e=ge.Clamp(e,0,15);const u=e|0;for(let p=0;p<=u;p++){const g=this._perlin(n.scale(o));c+=g*l,h+=l,l*=ge.Clamp(t,0,1),o*=2}const d=e-Math.floor(e);if(d==0)return c/h;const f=this._perlin(n.scale(o));let _=c+f*l;return c/=h,_/=h+l,(1-d)*c+d*_}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(bt.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}V("BABYLON.NoiseBlock",Qw);class hC extends qe{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",M.Geometry),this.registerInput("geometry1",M.Geometry,!0),this.registerInput("geometry2",M.Geometry,!0),this.registerInput("geometry3",M.Geometry,!0),this.registerInput("geometry4",M.Geometry,!0),this.registerOutput("output",M.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{let s=this.geometry0.getConnectedValue(i);const r=[];if(s)s=s.clone();else return null;if(this.geometry1.isConnected){const n=this.geometry1.getConnectedValue(i);n&&r.push(n)}if(this.geometry2.isConnected){const n=this.geometry2.getConnectedValue(i);n&&r.push(n)}if(this.geometry3.isConnected){const n=this.geometry3.getConnectedValue(i);n&&r.push(n)}if(this.geometry4.isConnected){const n=this.geometry4.getConnectedValue(i);n&&r.push(n)}return r.length&&s&&(s=s.merge(r,!0,!1,!0,!0)),s};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],hC.prototype,"evaluateContext",void 0);V("BABYLON.MergeGeometryBlock",hC);class cC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",M.Geometry,!0),this.registerInput("geometry1",M.Geometry,!0),this.registerInput("geometry2",M.Geometry,!0),this.registerInput("geometry3",M.Geometry,!0),this.registerInput("geometry4",M.Geometry,!0),this.registerInput("geometry5",M.Geometry,!0),this.registerInput("geometry6",M.Geometry,!0),this.registerInput("geometry7",M.Geometry,!0),this.registerInput("geometry8",M.Geometry,!0),this.registerInput("geometry9",M.Geometry,!0),this.registerOutput("output",M.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=i=>{const s=[];return this._storeGeometry(this.geometry0,i,0,s),this._storeGeometry(this.geometry1,i,1,s),this._storeGeometry(this.geometry2,i,2,s),this._storeGeometry(this.geometry3,i,3,s),this._storeGeometry(this.geometry4,i,4,s),this._storeGeometry(this.geometry5,i,5,s),this._storeGeometry(this.geometry6,i,6,s),this._storeGeometry(this.geometry7,i,7,s),this._storeGeometry(this.geometry8,i,8,s),this._storeGeometry(this.geometry9,i,9,s),s.length?s[Math.round(Math.random()*(s.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],cC.prototype,"evaluateContext",void 0);V("BABYLON.GeometryCollectionBlock",cC);class Zw extends qe{constructor(e){super(e),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=s=>i.getConnectedValue(s)}}V("BABYLON.GeometryElbowBlock",Zw);class Jw extends qe{constructor(e){super(e),this.registerInput("geometry",M.Geometry),this.registerOutput("output",M.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),le.ComputeNormals(t.positions,t.indices,t.normals),t}}}V("BABYLON.ComputeNormalsBlock",Jw);class e1 extends qe{constructor(e){super(e),this.registerInput("xyzw ",M.Vector4,!0),this.registerInput("xyz ",M.Vector3,!0),this.registerInput("xy ",M.Vector2,!0),this.registerInput("zw ",M.Vector2,!0),this.registerInput("x ",M.Float,!0),this.registerInput("y ",M.Float,!0),this.registerInput("z ",M.Float,!0),this.registerInput("w ",M.Float,!0),this.registerOutput("xyzw",M.Vector4),this.registerOutput("xyz",M.Vector3),this.registerOutput("xy",M.Vector2),this.registerOutput("zw",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.Float),this.registerOutput("z",M.Float),this.registerOutput("w",M.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return e==="xyzw "?"xyzwIn":e==="xyz "?"xyzIn":e==="xy "?"xyIn":e==="zw "?"zwIn":e==="x "?"xIn":e==="y "?"yIn":e==="z "?"zIn":e==="w "?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this.xyzwOut,u=this.xyzOut,d=this.xyOut,f=this.zwOut,_=this.xOut,p=this.yOut,g=this.zOut,x=this.wOut,T=S=>{if(h.isConnected)return h.getConnectedValue(S);let C=0,v=0,b=0,A=0;if(t.isConnected&&(C=t.getConnectedValue(S)),i.isConnected&&(v=i.getConnectedValue(S)),s.isConnected&&(b=s.getConnectedValue(S)),r.isConnected&&(A=r.getConnectedValue(S)),n.isConnected){const P=n.getConnectedValue(S);P&&(C=P.x,v=P.y)}if(o.isConnected){const P=o.getConnectedValue(S);P&&(b=P.x,A=P.y)}if(l.isConnected){const P=l.getConnectedValue(S);P&&(C=P.x,v=P.y,b=P.z)}return new we(C,v,b,A)};c._storedFunction=S=>T(S),u._storedFunction=S=>{const C=T(S);return new m(C.x,C.y,C.z)},d._storedFunction=S=>{const C=T(S);return new Z(C.x,C.y)},f._storedFunction=S=>{const C=T(S);return new Z(C.z,C.w)},_._storedFunction=S=>T(S).x,p._storedFunction=S=>T(S).y,g._storedFunction=S=>T(S).z,x._storedFunction=S=>T(S).w}}V("BABYLON.VectorConverterBlock",e1);class t1 extends qe{constructor(e){super(e),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=t=>this.input.getConnectedValue(t).normalize()}}V("BABYLON.NormalizeVectorBlock",t1);class uC extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("id",M.Int,!0,0),this.registerOutput("output",M.Geometry),this.id.acceptedConnectionPointTypes.push(M.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const s=this.geometry.getConnectedValue(i);if(!s||!s.indices||!s.positions)return s;const r=new kd;return r.materialIndex=this.id.getConnectedValue(i)|0,r.indexStart=0,r.indexCount=s.indices.length,r.verticesStart=0,r.verticesCount=s.positions.length/3,s.materialInfos=[r],s};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],uC.prototype,"evaluateContext",void 0);V("BABYLON.SetMaterialIDBlock",uC);var _t;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Round=4]="Round",a[a.Floor=5]="Floor",a[a.Ceiling=6]="Ceiling",a[a.Sqrt=7]="Sqrt",a[a.Log=8]="Log",a[a.Tan=9]="Tan",a[a.ArcTan=10]="ArcTan",a[a.ArcCos=11]="ArcCos",a[a.ArcSin=12]="ArcSin",a[a.Sign=13]="Sign",a[a.Negate=14]="Negate",a[a.OneMinus=15]="OneMinus",a[a.Reciprocal=16]="Reciprocal",a[a.ToDegrees=17]="ToDegrees",a[a.ToRadians=18]="ToRadians",a[a.Fract=19]="Fract",a[a.Exp2=20]="Exp2"})(_t||(_t={}));class dC extends qe{constructor(e){super(e),this.operation=_t.Cos,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case _t.Cos:{t=i=>Math.cos(i);break}case _t.Sin:{t=i=>Math.sin(i);break}case _t.Abs:{t=i=>Math.abs(i);break}case _t.Exp:{t=i=>Math.exp(i);break}case _t.Exp2:{t=i=>Math.pow(2,i);break}case _t.Round:{t=i=>Math.round(i);break}case _t.Floor:{t=i=>Math.floor(i);break}case _t.Ceiling:{t=i=>Math.ceil(i);break}case _t.Sqrt:{t=i=>Math.sqrt(i);break}case _t.Log:{t=i=>Math.log(i);break}case _t.Tan:{t=i=>Math.tan(i);break}case _t.ArcTan:{t=i=>Math.atan(i);break}case _t.ArcCos:{t=i=>Math.acos(i);break}case _t.ArcSin:{t=i=>Math.asin(i);break}case _t.Sign:{t=i=>Math.sign(i);break}case _t.Negate:{t=i=>-i;break}case _t.OneMinus:{t=i=>1-i;break}case _t.Reciprocal:{t=i=>1/i;break}case _t.ToRadians:{t=i=>i*Math.PI/180;break}case _t.ToDegrees:{t=i=>i*180/Math.PI;break}case _t.Fract:{t=i=>i>=0?i-Math.floor(i):i-Math.ceil(i);break}}if(!t){this.output._storedFunction=null,this.output._storedValue=null;return}switch(this.input.type){case M.Int:case M.Float:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return t(s)};break}case M.Vector2:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Z(t(s.x),t(s.y))};break}case M.Vector3:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new m(t(s.x),t(s.y),t(s.z))};break}case M.Vector4:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new we(t(s.x),t(s.y),t(s.z),t(s.w))};break}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${_t[this.operation]};
`}}E([Le("Operation",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:_t.Cos},{label:"Sin",value:_t.Sin},{label:"Abs",value:_t.Abs},{label:"Exp",value:_t.Exp},{label:"Exp2",value:_t.Exp2},{label:"Round",value:_t.Round},{label:"Floor",value:_t.Floor},{label:"Ceiling",value:_t.Ceiling},{label:"Sqrt",value:_t.Sqrt},{label:"Log",value:_t.Log},{label:"Tan",value:_t.Tan},{label:"ArcTan",value:_t.ArcTan},{label:"ArcCos",value:_t.ArcCos},{label:"ArcSin",value:_t.ArcSin},{label:"Sign",value:_t.Sign},{label:"Negate",value:_t.Negate},{label:"OneMinus",value:_t.OneMinus},{label:"Reciprocal",value:_t.Reciprocal},{label:"ToDegrees",value:_t.ToDegrees},{label:"ToRadians",value:_t.ToRadians},{label:"Fract",value:_t.Fract}]})],dC.prototype,"operation",void 0);V("BABYLON.GeometryTrigonometryBlock",dC);class fC extends qe{constructor(e){super(e),this._rotationMatrix=new D,this._scalingMatrix=new D,this._translationMatrix=new D,this._scalingRotationMatrix=new D,this._transformMatrix=new D,this.evaluateContext=!0,this.registerInput("value",M.AutoDetect),this.registerInput("matrix",M.Matrix,!0),this.registerInput("translation",M.Vector3,!0,m.Zero()),this.registerInput("rotation",M.Vector3,!0,m.Zero()),this.registerInput("scaling",M.Vector3,!0,m.One()),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const t=i=>{const s=this.value.getConnectedValue(i);if(!s)return null;let r;if(this.matrix.isConnected)r=this.matrix.getConnectedValue(i);else{const n=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);D.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),D.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),D.TranslationToRef(l.x,l.y,l.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),r=this._transformMatrix}switch(this.value.type){case M.Geometry:{const n=s.clone();return n.transform(r),n}case M.Vector2:return Z.Transform(s,r);case M.Vector3:return m.TransformCoordinates(s,r);case M.Vector4:return we.TransformCoordinates(s,r)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],fC.prototype,"evaluateContext",void 0);V("BABYLON.GeometryTransformBlock",fC);class i1 extends qe{constructor(e){super(e),this.registerInput("angle",M.Float,!1,0),this.registerOutput("matrix",M.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ui("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>D.RotationX(this.angle.getConnectedValue(t))}}V("BABYLON.RotationXBlock",i1);class s1 extends qe{constructor(e){super(e),this.registerInput("angle",M.Float,!1,0),this.registerOutput("matrix",M.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ui("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>D.RotationY(this.angle.getConnectedValue(t))}}V("BABYLON.RotationYBlock",s1);class r1 extends qe{constructor(e){super(e),this.registerInput("angle",M.Float,!1,0),this.registerOutput("matrix",M.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Ui("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>D.RotationZ(this.angle.getConnectedValue(t))}}V("BABYLON.RotationZBlock",r1);class n1 extends qe{constructor(e){super(e),this.registerInput("scale",M.Vector3,!1,m.One()),this.registerOutput("matrix",M.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Ui("Scale");e.value=new m(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return D.Scaling(i.x,i.y,i.z)}}}V("BABYLON.ScalingBlock",n1);class a1 extends qe{constructor(e){super(e),this.registerInput("source",M.Vector3,!0,m.Up()),this.registerInput("target",M.Vector3,!0,m.Left()),this.registerOutput("matrix",M.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.source.getConnectedValue(t).clone(),s=this.target.getConnectedValue(t).clone(),r=new D;return i.normalize(),s.normalize(),D.RotationAlignToRef(i,s,r,!0),r}}}V("BABYLON.AlignBlock",a1);class o1 extends qe{constructor(e){super(e),this.registerInput("translation",M.Vector3,!1,m.Zero()),this.registerOutput("matrix",M.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Ui("Translation");e.value=new m(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return D.Translation(i.x,i.y,i.z)}}}V("BABYLON.TranslationBlock",o1);class vg extends qe{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",M.Geometry),this.registerInput("instance",M.Geometry,!0),this.registerInput("density",M.Float,!0,1,0,1),this.registerInput("matrix",M.Matrix,!0),this.registerInput("rotation",M.Vector3,!0,m.Zero()),this.registerInput("scaling",M.Vector3,!0,m.One()),this.scaling.acceptedConnectionPointTypes.push(M.Float),this.registerOutput("output",M.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let s=this._vertexData.positions.length/3;const r=[],n=new m,o=[];let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const h=l[this._currentIndex*3],c=l[this._currentIndex*3+1],u=l[this._currentIndex*3+2];let d=!1;for(let f=0;f<o.length;f+=3)if(Math.abs(o[f]-h)<rt&&Math.abs(o[f+1]-c)<rt&&Math.abs(o[f+2]-u)<rt){d=!0;break}d||(this._indexTranslation[o.length/3]=this._currentIndex,o.push(h,c,u))}l=o,s=l.length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const h=this.instance.getConnectedValue(i);if(!h||!h.positions||h.positions.length===0)continue;const c=this.density.getConnectedValue(i);if(c<1&&Math.random()>c)continue;n.fromArray(l,this._currentIndex*3);const u=h.clone();if(this.matrix.isConnected){const d=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(u,n,d,r)}else{const d=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly),f=this.rotation.getConnectedValue(i)||m.ZeroReadOnly;i._instantiate(u,n,f,d,r)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),r.length)if(r.length===1)this._vertexData=r[0];else{const h=r.splice(0,1)[0];this._vertexData=h.merge(r,!0,!1,!0,!0)}else return null;return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};
`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vg.prototype,"evaluateContext",void 0);E([Le("Remove duplicated positions",Ne.Boolean,"ADVANCED",{notifiers:{update:!0}})],vg.prototype,"removeDuplicatedPositions",void 0);V("BABYLON.InstantiateOnVerticesBlock",vg);class _C extends qe{constructor(e){super(e),this._currentPosition=new m,this._currentUV=new Z,this._vertex0=new m,this._vertex1=new m,this._vertex2=new m,this._tempVector0=new m,this._tempVector1=new m,this._uv0=new Z,this._uv1=new Z,this._uv2=new Z,this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("instance",M.Geometry,!0),this.registerInput("count",M.Int,!0,256),this.registerInput("matrix",M.Matrix,!0),this.registerInput("rotation",M.Vector3,!0,m.Zero()),this.registerInput("scaling",M.Vector3,!0,m.One()),this.scaling.acceptedConnectionPointTypes.push(M.Float),this.registerOutput("output",M.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),m.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let s=null;const r=this.count.getConnectedValue(i),n=this._vertexData.indices.length/3,o=r/n;let l=0;const h=[];let c=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex<n;this._currentFaceIndex++){l+=o;const u=(l|0)-c;if(u<1)continue;const d=this._vertexData.indices[this._currentFaceIndex*3],f=this._vertexData.indices[this._currentFaceIndex*3+1],_=this._vertexData.indices[this._currentFaceIndex*3+2];this._vertex0.fromArray(this._vertexData.positions,d*3),this._vertex1.fromArray(this._vertexData.positions,f*3),this._vertex2.fromArray(this._vertexData.positions,_*3),this._vertexData.uvs&&(this._uv0.fromArray(this._vertexData.uvs,d*2),this._uv1.fromArray(this._vertexData.uvs,f*2),this._uv2.fromArray(this._vertexData.uvs,_*2));for(let p=0;p<u&&!(c>=r);p++){let g=Math.random(),x=Math.random();if(g>x){const b=g;g=x,x=b}const T=g,S=x-g,C=1-T-S;if(this._currentPosition.set(T*this._vertex0.x+S*this._vertex1.x+C*this._vertex2.x,T*this._vertex0.y+S*this._vertex1.y+C*this._vertex2.y,T*this._vertex0.z+S*this._vertex1.z+C*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(T*this._uv0.x+S*this._uv1.x+C*this._uv2.x,T*this._uv0.y+S*this._uv1.y+C*this._uv2.y),s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0){l-=o;continue}const v=s.clone();if(this.matrix.isConnected){const b=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(v,this._currentPosition,b,h)}else{const b=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly),A=this.rotation.getConnectedValue(i)||m.ZeroReadOnly;i._instantiate(v,this._currentPosition,A,b,h)}c++,this._currentLoopIndex++}}if(h.length)if(h.length===1)this._vertexData=h[0];else{const u=h.splice(0,1)[0];this._vertexData=u.merge(h,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],_C.prototype,"evaluateContext",void 0);V("BABYLON.InstantiateOnFacesBlock",_C);class pC extends qe{constructor(e){super(e),this._currentPosition=new m,this._vertex0=new m,this._vertex1=new m,this._vertex2=new m,this.evaluateContext=!0,this.registerInput("geometry",M.Geometry),this.registerInput("instance",M.Geometry,!0),this.registerInput("count",M.Int,!0,256),this.registerInput("matrix",M.Matrix,!0),this.registerInput("rotation",M.Vector3,!0,m.Zero()),this.registerInput("scaling",M.Vector3,!0,m.One()),this.scaling.acceptedConnectionPointTypes.push(M.Float),this.registerOutput("output",M.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{if(i.pushExecutionContext(this),i.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(i),i.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){i.restoreExecutionContext(),i.restoreInstancingContext(),i.restoreGeometryContext(),this.output._storedValue=null;return}let s=null;const r=this.count.getConnectedValue(i),n=[],o=Au(this._vertexData.positions,0,this._vertexData.positions.length/3),l=o.minimum,h=o.maximum,c=new m(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let d=0;d<r;d++){this._currentPosition.set(Math.random()*(h.x-l.x)+l.x,Math.random()*(h.y-l.y)+l.y,Math.random()*(h.z-l.z)+l.z);const f=new tt(this._currentPosition,c);let _=0;for(let g=0;g<u;g++){this._vertex0.fromArray(this._vertexData.positions,this._vertexData.indices[g*3]*3),this._vertex1.fromArray(this._vertexData.positions,this._vertexData.indices[g*3+1]*3),this._vertex2.fromArray(this._vertexData.positions,this._vertexData.indices[g*3+2]*3);const x=f.intersectsTriangle(this._vertex0,this._vertex1,this._vertex2);x&&x.distance>0&&_++}if(_%2===0){d--;continue}if(s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0)continue;const p=s.clone();if(this.matrix.isConnected){const g=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(p,this._currentPosition,g,n)}else{const g=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly),x=this.rotation.getConnectedValue(i)||m.ZeroReadOnly;i._instantiate(p,this._currentPosition,x,g,n)}this._currentLoopIndex++}if(n.length)if(n.length===1)this._vertexData=n[0];else{const d=n.splice(0,1)[0];this._vertexData=d.merge(n,!0,!1,!0,!0)}return i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],pC.prototype,"evaluateContext",void 0);V("BABYLON.InstantiateOnVolumeBlock",pC);class a_ extends qe{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",M.Geometry,!0),this.registerInput("count",M.Int,!0,1),this.registerOutput("output",M.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],a_.prototype,"evaluateContext",void 0);class l1 extends a_{constructor(e){super(e),this.registerInput("matrix",M.Matrix,!0),this.registerInput("position",M.Vector3,!0,m.Zero()),this.registerInput("rotation",M.Vector3,!0,m.Zero()),this.registerInput("scaling",M.Vector3,!0,m.One()),this.scaling.acceptedConnectionPointTypes.push(M.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=i=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[];for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const n=this.instance.getConnectedValue(i);if(!n||!n.positions||n.positions.length===0)continue;const o=n.clone();if(this.matrix.isConnected){const l=this.matrix.getConnectedValue(i);i._instantiateWithMatrix(o,l,r)}else{const l=this.position.getConnectedValue(i)||m.ZeroReadOnly,h=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly),c=this.rotation.getConnectedValue(i)||m.ZeroReadOnly;i._instantiate(o,l,c,h,r)}}if(r.length)if(r.length===1)this._vertexData=r[0];else{const n=r.splice(0,1)[0];this._vertexData=n.merge(r,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}}V("BABYLON.InstantiateBlock",l1);class h1 extends a_{constructor(e){super(e),this.registerInput("direction",M.Vector3,!0,new m(1,0,0)),this.registerInput("rotation",M.Vector3,!0,new m(0,0,0)),this.registerInput("scaling",M.Vector3,!0,new m(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(M.Float)}getClassName(){return"InstantiateLinearBlock"}get direction(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}_buildBlock(e){const t=i=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=D.Identity(),o=m.Zero(),l=m.Zero(),h=m.Zero();for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const c=this.instance.getConnectedValue(i);if(!c||!c.positions||c.positions.length===0)continue;const u=c.clone(),d=this.direction.getConnectedValue(i),f=this.rotation.getConnectedValue(i),_=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly);o.copyFrom(d.clone().scale(this._currentIndex)),l.copyFrom(f.clone().scale(this._currentIndex)),h.copyFrom(_.clone().scale(this._currentIndex)),h.addInPlaceFromFloats(1,1,1),D.ComposeToRef(h,Q.FromEulerAngles(l.x,l.y,l.z),o,n),i._instantiateWithMatrix(u,n,r)}if(r.length)if(r.length===1)this._vertexData=r[0];else{const c=r.splice(0,1)[0];this._vertexData=c.merge(r,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}}V("BABYLON.InstantiateLinearBlock",h1);class c1 extends a_{constructor(e){super(e),this.registerInput("radius",M.Int,!0,0,0),this.registerInput("angleStart",M.Float,!0,0),this.registerInput("angleEnd",M.Float,!0,Math.PI*2),this.registerInput("transform",M.Vector3,!0,new m(0,0,0)),this.registerInput("rotation",M.Vector3,!0,new m(0,0,0)),this.registerInput("scaling",M.Vector3,!0,new m(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(M.Float)}getClassName(){return"InstantiateRadialBlock"}get radius(){return this._inputs[2]}get angleStart(){return this._inputs[3]}get angleEnd(){return this._inputs[4]}get transform(){return this._inputs[5]}get rotation(){return this._inputs[6]}get scaling(){return this._inputs[7]}_buildBlock(e){const t=i=>{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=D.Identity(),o=D.Identity(),l=D.Identity(),h=m.Zero(),c=m.Zero(),u=m.Zero();for(this._currentIndex=0;this._currentIndex<s;this._currentIndex++){const d=this.instance.getConnectedValue(i);if(!d||!d.positions||d.positions.length===0)continue;const f=d.clone(),_=this.radius.getConnectedValue(i),p=this.angleStart.getConnectedValue(i),g=this.angleEnd.getConnectedValue(i),x=this.transform.getConnectedValue(i),T=this.rotation.getConnectedValue(i),S=i.adaptInput(this.scaling,M.Vector3,m.OneReadOnly),v=(g-p)/s,b=p+v*this._currentIndex,A=Q.FromEulerAngles(0,b,0);h.copyFrom(x.clone().scale(this._currentIndex)),c.copyFrom(T.clone().scale(this._currentIndex)),u.copyFrom(S.clone().scale(this._currentIndex)),u.addInPlaceFromFloats(1,1,1),D.RotationYawPitchRollToRef(c.y,c.x,c.z,n),o.setTranslationFromFloats(0,0,_),D.ComposeToRef(u,A,h,l),n.multiplyToRef(o,o),o.multiplyToRef(l,l),i._instantiateWithMatrix(f,l,r)}if(r.length)if(r.length===1)this._vertexData=r[0];else{const d=r.splice(0,1)[0];this._vertexData=d.merge(r,!0,!1,!0,!0)}return i.restoreExecutionContext(),i.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}}V("BABYLON.InstantiateRadialBlock",c1);class u1 extends qe{constructor(e){super(e),this.registerInput("float ",M.Float,!0),this.registerInput("int ",M.Int,!0),this.registerOutput("float",M.Float),this.registerOutput("int",M.Int)}getClassName(){return"IntFloatConverterBlock"}get floatIn(){return this._inputs[0]}get intIn(){return this._inputs[1]}get floatOut(){return this._outputs[0]}get intOut(){return this._outputs[1]}_inputRename(e){return e==="float "?"floatIn":e==="int "?"intIn":e}_buildBlock(){this.floatOut._storedFunction=e=>this.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}V("BABYLON.IntFloatConverterBlock",u1);class d1 extends qe{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];const t=i=>{const s=this.input.getConnectedValue(i);if(s==null)return this.log.push(["null",""]),s;switch(this.input.type){case M.Vector2:this.log.push([bw(s,4),s.toString()]);break;case M.Vector3:this.log.push([Aw(s,4),s.toString()]);break;case M.Vector4:this.log.push([yw(s,4),s.toString()]);break;default:this.log.push([s.toString(),s.toString()]);break}return s};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}V("BABYLON.DebugBlock",d1);class f1 extends qe{constructor(e){super(e),this.registerInput("geometry",M.Geometry),this.registerOutput("output",M.Geometry),this.registerOutput("id",M.Int),this.registerOutput("collectionId",M.Int),this.registerOutput("verticesCount",M.Int),this.registerOutput("facesCount",M.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}V("BABYLON.GeometryInfoBlock",f1);var Vn;(function(a){a[a.Spherical=0]="Spherical",a[a.Cylindrical=1]="Cylindrical",a[a.Cubic=2]="Cubic"})(Vn||(Vn={}));class mC extends qe{constructor(e){super(e),this.mapping=Vn.Spherical,this.registerInput("position",M.Vector3),this.registerInput("normal",M.Vector3),this.registerInput("center",M.Vector3,!0,m.Zero()),this.registerOutput("uv",M.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}const e=m.Zero(),t=i=>{const s=this.position.getConnectedValue(i)||m.Zero(),r=this.normal.getConnectedValue(i)||m.Zero(),n=this.center.getConnectedValue(i),o=Z.Zero();switch(this.mapping){case Vn.Spherical:{s.subtractToRef(n,e);const l=e.length();l>0&&(o.x=Math.acos(e.y/l)/Math.PI,(e.x!==0||e.z!==0)&&(o.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case Vn.Cylindrical:{s.subtractToRef(n,e);const l=e.length();l>0&&(o.x=Math.atan2(e.x/l,e.z/l)/(Math.PI*2),o.y=(e.y+1)/2);break}case Vn.Cubic:{const l=Math.abs(r.x),h=Math.abs(r.y),c=Math.abs(r.z),u=Math.max(Math.abs(s.x),Math.abs(s.y),Math.abs(s.z));let d=0,f=0;l>=h&&l>=c?(d=s.y/u-n.y,f=s.z/u-n.z):h>=l&&h>=c?(d=s.x/u-n.x,f=s.z/u-n.z):(d=s.x/u-n.x,f=s.y/u-n.y),o.x=(d+1)/2,o.y=(f+1)/2}}return o};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Vn[this.mapping]};
`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}E([Le("Mapping",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Vn.Spherical},{label:"Cylindrical",value:Vn.Cylindrical},{label:"Cubic",value:Vn.Cubic}]})],mC.prototype,"mapping",void 0);V("BABYLON.MappingBlock",mC);class _1 extends qe{constructor(e){super(e),this.registerInput("matrix0",M.Matrix),this.registerInput("matrix1",M.Matrix),this.registerOutput("output",M.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return!t||!i?null:t.multiply(i)}}}V("BABYLON.MatrixComposeBlock",_1);class p1 extends qe{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",M.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)t.indexOf(s)===-1&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=t=>this.input.getConnectedValue(t)}}V("BABYLON.TeleportInBlock",p1);class m1 extends qe{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",M.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&t.indexOf(this.entryPoint)===-1&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});
`),e}serialize(){var t;const e=super.serialize();return e.entryPoint=((t=this.entryPoint)==null?void 0:t.uniqueId)??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}V("BABYLON.TeleportOutBlock",m1);class gC extends qe{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",M.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const l=n.getImageData(0,0,s.width,s.height).data,h=new Float32Array(l.length);for(let c=0;c<l.length;c++)h[c]=l[c]/255;this._data=h,this._width=s.width,this._height=s.height,t()},s.onerror=()=>{this._data=null,i()},s.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}const s=e.getSize();DI.GetTextureDataAsync(e,s.width,s.height).then(async r=>{const n=new Float32Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]/255;this._data=n,this._width=s.width,this._height=s.height,t()}).catch(i)})}_buildBlock(){if(!this._data){this.texture._storedValue=null;return}const e={data:this._data,width:this._width,height:this._height};this.texture._storedValue=e}serialize(){const e=super.serialize();return e.width=this._width,e.height=this._height,e.serializedCachedData=this.serializedCachedData,this._data&&this.serializedCachedData&&(e.data=Array.from(this._data)),e}_deserialize(e){super._deserialize(e),this._width=e.width,this._height=e.height,e.data?(this._data=new Float32Array(e.data),this.serializedCachedData=!0):this.serializedCachedData=!!e.serializedCachedData}}E([Le("Serialize cached data",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gC.prototype,"serializedCachedData",void 0);V("BABYLON.GeometryTextureBlock",gC);class xC extends qe{constructor(e){super(e),this.clampCoordinates=!0,this.registerInput("texture",M.Texture),this.registerInput("coordinates",M.Vector2),this.registerOutput("rgba",M.Vector4),this.registerOutput("rgb",M.Vector3),this.registerOutput("r",M.Float),this.registerOutput("g",M.Float),this.registerOutput("b",M.Float),this.registerOutput("a",M.Float)}getClassName(){return"GeometryTextureFetchBlock"}get texture(){return this.inputs[0]}get coordinates(){return this.inputs[1]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}_repeatClamp(e){return e>=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=t=>{const i=this.texture.getConnectedValue(t);if(!i||!i.data)return null;const s=this.coordinates.getConnectedValue(t);if(!s)return null;const r=this.clampCoordinates?Math.max(0,Math.min(s.x,1)):this._repeatClamp(s.x),n=this.clampCoordinates?Math.max(0,Math.min(s.y,1)):this._repeatClamp(s.y),o=Math.floor(r*(i.width-1)),l=Math.floor(n*(i.height-1)),h=o+i.width*l;return we.FromArray(i.data,h*4)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};
`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}E([Le("Clamp Coordinates",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xC.prototype,"clampCoordinates",void 0);V("BABYLON.GeometryTextureFetchBlock",xC);class g1 extends qe{constructor(e){super(e),this.registerInput("geometry",M.Geometry),this.registerOutput("min",M.Vector3),this.registerOutput("max",M.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Au(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Au(t.positions,0,t.positions.length/3).maximum:null}}}V("BABYLON.BoundingBlock",g1);var kn;(function(a){a[a.Intersect=0]="Intersect",a[a.Subtract=1]="Subtract",a[a.Union=2]="Union"})(kn||(kn={}));class bg extends qe{constructor(e){super(e),this.evaluateContext=!1,this.operation=kn.Intersect,this.registerInput("geometry0",M.Geometry),this.registerInput("geometry1",M.Geometry),this.registerOutput("output",M.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=i=>{const s=this.geometry0.getConnectedValue(i),r=this.geometry1.getConnectedValue(i);if(!s||!r)return null;const n=s.positions.length/3;!s.normals&&r.normals&&(s.normals=new Array(s.positions.length)),!r.normals&&s.normals&&(r.normals=new Array(r.positions.length)),!s.uvs&&r.uvs&&(s.uvs=new Array(n*2)),!r.uvs&&s.uvs&&(r.uvs=new Array(n*2)),!s.colors&&r.colors&&(s.colors=new Array(n*4)),!r.colors&&s.colors&&(r.colors=new Array(n*4));const o=wn.FromVertexData(s),l=wn.FromVertexData(r);let h;switch(this.operation){case kn.Intersect:h=o.intersect(l);break;case kn.Subtract:h=o.subtract(l);break;case kn.Union:h=o.union(l);break}return h.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};
`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${kn[this.operation]};
`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}E([Le("Evaluate context",Ne.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bg.prototype,"evaluateContext",void 0);E([Le("Operation",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:kn.Intersect},{label:"Subtract",value:kn.Subtract},{label:"Union",value:kn.Union}]})],bg.prototype,"operation",void 0);V("BABYLON.BooleanGeometryBlock",bg);class x1 extends qe{constructor(e){super(e),this.registerInput("x",M.AutoDetect),this.registerInput("y",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.atan2(t,i);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case M.Int:case M.Float:return e(i,s);case M.Vector2:return new Z(e(i.x,s.x),e(i.y,s.y));case M.Vector3:return new m(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case M.Vector4:return new we(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}V("BABYLON.GeometryArcTan2Block",x1);class T1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerInput("gradient",M.Float),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,s)=>(1-t)*i+t*s;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case M.Int:case M.Float:return e(r,i,s);case M.Vector2:return new Z(e(r,i.x,s.x),e(r,i.y,s.y));case M.Vector3:return new m(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case M.Vector4:return new we(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}V("BABYLON.GeometryLerpBlock",T1);class E1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerInput("gradient",M.Float),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,s)=>(1-t)*i+t*s;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case M.Int:case M.Float:return e(r,i,s);case M.Vector2:{const n=new Z(e(r,i.x,s.x),e(r,i.y,s.y));return n.normalize(),n}case M.Vector3:{const n=new m(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return n.normalize(),n}case M.Vector4:{const n=new we(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return n.normalize(),n}}return 0},this}}V("BABYLON.GeometryNLerpBlock",E1);class S1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("edge",M.Float),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t<i?0:1;return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case M.Int:case M.Float:return e(i,s);case M.Vector2:return new Z(e(i.x,s),e(i.y,s));case M.Vector3:return new m(e(i.x,s),e(i.y,s),e(i.z,s));case M.Vector4:return new we(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}V("BABYLON.GeometryStepBlock",S1);class C1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("edge0",M.Float),this.registerInput("edge1",M.Float),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i,s)=>{const r=Math.max(0,Math.min((t-i)/(s-i),1));return r*r*(3-2*r)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case M.Int:case M.Float:return e(i,s,r);case M.Vector2:return new Z(e(i.x,s,r),e(i.y,s,r));case M.Vector3:return new m(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case M.Vector4:return new we(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}V("BABYLON.GeometrySmoothStepBlock",C1);class v1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>t-Math.floor(t/i)*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case M.Int:case M.Float:return e(i,s);case M.Vector2:return new Z(e(i.x,s.x),e(i.y,s.y));case M.Vector3:return new m(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case M.Vector4:return new we(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}V("BABYLON.GeometryModBlock",v1);class b1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("power",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=(t,i)=>Math.pow(t,i);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case M.Int:case M.Float:return e(i,s);case M.Vector2:return new Z(e(i.x,s),e(i.y,s));case M.Vector3:return new m(e(i.x,s),e(i.y,s),e(i.z,s));case M.Vector4:return new we(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}V("BABYLON.GeometryPowBlock",b1);class Ag extends qe{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Geometry),this._inputs[0].excludedConnectionPointTypes.push(M.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}const e=t=>Math.max(this.minimum,Math.min(t,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case M.Int:case M.Float:return e(i);case M.Vector2:return new Z(e(i.x),e(i.y));case M.Vector3:return new m(e(i.x),e(i.y),e(i.z));case M.Vector4:return new we(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};
`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};
`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}E([Le("Minimum",Ne.Float)],Ag.prototype,"minimum",void 0);E([Le("Maximum",Ne.Float)],Ag.prototype,"maximum",void 0);V("BABYLON.GeometryClampBlock",Ag);class A1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Int),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Vector2),this._inputs[1].excludedConnectionPointTypes.push(M.Int),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case M.Vector3:return m.Cross(t,i);case M.Vector4:return m.Cross(t.toVector3(),i.toVector3())}return 0},this}}V("BABYLON.GeometryCrossBlock",A1);var at;(function(a){a[a.EaseInSine=0]="EaseInSine",a[a.EaseOutSine=1]="EaseOutSine",a[a.EaseInOutSine=2]="EaseInOutSine",a[a.EaseInQuad=3]="EaseInQuad",a[a.EaseOutQuad=4]="EaseOutQuad",a[a.EaseInOutQuad=5]="EaseInOutQuad",a[a.EaseInCubic=6]="EaseInCubic",a[a.EaseOutCubic=7]="EaseOutCubic",a[a.EaseInOutCubic=8]="EaseInOutCubic",a[a.EaseInQuart=9]="EaseInQuart",a[a.EaseOutQuart=10]="EaseOutQuart",a[a.EaseInOutQuart=11]="EaseInOutQuart",a[a.EaseInQuint=12]="EaseInQuint",a[a.EaseOutQuint=13]="EaseOutQuint",a[a.EaseInOutQuint=14]="EaseInOutQuint",a[a.EaseInExpo=15]="EaseInExpo",a[a.EaseOutExpo=16]="EaseOutExpo",a[a.EaseInOutExpo=17]="EaseInOutExpo",a[a.EaseInCirc=18]="EaseInCirc",a[a.EaseOutCirc=19]="EaseOutCirc",a[a.EaseInOutCirc=20]="EaseInOutCirc",a[a.EaseInBack=21]="EaseInBack",a[a.EaseOutBack=22]="EaseOutBack",a[a.EaseInOutBack=23]="EaseInOutBack",a[a.EaseInElastic=24]="EaseInElastic",a[a.EaseOutElastic=25]="EaseOutElastic",a[a.EaseInOutElastic=26]="EaseInOutElastic"})(at||(at={}));class TC extends qe{constructor(e){super(e),this.type=at.EaseInOutSine,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e;switch(this.type){case at.EaseInSine:e=t=>1-Math.cos(t*3.1415/2);break;case at.EaseOutSine:e=t=>Math.sin(t*3.1415/2);break;case at.EaseInOutSine:e=t=>-(Math.cos(t*3.1415)-1)/2;break;case at.EaseInQuad:e=t=>t*t;break;case at.EaseOutQuad:e=t=>(1-t)*(1-t);break;case at.EaseInOutQuad:{e=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break}case at.EaseInCubic:e=t=>t*t*t;break;case at.EaseOutCubic:{e=t=>1-Math.pow(1-t,3);break}case at.EaseInOutCubic:{e=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;break}case at.EaseInQuart:e=t=>t*t*t*t;break;case at.EaseOutQuart:{e=t=>1-Math.pow(1-t,4);break}case at.EaseInOutQuart:{e=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;break}case at.EaseInQuint:e=t=>t*t*t*t*t;break;case at.EaseOutQuint:{e=t=>1-Math.pow(1-t,5);break}case at.EaseInOutQuint:{e=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;break}case at.EaseInExpo:{e=t=>t===0?0:Math.pow(2,10*t-10);break}case at.EaseOutExpo:{e=t=>t===1?1:1-Math.pow(2,-10*t);break}case at.EaseInOutExpo:{e=t=>t===0?0:t===1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2;break}case at.EaseInCirc:{e=t=>1-Math.sqrt(1-Math.pow(t,2));break}case at.EaseOutCirc:{e=t=>Math.sqrt(1-Math.pow(t-1,2));break}case at.EaseInOutCirc:{e=t=>t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2;break}case at.EaseInBack:{e=t=>2.70158*t*t*t-1.70158*t*t;break}case at.EaseOutBack:{e=t=>2.70158*Math.pow(t-1,3)+1.70158*Math.pow(t-1,2);break}case at.EaseInOutBack:{e=t=>t<.5?Math.pow(2*t,2)*(3.5949095*2*t-2.5949095)/2:(Math.pow(2*t-2,2)*(3.5949095*(t*2-2)+3.5949095)+2)/2;break}case at.EaseInElastic:{e=t=>t===0?0:t===1?1:-Math.pow(2,10*t-10)*Math.sin((t*10-10.75)*(2*3.1415/3));break}case at.EaseOutElastic:{e=t=>t===0?0:t===1?1:Math.pow(2,-10*t)*Math.sin((t*10-.75)*(2*3.1415/3))+1;break}case at.EaseInOutElastic:{e=t=>t===0?0:t==1?1:t<.5?-(Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*(2*3.1415/4.5)))/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*(2*3.1415/4.5))/2+1;break}}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case M.Float:return e(i);case M.Vector2:return new Z(e(i.x),e(i.y));case M.Vector3:return new m(e(i.x),e(i.y),e(i.z));case M.Vector4:return new we(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${at[this.type]};
`}}E([Le("Type",Ne.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:at.EaseInSine},{label:"EaseOutSine",value:at.EaseOutSine},{label:"EaseInOutSine",value:at.EaseInOutSine},{label:"EaseInQuad",value:at.EaseInQuad},{label:"EaseOutQuad",value:at.EaseOutQuad},{label:"EaseInOutQuad",value:at.EaseInOutQuad},{label:"EaseInCubic",value:at.EaseInCubic},{label:"EaseOutCubic",value:at.EaseOutCubic},{label:"EaseInOutCubic",value:at.EaseInOutCubic},{label:"EaseInQuart",value:at.EaseInQuart},{label:"EaseOutQuart",value:at.EaseOutQuart},{label:"EaseInOutQuart",value:at.EaseInOutQuart},{label:"EaseInQuint",value:at.EaseInQuint},{label:"EaseOutQuint",value:at.EaseOutQuint},{label:"EaseInOutQuint",value:at.EaseInOutQuint},{label:"EaseInExpo",value:at.EaseInExpo},{label:"EaseOutExpo",value:at.EaseOutExpo},{label:"EaseInOutExpo",value:at.EaseInOutExpo},{label:"EaseInCirc",value:at.EaseInCirc},{label:"EaseOutCirc",value:at.EaseOutCirc},{label:"EaseInOutCirc",value:at.EaseInOutCirc},{label:"EaseInBack",value:at.EaseInBack},{label:"EaseOutBack",value:at.EaseOutBack},{label:"EaseInOutBack",value:at.EaseInOutBack},{label:"EaseInElastic",value:at.EaseInElastic},{label:"EaseOutElastic",value:at.EaseOutElastic},{label:"EaseInOutElastic",value:at.EaseInOutElastic}]})],TC.prototype,"type",void 0);V("BABYLON.GeometryCurveBlock",TC);class y1 extends qe{constructor(e){super(e),this.registerInput("color",M.Vector3),this.registerInput("level",M.Float,!0,0),this.registerOutput("output",M.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.color.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=Math.min(t.x,t.y,t.z),r=Math.max(t.x,t.y,t.z),n=.5*(s+r);return new m(t.x*(1-i)+n*i,t.y*(1-i)+n*i,t.z*(1-i)+n*i)},this}}V("BABYLON.GeometryDesaturateBlock",y1);class R1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("steps",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(M.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.steps.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===M.Float)switch(this.value.type){case M.Vector2:s=new Z(i,i);break;case M.Vector3:s=new m(i,i,i);break;case M.Vector4:s=new we(i,i,i,i);break}switch(this.value.type){case M.Vector2:return new Z(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case M.Vector3:return new m(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case M.Vector4:return new we(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this}}V("BABYLON.GeometryPosterizeBlock",R1);class I1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerInput("reference",M.AutoDetect),this.registerInput("distance",M.Float),this.registerInput("replacement",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[3].excludedConnectionPointTypes.push(M.Float),this._inputs[3].excludedConnectionPointTypes.push(M.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.reference.isConnected||!this.distance.isConnected||!this.replacement.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length()<s?r:t},this}}V("BABYLON.GeometryReplaceColorBlock",I1);class P1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Int),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix)}getClassName(){return"GeometryDistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this}}V("BABYLON.GeometryDistanceBlock",P1);class M1 extends qe{constructor(e){super(e),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Int),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this}}V("BABYLON.GeometryDotBlock",M1);class D1 extends qe{constructor(e){super(e),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Int),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this}}V("BABYLON.GeometryLengthBlock",D1);class O1 extends qe{constructor(e){super(e),this.registerInput("input",M.Vector2),this.registerInput("angle",M.Float),this.registerOutput("output",M.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.angle.isConnected||!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}return this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new Z(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this}}V("BABYLON.GeometryRotate2dBlock",O1);class wo extends z{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=D.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new le;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new Ss(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new Nu(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const r=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(r-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=new TextDecoder().decode(t.slice(0,1024*10)),s=`end_header
`,r=i.indexOf(s);if(r<0||!i)return e;const n=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let o=0;const l={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},h=[],c=i.slice(0,r).split(`
`).filter(g=>g.startsWith("property "));for(const g of c){const[,x,T]=g.split(" ");if(h.push({name:T,type:x,offset:o}),l[x])o+=l[x];else return O.Error(`Unsupported property type: ${x}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0)}const u=3*4+3*4+4+4,d=.28209479177387814,f=new DataView(e,r+s.length),_=new ArrayBuffer(u*n),p=new Q;for(let g=0;g<n;g++){const x=new Float32Array(_,g*u,3),T=new Float32Array(_,g*u+12,3),S=new Uint8ClampedArray(_,g*u+24,4),C=new Uint8ClampedArray(_,g*u+28,4);let v=255,b=0,A=0,P=0;for(let L=0;L<h.length;L++){const w=h[L];let $;switch(w.type){case"float":$=f.getFloat32(w.offset+g*o,!0);break;case"int":$=f.getInt32(w.offset+g*o,!0);break;default:throw new Error(`Unsupported property type: ${w.type}`)}switch(w.name){case"x":x[0]=$;break;case"y":x[1]=$;break;case"z":x[2]=$;break;case"scale_0":T[0]=Math.exp($);break;case"scale_1":T[1]=Math.exp($);break;case"scale_2":T[2]=Math.exp($);break;case"red":S[0]=$;break;case"green":S[1]=$;break;case"blue":S[2]=$;break;case"f_dc_0":S[0]=(.5+d*$)*255;break;case"f_dc_1":S[1]=(.5+d*$)*255;break;case"f_dc_2":S[2]=(.5+d*$)*255;break;case"f_dc_3":S[3]=(.5+d*$)*255;break;case"opacity":S[3]=1/(1+Math.exp(-$))*255;break;case"rot_0":v=$;break;case"rot_1":b=$;break;case"rot_2":A=$;break;case"rot_3":P=$;break}}p.set(b,A,P,v),p.normalize(),C[0]=p.w*128+128,C[1]=p.x*128+128,C[2]=p.y*128+128,C[3]=p.z*128+128}return _}loadDataAsync(e){return Promise.resolve(this._loadData(e))}loadFileAsync(e){return X.LoadFileAsync(e,!0).then(t=>{this._loadData(wo.ConvertPLYToSplat(t))})}dispose(e){var t,i,s,r,n,o;(t=this._covariancesATexture)==null||t.dispose(),(i=this._covariancesBTexture)==null||i.dispose(),(s=this._centersTexture)==null||s.dispose(),(r=this._colorsTexture)==null||r.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,(n=this._material)==null||n.dispose(!1,!0),this._material=null,(o=this._worker)==null||o.terminate(),this._worker=null,super.dispose(e)}_loadData(e){var v;if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=3*4+3*4+4+4,r=t.length/s;this._vertexCount=r;const n=this._getTextureSize(r),o=n.x*n.y,l=new Float32Array(3*o),h=new Float32Array(3*o),c=new Float32Array(3*o),u=U.Matrix[0],d=U.Matrix[1],f=U.Quaternion[0],_=new m(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new m(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let b=0;b<r;b++){const A=i[8*b+0],P=-i[8*b+1],L=i[8*b+2];l[3*b+0]=A,l[3*b+1]=P,l[3*b+2]=L,_.minimizeInPlaceFromFloats(A,P,L),p.maximizeInPlaceFromFloats(A,P,L),f.set((t[32*b+28+1]-128)/128,(t[32*b+28+2]-128)/128,(t[32*b+28+3]-128)/128,-(t[32*b+28+0]-128)/128),f.toRotationMatrix(u),D.ScalingToRef(i[8*b+3+0]*2,i[8*b+3+1]*2,i[8*b+3+2]*2,d);const w=u.multiplyToRef(d,U.Matrix[0]).m;h[b*3+0]=w[0]*w[0]+w[1]*w[1]+w[2]*w[2],h[b*3+1]=w[0]*w[4]+w[1]*w[5]+w[2]*w[6],h[b*3+2]=w[0]*w[8]+w[1]*w[9]+w[2]*w[10],c[b*3+0]=w[4]*w[4]+w[5]*w[5]+w[6]*w[6],c[b*3+1]=w[4]*w[8]+w[5]*w[9]+w[6]*w[10],c[b*3+2]=w[8]*w[8]+w[9]*w[9]+w[10]*w[10]}const g=this.getBoundingInfo();g.reConstruct(_,p,this.getWorldMatrix()),g.isLocked=!0,this.forcedInstanceCount=this._vertexCount,this.setEnabled(!0);const x=new Float32Array(this._vertexCount*1);this.thinInstanceSetBuffer("splatIndex",x,1,!1);const T=(b,A,P,L)=>new Fi(b,A,P,L,this._scene,!1,!1,2,1),S=b=>{const A=b.length/3,P=new Float32Array(A*4);for(let L=0;L<A;++L)P[L*4+0]=b[L*3+0],P[L*4+1]=b[L*3+1],P[L*4+2]=b[L*3+2],P[L*4+3]=1;return P},C=new Float32Array(n.x*n.y*4);for(let b=0;b<this._vertexCount;++b)C[b*4+0]=t[32*b+24+0]/255,C[b*4+1]=t[32*b+24+1]/255,C[b*4+2]=t[32*b+24+2]/255,C[b*4+3]=t[32*b+24+3]/255;this._covariancesATexture=T(S(h),n.x,n.y,5),this._covariancesBTexture=T(S(c),n.x,n.y,5),this._centersTexture=T(S(l),n.x,n.y,5),this._colorsTexture=T(C,n.x,n.y,5),(v=this._worker)==null||v.terminate(),this._worker=new Worker(URL.createObjectURL(new Blob(["(",wo._CreateWorker.toString(),")(self)"],{type:"application/javascript"}))),this._depthMix=new BigInt64Array(r),this._worker.postMessage({positions:l,vertexCount:r},[l.buffer]),this._worker.onmessage=b=>{this._depthMix=b.data.depthMix;const A=new Uint32Array(b.data.depthMix.buffer);for(let P=0;P<this._vertexCount;P++)x[P]=A[2*P];this.thinInstanceBufferUpdated("splatIndex"),this._canPostToWorker=!0}}_getTextureSize(e){const t=this._scene.getEngine(),i=t.getCaps().maxTextureSize;let s=1;if(t.webGLVersion===1&&!t.isWebGPU)for(;i*s<e;)s*=2;else s=Math.ceil(e/i);return s>i&&(O.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new Z(i,s)}}wo._CreateWorker=function(a){let e=0,t,i,s,r;a.onmessage=n=>{if(n.data.positions)t=n.data.positions,e=n.data.vertexCount;else{const o=n.data.view;if(!t||!o)throw new Error("positions or view is not defined!");i=n.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let l=0;l<e;l++)s[2*l]=l;for(let l=0;l<e;l++)r[2*l+1]=1e4-(o[2]*t[3*l+0]+o[6]*t[3*l+1]+o[10]*t[3*l+2]);i.sort(),a.postMessage({depthMix:i},[i.buffer])}}};H.OfflineProviderFactory=(a,e,t=!1)=>new Ys(a,e,t);class Ys{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory=typeof indexedDB<"u"?indexedDB:void 0,this._currentSceneUrl=Ys._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Ys.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,X.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if(typeof URL=="function"&&this._currentSceneUrl.indexOf("http")===0){const o=new URL(this._currentSceneUrl);return o.pathname+=".manifest",o.toString()}}catch{}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new yi;navigator.onLine&&(s=!0,r=r+(r.match(/\?/)==null?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",()=>{if(n.status===200||Ys._ValidateXHRData(n,1))try{const o=JSON.parse(n.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&Ys._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),n.addEventListener("error",()=>{if(s){s=!1;const o=i();n.open("GET",o),n.send()}else t()},!1);try{n.send()}catch{O.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(!this._idbFactory||!(this._enableSceneOffline||this._enableTexturesOffline))this._isSupported=!1,t&&t();else if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const s=this._idbFactory.open("babylonjs",1);s.onerror=()=>{i()},s.onblocked=()=>{O.Error("IDB request blocked. Please reload the page."),i()},s.onsuccess=()=>{this._db=s.result,e()},s.onupgradeneeded=r=>{if(this._db=r.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(n){O.Error("Error while creating object stores. Exception: "+n.message),i()}}}}loadImage(e,t){const i=Ys._ReturnFullUrlLocation(e),s=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let o;s&&typeof URL=="function"?(o=URL.createObjectURL(s.data),t.onerror=()=>{O.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const n=r.objectStore("textures").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{O.Error("Error loading texture "+e+" from DB."),t.src=e}}else O.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let r;if(i&&typeof URL=="function")try{r=URL.createObjectURL(i)}catch{r=URL.createObjectURL(i)}r&&(t.src=r)};if(Ys._IsUASupportingBlobStorage){const r=new yi;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(r.status===200&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=l=>{try{const c=l.target.error;c&&c.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const l=n.objectStore("textures").put(o);l.onsuccess=()=>{},l.onerror=()=>{s()}}catch(l){l.code===25&&(Ys._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{O.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else O.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){const i=()=>{this._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,i)}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{O.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(r){O.Error("Error while accessing 'versions' object store (READ OP). Exception: "+r.message),t(-1)}}else O.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=n=>{try{const o=n.target.error;o&&o.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{O.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){O.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=Ys._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,l=>{l!==-1?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s;e.indexOf(".babylon")!==-1?s="scenes":s="textures";let r;const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=l=>{r=l.target.result},o.onerror=()=>{O.Error("Error loading file "+e+" from DB."),i()}}else O.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;e.indexOf(".babylon")!==-1?n="scenes":n="textures";const o=new yi;let l;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&Ys._ValidateXHRData(o,s?6:1))if(l=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const h=this._db.transaction([n],"readwrite");h.onabort=u=>{try{const d=u.target.error;d&&d.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(l)},h.oncomplete=()=>{t(l)};let c;n==="scenes"?c={sceneUrl:e,data:l,version:this._manifestVersionFound}:c={textureUrl:e,data:l};try{const u=h.objectStore(n).put(c);u.onsuccess=()=>{},u.onerror=()=>{O.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else o.status>=400&&r?r(o):t()},!1),o.addEventListener("error",()=>{O.Error("error on XHR request."),r&&r()},!1),o.send()}else O.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(t&1){if(e.responseText&&e.responseText.length>0)return!0;if(t===1)return!1}if(t&2){const i=i_(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(t===2)return!1}if(t&4){const i=new Uint8Array(e.response,0,3);return i[0]===68&&i[1]===68&&i[2]===83}}catch{}return!1}}Ys._IsUASupportingBlobStorage=!0;Ys.IDBStorageEnabled=!1;Ys._ParseURL=a=>{const e=document.createElement("a");e.href=a;const t=a.substring(0,a.lastIndexOf("#")),i=a.substring(t.lastIndexOf("/")+1,a.length);return a.substring(0,a.indexOf(i,0))};Ys._ReturnFullUrlLocation=a=>a.indexOf("http:/")===-1&&a.indexOf("https:/")===-1&&typeof window<"u"?Ys._ParseURL(window.location.href)+a:a;class Ha{constructor(){this.direction1=new m(0,1,0),this.direction2=new m(0,1,0),this.minEmitBox=new m(-.5,-.5,-.5),this.maxEmitBox=new m(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=Pt(this.direction1.x,this.direction2.x),n=Pt(this.direction1.y,this.direction2.y),o=Pt(this.direction1.z,this.direction2.z);if(s){t.x=r,t.y=n,t.z=o;return}m.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=Pt(this.minEmitBox.x,this.maxEmitBox.x),n=Pt(this.minEmitBox.y,this.maxEmitBox.y),o=Pt(this.minEmitBox.z,this.maxEmitBox.z);if(s){t.x=r,t.y=n,t.z=o;return}m.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new Ha;return Cs.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){m.FromArrayToRef(e.direction1,0,this.direction1),m.FromArrayToRef(e.direction2,0,this.direction2),m.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),m.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class o_{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){this._angle!==0?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?U.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),U.Vector3[0]).normalize();const r=ge.RandomRange(0,this.directionRandomizer),n=ge.RandomRange(0,this.directionRandomizer),o=ge.RandomRange(0,this.directionRandomizer);t.x=U.Vector3[0].x+r,t.y=U.Vector3[0].y+n,t.z=U.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=ge.RandomRange(0,Math.PI*2);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=ge.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-ge.RandomRange(0,this._radius*this.radiusRange);o=o*n;const l=o*Math.sin(r),h=o*Math.cos(r),c=n*this._height;if(s){t.x=l,t.y=c,t.z=h;return}m.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new o_(this._radius,this._angle,this.directionRandomizer);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+=`
#define CONEEMITTERSPAWNPOINT`),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=e.radiusRange!==void 0?e.radiusRange:1,this.heightRange=e.radiusRange!==void 0?e.heightRange:1,this.emitFromSpawnPointOnly=e.emitFromSpawnPointOnly!==void 0?e.emitFromSpawnPointOnly:!1}}class rd{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=m.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),m.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=ge.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=ge.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s){t.copyFrom(this._tempVector);return}m.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=ge.RandomRange(-this.height/2,this.height/2),n=ge.RandomRange(0,2*Math.PI),o=ge.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(o)*this.radius,h=l*Math.cos(n),c=l*Math.sin(n);if(s){t.copyFromFloats(h,r,c);return}m.TransformCoordinatesFromFloatsToRef(h,r,c,e,t)}clone(){const e=new rd(this.radius,this.directionRandomizer);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class l_ extends rd{constructor(e=1,t=1,i=1,s=new m(0,1,0),r=new m(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=ge.RandomRange(this.direction1.x,this.direction2.x),n=ge.RandomRange(this.direction1.y,this.direction2.y),o=ge.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}m.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new l_(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define CYLINDEREMITTER
#define DIRECTEDCYLINDEREMITTER`}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class h_{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=ge.RandomRange(0,this.directionRandomizer),o=ge.RandomRange(0,this.directionRandomizer),l=ge.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}m.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-ge.RandomRange(0,this.radius*this.radiusRange),n=ge.RandomRange(0,1),o=ge.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(o)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(h,Math.abs(c),u);return}m.TransformCoordinatesFromFloatsToRef(h,Math.abs(c),u,e,t)}clone(){const e=new h_(this.radius,this.directionRandomizer);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class c_{constructor(){this.direction1=new m(0,1,0),this.direction2=new m(0,1,0)}startDirectionFunction(e,t,i,s){const r=ge.RandomRange(this.direction1.x,this.direction2.x),n=ge.RandomRange(this.direction1.y,this.direction2.y),o=ge.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}m.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(s){t.copyFromFloats(0,0,0);return}m.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new c_;return Cs.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){m.FromArrayToRef(e.direction1,0,this.direction1),m.FromArrayToRef(e.direction2,0,this.direction2)}}class nd{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=ge.RandomRange(0,this.directionRandomizer),o=ge.RandomRange(0,this.directionRandomizer),l=ge.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}m.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-ge.RandomRange(0,this.radius*this.radiusRange),n=ge.RandomRange(0,1),o=ge.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(o)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(h,c,u);return}m.TransformCoordinatesFromFloatsToRef(h,c,u,e,t)}clone(){const e=new nd(this.radius,this.directionRandomizer);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class u_ extends nd{constructor(e=1,t=new m(0,1,0),i=new m(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=ge.RandomRange(this.direction1.x,this.direction2.x),s=ge.RandomRange(this.direction1.y,this.direction2.y),r=ge.RandomRange(this.direction1.z,this.direction2.z);m.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new u_(this.radius,this.direction1,this.direction2);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return`#define SPHEREEMITTER
#define DIRECTEDSPHEREEMITTER`}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class Xa{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=U.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const n=U.Vector3[1];r.subtractToRef(i.position,n),n.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);if(s){t.copyFrom(r);return}m.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=U.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s){t.copyFrom(r);return}m.TransformCoordinatesToRef(r,e,t)}clone(){const e=new Xa;return Cs.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class yg{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(y.PositionKind),this._normals=e.getVerticesData(y.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=m.Zero(),this._mesh=null,this.direction1=new m(0,1,0),this.direction2=new m(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals){m.TransformNormalToRef(this._storedNormal,e,t);return}const r=ge.RandomRange(this.direction1.x,this.direction2.x),n=ge.RandomRange(this.direction1.y,this.direction2.y),o=ge.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}m.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),l=1-n-o,h=this._indices[r],c=this._indices[r+1],u=this._indices[r+2],d=U.Vector3[0],f=U.Vector3[1],_=U.Vector3[2],p=U.Vector3[3];m.FromArrayToRef(this._positions,h*3,d),m.FromArrayToRef(this._positions,c*3,f),m.FromArrayToRef(this._positions,u*3,_),p.x=n*d.x+o*f.x+l*_.x,p.y=n*d.y+o*f.y+l*_.y,p.z=n*d.z+o*f.z+l*_.z,s?t.copyFromFloats(p.x,p.y,p.z):m.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(m.FromArrayToRef(this._normals,h*3,d),m.FromArrayToRef(this._normals,c*3,f),m.FromArrayToRef(this._normals,u*3,_),this._storedNormal.x=n*d.x+o*f.x+l*_.x,this._storedNormal.y=n*d.y+o*f.y+l*_.y,this._storedNormal.z=n*d.z+o*f.z+l*_.z)}clone(){const e=new yg(this.mesh);return Cs.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var t;const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=(t=this.mesh)==null?void 0:t.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){m.FromArrayToRef(e.direction1,0,this.direction1),m.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class EC{_isUbo(e){return e.addUniform!==void 0}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}const N1="gpuUpdateParticlesPixelShader",F1=`#version 300 es
void main() {discard;}
`;W.ShadersStore[N1]=F1;const w1="gpuUpdateParticlesVertexShader",L1=`#version 300 es
#define PI 3.14159
uniform float currentCount;uniform float timeDelta;uniform float stopFactor;
#ifndef LOCAL
uniform mat4 emitterWM;
#endif
uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;
#ifndef COLORGRADIENTS
uniform vec4 color1;uniform vec4 color2;
#endif
uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;
#ifdef BOXEMITTER
uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;
#endif
#ifdef POINTEMITTER
uniform vec3 direction1;uniform vec3 direction2;
#endif
#ifdef HEMISPHERICEMITTER
uniform float radius;uniform float radiusRange;uniform float directionRandomizer;
#endif
#ifdef SPHEREEMITTER
uniform float radius;uniform float radiusRange;
#ifdef DIRECTEDSPHEREEMITTER
uniform vec3 direction1;uniform vec3 direction2;
#else
uniform float directionRandomizer;
#endif
#endif
#ifdef CYLINDEREMITTER
uniform float radius;uniform float height;uniform float radiusRange;
#ifdef DIRECTEDCYLINDEREMITTER
uniform vec3 direction1;uniform vec3 direction2;
#else
uniform float directionRandomizer;
#endif
#endif
#ifdef CONEEMITTER
uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;
#endif
in vec3 position;
#ifdef CUSTOMEMITTER
in vec3 initialPosition;
#endif
in float age;in float life;in vec4 seed;in vec3 size;
#ifndef COLORGRADIENTS
in vec4 color;
#endif
in vec3 direction;
#ifndef BILLBOARD
in vec3 initialDirection;
#endif
#ifdef ANGULARSPEEDGRADIENTS
in float angle;
#else
in vec2 angle;
#endif
#ifdef ANIMATESHEET
in float cellIndex;
#ifdef ANIMATESHEETRANDOMSTART
in float cellStartOffset;
#endif
#endif
#ifdef NOISE
in vec3 noiseCoordinates1;in vec3 noiseCoordinates2;
#endif
out vec3 outPosition;
#ifdef CUSTOMEMITTER
out vec3 outInitialPosition;
#endif
out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;
#ifndef COLORGRADIENTS
out vec4 outColor;
#endif
out vec3 outDirection;
#ifndef BILLBOARD
out vec3 outInitialDirection;
#endif
#ifdef ANGULARSPEEDGRADIENTS
out float outAngle;
#else
out vec2 outAngle;
#endif
#ifdef ANIMATESHEET
out float outCellIndex;
#ifdef ANIMATESHEETRANDOMSTART
out float outCellStartOffset;
#endif
#endif
#ifdef NOISE
out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;
#endif
#ifdef SIZEGRADIENTS
uniform sampler2D sizeGradientSampler;
#endif 
#ifdef ANGULARSPEEDGRADIENTS
uniform sampler2D angularSpeedGradientSampler;
#endif 
#ifdef VELOCITYGRADIENTS
uniform sampler2D velocityGradientSampler;
#endif
#ifdef LIMITVELOCITYGRADIENTS
uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;
#endif
#ifdef DRAGGRADIENTS
uniform sampler2D dragGradientSampler;
#endif
#ifdef NOISE
uniform vec3 noiseStrength;uniform sampler2D noiseSampler;
#endif
#ifdef ANIMATESHEET
uniform vec4 cellInfos;
#endif
vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}
vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}
void main() {float newAge=age+timeDelta; 
if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;
#ifdef SIZEGRADIENTS 
outSize.x=texture(sizeGradientSampler,vec2(0,0)).r;
#else
outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;
#endif
outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; 
#ifndef COLORGRADIENTS
outColor=color1+(color2-color1)*randoms.b;
#endif
#ifndef ANGULARSPEEDGRADIENTS 
outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;
#else
outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;
#endif 
#ifdef POINTEMITTER
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;
#elif defined(BOXEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; 
#elif defined(HEMISPHERICEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; 
#elif defined(SPHEREEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);
#ifdef DIRECTEDSPHEREEMITTER
newDirection=normalize(direction1+(direction2-direction1)*randoms3);
#else
newDirection=normalize(newPosition+directionRandomizer*randoms3);
#endif
#elif defined(CYLINDEREMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);
#ifdef DIRECTEDCYLINDEREMITTER
newDirection=direction1+(direction2-direction1)*randoms3;
#else
angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);
#endif
#elif defined(CONEEMITTER)
vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;
#ifdef CONEEMITTERSPAWNPOINT
float h=0.0001;
#else
float h=randoms2.y*height.y;h=1.-h*h; 
#endif
float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); 
if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }
#elif defined(CUSTOMEMITTER)
newPosition=initialPosition;outInitialPosition=initialPosition;
#else 
newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));
#endif
float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;
#ifdef LOCAL
outPosition=newPosition;
#else
outPosition=(emitterWM*vec4(newPosition,1.)).xyz;
#endif
#ifdef CUSTOMEMITTER
outDirection=direction;
#ifndef BILLBOARD 
outInitialDirection=direction;
#endif
#else
#ifdef LOCAL
vec3 initial=newDirection;
#else 
vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;
#endif
outDirection=initial*power;
#ifndef BILLBOARD 
outInitialDirection=initial;
#endif
#endif
#ifdef ANIMATESHEET 
outCellIndex=cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
outCellStartOffset=randoms.a*outLife;
#endif 
#endif
#ifdef NOISE
outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;
#endif
} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;
#ifdef VELOCITYGRADIENTS
directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;
#endif
#ifdef DRAGGRADIENTS
directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;
#endif
#if defined(CUSTOMEMITTER)
outPosition=position+(direction-position)*ageGradient; 
outInitialPosition=initialPosition;
#else
outPosition=position+direction*directionScale;
#endif
outLife=life;outSeed=seed;
#ifndef COLORGRADIENTS 
outColor=color;
#endif
#ifdef SIZEGRADIENTS
outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;
#else
outSize=size;
#endif 
#ifndef BILLBOARD 
outInitialDirection=initialDirection;
#endif
#ifdef CUSTOMEMITTER
outDirection=direction;
#else
vec3 updatedDirection=direction+gravity*timeDelta;
#ifdef LIMITVELOCITYGRADIENTS
float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}
#endif
outDirection=updatedDirection;
#ifdef NOISE
float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;
#endif 
#endif 
#ifdef ANGULARSPEEDGRADIENTS
float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;
#else
outAngle=vec2(angle.x+angle.y*timeDelta,angle.y);
#endif
#ifdef ANIMATESHEET 
float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;
#else
float cellStartOffset=0.;
#endif 
float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}
else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}
outCellIndex=float(int(cellInfos.x+ratio*dist));
#endif
}}`;W.ShadersStore[w1]=L1;class B1{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e;return((e=this._updateEffect)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof Xa&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new xt("gpuUpdateParticles",this._updateEffectOptions,this._engine),new EC(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO.length=0;for(let e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0}_createUpdateVAO(e){const t={};t.position=e.createVertexBuffer("position",0,3);let i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof Xa&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));const s=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),s}}V("BABYLON.WebGL2ParticleSystem",B1);const U1="gpuUpdateParticlesComputeShader",V1=`struct Particle {position : vec3<f32>,
age : f32,
size : vec3<f32>,
life : f32,
seed : vec4<f32>,
direction : vec3<f32>,
dummy0: f32,
#ifdef CUSTOMEMITTER
initialPosition : vec3<f32>,
dummy1: f32,
#endif
#ifndef COLORGRADIENTS
color : vec4<f32>,
#endif
#ifndef BILLBOARD
initialDirection : vec3<f32>,
dummy2: f32,
#endif
#ifdef NOISE
noiseCoordinates1 : vec3<f32>,
dummy3: f32,
noiseCoordinates2 : vec3<f32>,
dummy4: f32,
#endif
#ifdef ANGULARSPEEDGRADIENTS
angle : f32,
#else
angle : vec2<f32>,
#endif
#ifdef ANIMATESHEET
cellIndex : f32,
#ifdef ANIMATESHEETRANDOMSTART
cellStartOffset : f32,
#endif
#endif
};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32,
timeDelta : f32,
stopFactor : f32,
randomTextureSize: i32,
lifeTime : vec2<f32>,
emitPower : vec2<f32>,
#ifndef COLORGRADIENTS
color1 : vec4<f32>,
color2 : vec4<f32>,
#endif
sizeRange : vec2<f32>,
scaleRange : vec4<f32>,
angleRange : vec4<f32>,
gravity : vec3<f32>,
#ifdef LIMITVELOCITYGRADIENTS
limitVelocityDamping : f32,
#endif
#ifdef ANIMATESHEET
cellInfos : vec4<f32>,
#endif
#ifdef NOISE
noiseStrength : vec3<f32>,
#endif
#ifndef LOCAL
emitterWM : mat4x4<f32>,
#endif
#ifdef BOXEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
minEmitBox : vec3<f32>,
maxEmitBox : vec3<f32>,
#endif
#ifdef CONEEMITTER
radius : vec2<f32>,
coneAngle : f32,
height : vec2<f32>,
directionRandomizer : f32,
#endif
#ifdef CYLINDEREMITTER
radius : f32,
height : f32,
radiusRange : f32,
#ifdef DIRECTEDCYLINDEREMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#else
directionRandomizer : f32,
#endif
#endif
#ifdef HEMISPHERICEMITTER
radius : f32,
radiusRange : f32,
directionRandomizer : f32,
#endif
#ifdef POINTEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#endif
#ifdef SPHEREEMITTER
radius : f32,
radiusRange : f32,
#ifdef DIRECTEDSPHEREEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#else
directionRandomizer : f32,
#endif
#endif
};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>;
#ifdef SIZEGRADIENTS
@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>;
#endif 
#ifdef ANGULARSPEEDGRADIENTS
@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>;
#endif 
#ifdef VELOCITYGRADIENTS
@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>;
#endif
#ifdef LIMITVELOCITYGRADIENTS
@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>;
#endif
#ifdef DRAGGRADIENTS
@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>;
#endif
#ifdef NOISE
@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>;
#endif
fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;}
fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;}
let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32;
#ifdef SIZEGRADIENTS 
sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r;
#else
sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;
#endif
particlesOut.particles[index].size=vec3<f32>(
sizex,
params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,
params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);
#ifndef COLORGRADIENTS
particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;
#endif
#ifndef ANGULARSPEEDGRADIENTS 
particlesOut.particles[index].angle=vec2<f32>(
params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,
params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);
#else
particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;
#endif 
#if defined(POINTEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;
#elif defined(BOXEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; 
#elif defined(HEMISPHERICEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3);
#elif defined(SPHEREEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ);
#ifdef DIRECTEDSPHEREEMITTER
newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);
#else
newDirection=normalize(newPosition+params.directionRandomizer*randoms3);
#endif
#elif defined(CYLINDEREMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos);
#ifdef DIRECTEDCYLINDEREMITTER
newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;
#else
angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection);
#endif
#elif defined(CONEEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x;
#ifdef CONEEMITTERSPAWNPOINT
let h : f32=0.0001;
#else
var h : f32=randoms2.y*params.height.y;h=1.-h*h; 
#endif
var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); 
if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); }
#elif defined(CUSTOMEMITTER)
newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition;
#else 
newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5));
#endif
let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;
#ifdef LOCAL
particlesOut.particles[index].position=newPosition;
#else
particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz;
#endif
#ifdef CUSTOMEMITTER
particlesOut.particles[index].direction=direction;
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=direction;
#endif
#else
#ifdef LOCAL
let initial : vec3<f32>=newDirection;
#else 
let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz;
#endif
particlesOut.particles[index].direction=initial*power;
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=initial;
#endif
#endif
#ifdef ANIMATESHEET 
particlesOut.particles[index].cellIndex=params.cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
particlesOut.particles[index].cellStartOffset=randoms.a*outLife;
#endif 
#endif
#ifdef NOISE
particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;
#endif
} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life;
#ifdef VELOCITYGRADIENTS
directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;
#endif
#ifdef DRAGGRADIENTS
directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r);
#endif
let position : vec3<f32>=particlesIn.particles[index].position;
#if defined(CUSTOMEMITTER)
particlesOut.particles[index].position=position+(direction-position)*ageGradient; 
particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;
#else
particlesOut.particles[index].position=position+direction*directionScale;
#endif
particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed;
#ifndef COLORGRADIENTS 
particlesOut.particles[index].color=particlesIn.particles[index].color;
#endif
#ifdef SIZEGRADIENTS
particlesOut.particles[index].size=vec3<f32>(
textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r,
particlesIn.particles[index].size.yz);
#else
particlesOut.particles[index].size=particlesIn.particles[index].size;
#endif 
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;
#endif
#ifdef CUSTOMEMITTER
particlesOut.particles[index].direction=direction;
#else
var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta;
#ifdef LIMITVELOCITYGRADIENTS
let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;}
#endif
particlesOut.particles[index].direction=updatedDirection;
#ifdef NOISE
let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;
#endif 
#endif 
#ifdef ANGULARSPEEDGRADIENTS
let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;
#else
let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y);
#endif
#ifdef ANIMATESHEET 
var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset;
#else
let cellStartOffset : f32=0.;
#endif 
var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);}
else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);}
particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));
#endif
}}
`;W.ShadersStoreWGSL[U1]=V1;class k1{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e;return((e=this._updateComputeShader)==null?void 0:e.isReady())??!1}createUpdateBuffer(e){var i;const t={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(t.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(t.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(t.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(t.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(t.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(t.noiseTexture={group:1,binding:11}),this._updateComputeShader=new za("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:t,defines:e.split(`
`)}),(i=this._simParamsComputeShader)==null||i.dispose(),this._simParamsComputeShader=new be(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new EC(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new Bb(this._engine,e.length*4,11,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[e^1]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let t=0;t<this._bufferComputeShader.length;++t)this._bufferComputeShader[t].dispose();this._bufferComputeShader.length=0,(e=this._simParamsComputeShader)==null||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null}releaseVertexBuffers(){this._renderVertexBuffers.length=0}}V("BABYLON.ComputeShaderParticleSystem",k1);class SC{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){if(!this.color2){e.copyFrom(this.color1);return}xe.LerpToRef(this.color1,this.color2,Math.random(),e)}}class G1{constructor(e,t){this.gradient=e,this.color=t}}class CC{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return this.factor2===void 0||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class mr{static GetCurrentGradient(e,t,i){if(t[0].gradient>e){i(t[0],t[0],1);return}for(let r=0;r<t.length-1;r++){const n=t[r],o=t[r+1];if(e>=n.gradient&&e<=o.gradient){const l=(e-n.gradient)/(o.gradient-n.gradient);i(n,o,l);return}}const s=t.length-1;i(t[s],t[s],1)}}class Lu{constructor(e){this.particleSystem=e,this.position=m.Zero(),this.direction=m.Zero(),this.color=new xe(0,0,0,0),this.colorStep=new xe(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Z(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new xe(0,0,0,0),this._currentColor2=new xe(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=Lu._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(this._randomCellOffset===void 0&&(this._randomCellOffset=Math.random()*this.lifeTime),t===0?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let s;this._initialSpriteCellLoop?s=xi(e*t%this.lifeTime/this.lifeTime):s=xi(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=U.Vector3[0];this.direction.normalizeToRef(i),t.setDirection(i,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,U.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(U.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Lu._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new we(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}Lu._Count=0;const z1="particlesPixelShader",W1=`#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;
#include<clipPlaneFragmentDeclaration>
#include<imageProcessingDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#ifdef RAMPGRADIENT
varying vec4 remapRanges;uniform sampler2D rampSampler;
#endif
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;
#ifdef RAMPGRADIENT
float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);
#endif
#ifdef BLENDMULTIPLYMODE
float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);
#endif
#include<logDepthFragment>
#include<fogFragment>(color,baseColor)
#ifdef IMAGEPROCESSINGPOSTPROCESS
baseColor.rgb=toLinearSpace(baseColor.rgb);
#else
#ifdef IMAGEPROCESSING
baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);
#endif
#endif
gl_FragColor=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[z1]=W1;const H1="particlesVertexShader",X1=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
#ifndef BILLBOARD
attribute vec3 direction;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
#ifdef RAMPGRADIENT
attribute vec4 remapData;
#endif
attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;
#ifdef ANIMATESHEET
uniform vec3 particlesInfos; 
#endif
varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;
#ifdef RAMPGRADIENT
varying vec4 remapRanges;
#endif
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
#ifdef BILLBOARDSTRETCHED_LOCAL
vec3 row1=direction;
#else
vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
#endif
mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;
#ifdef BILLBOARD
vec3 rotatedCorner;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#else
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;
#endif
#ifdef RAMPGRADIENT
remapRanges=remapData;
#endif
gl_Position=projection*vec4(viewPos,1.0);
#else
vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);
#endif
vColor=color;
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=offset;
#endif
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[H1]=X1;class gf extends as{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Bi(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new G),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=D.Identity(),this._inheritedVelocityOffset=new m,this.onDisposeObservable=new G,this.onStoppedObservable=new G,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new xe(0,0,0,0),this._colorDiff=new xe(0,0,0,0),this._scaledDirection=m.Zero(),this._scaledGravity=m.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=l=>{},this.recycleParticle=l=>{const h=this._particles.pop();h!==l&&h.copyTo(l),this._stockParticles.push(h)},this._createParticle=()=>{let l;return this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new Lu(this),this._prepareParticle(l),l},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,!i||i.getClassName()==="Scene"?(this._scene=i||Ae.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=D.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Bi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Ha;let o=null;this.updateFunction=l=>{var u;let h=null;this.noiseTexture&&(h=this.noiseTexture.getSize(),(u=this.noiseTexture.getContent())==null||u.then(d=>{o=d}));const c=l===this._particles;for(let d=0;d<l.length;d++){const f=l[d];let _=this._scaledUpdateSpeed;const p=f.age;if(f.age+=_,f.age>f.lifeTime){const T=f.age-p;_=(f.lifeTime-p)*_/T,f.age=f.lifeTime}const g=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?mr.GetCurrentGradient(g,this._colorGradients,(T,S,C)=>{T!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),S.getColorToRef(f._currentColor2),f._currentColorGradient=T),xe.LerpToRef(f._currentColor1,f._currentColor2,C,f.color)}):(f.colorStep.scaleToRef(_,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&mr.GetCurrentGradient(g,this._angularSpeedGradients,(T,S,C)=>{T!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=S.getFactor(),f._currentAngularSpeedGradient=T),f.angularSpeed=_r(f._currentAngularSpeed1,f._currentAngularSpeed2,C)}),f.angle+=f.angularSpeed*_;let x=_;if(this._velocityGradients&&this._velocityGradients.length>0&&mr.GetCurrentGradient(g,this._velocityGradients,(T,S,C)=>{T!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=S.getFactor(),f._currentVelocityGradient=T),x*=_r(f._currentVelocity1,f._currentVelocity2,C)}),f.direction.scaleToRef(x,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&mr.GetCurrentGradient(g,this._limitVelocityGradients,(T,S,C)=>{T!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=S.getFactor(),f._currentLimitVelocityGradient=T);const v=_r(f._currentLimitVelocity1,f._currentLimitVelocity2,C);f.direction.length()>v&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&mr.GetCurrentGradient(g,this._dragGradients,(T,S,C)=>{T!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=S.getFactor(),f._currentDragGradient=T);const v=_r(f._currentDrag1,f._currentDrag2,C);this._scaledDirection.scaleInPlace(1-v)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),m.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),o&&h&&f._randomNoiseCoordinates1){const T=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,h.width,h.height,o),S=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,h.width,h.height,o),C=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,h.width,h.height,o),v=U.Vector3[0],b=U.Vector3[1];v.copyFromFloats((2*T-1)*this.noiseStrength.x,(2*S-1)*this.noiseStrength.y,(2*C-1)*this.noiseStrength.z),v.scaleToRef(_,b),f.direction.addInPlace(b)}if(this.gravity.scaleToRef(_,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&mr.GetCurrentGradient(g,this._sizeGradients,(T,S,C)=>{T!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=S.getFactor(),f._currentSizeGradient=T),f.size=_r(f._currentSize1,f._currentSize2,C)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&mr.GetCurrentGradient(g,this._colorRemapGradients,(T,S,C)=>{const v=_r(T.factor1,S.factor1,C),b=_r(T.factor2,S.factor2,C);f.remapData.x=v,f.remapData.y=b-v}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&mr.GetCurrentGradient(g,this._alphaRemapGradients,(T,S,C)=>{const v=_r(T.factor1,S.factor1,C),b=_r(T.factor2,S.factor2,C);f.remapData.z=v,f.remapData.w=b-v})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(T=>{T.particleSystem.disposeOnStop=!0,T.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),c&&d--;continue}}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new CC(t,i,s);e.push(r),e.sort((n,o)=>n.gradient<o.gradient?-1:n.gradient>o.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(this._rawTextureWidth*4),t=gt.Color3[0];for(let i=0;i<this._rawTextureWidth;i++){const s=i/this._rawTextureWidth;mr.GetCurrentGradient(s,this._rampGradients,(r,n,o)=>{q.LerpToRef(r.color,n.color,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=255})}this._rampGradientsTexture=Fi.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new G1(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new SC(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort((r,n)=>r.gradient<n.gradient?-1:r.gradient>n.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t==null||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const n=e*i%i|0,o=t*s%s|0,l=(n+o*i)*4;return r[l]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Ji(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(y.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[y.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(y.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[y.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const h=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=h,i+=1}if(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9){const h=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=h,i+=3}if(this._useRampGradients){const h=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=h,i+=4}let l;if(this._useInstancing){const h=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ji(e,h,!1,2),l=this._spriteBuffer.createVertexBuffer("offset",0,2)}else l=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=l,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}const e=[],t=[];let i=0;for(let s=0;s<this._capacity;s++)e.push(i),e.push(i+1),e.push(i+2),e.push(i),e.push(i+2),e.push(i+3),t.push(i,i+1,i+1,i+2,i+2,i+3,i+3,i,i,i+3),i+=4;this._indexBuffer=this._engine.createIndexBuffer(e),this._linesIndexBuffer=this._engine.createIndexBuffer(t)}getCapacity(){return this._capacity}isAlive(){return this._alive}isStarted(){return this._started}_preStart(){}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){((t=this.emitter)==null?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);const i=this.noiseTexture;if(i&&i.onGeneratedObservable)i.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let s=0;s<this.preWarmCycles;s++)this.animate(!0),i.render()})});else for(let s=0;s<this.preWarmCycles;s++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===8||this.billboardMode===9)&&(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let n=t._initialDirection;this.isLocal&&(m.TransformNormalToRef(n,this._emitterWorldMatrix,U.Vector3[0]),n=U.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}else{let n=t.direction;this.isLocal&&(m.TransformNormalToRef(n,this._emitterWorldMatrix,U.Vector3[0]),n=U.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),s===0?s=this._epsilon:s===1&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const i=this.emitter;this._emitterWorldMatrix=i.getWorldMatrix()}else{const i=this.emitter;this._emitterWorldMatrix=D.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i<e&&this._particles.length!==this._capacity;i++){if(t=this._createParticle(),this._particles.push(t),this.targetStopDuration&&this._lifeTimeGradients&&this._lifeTimeGradients.length>0){const r=xi(this._actualFrame/this.targetStopDuration);mr.GetCurrentGradient(r,this._lifeTimeGradients,(n,o)=>{const l=n,h=o,c=l.getFactor(),u=h.getFactor(),d=(r-l.gradient)/(h.gradient-l.gradient);t.lifeTime=_r(c,u,d)})}else t.lifeTime=Pt(this.minLifeTime,this.maxLifeTime);const s=Pt(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),m.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),s===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(s),!this._sizeGradients||this._sizeGradients.length===0?t.size=Pt(this.minSize,this.maxSize):(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1),t.scale.copyFromFloats(Pt(this.minScaleX,this.maxScaleX),Pt(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;mr.GetCurrentGradient(r,this._startSizeGradients,(n,o,l)=>{n!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=n);const h=_r(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(h)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=Pt(this.minAngularSpeed,this.maxAngularSpeed):(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1),t.angle=Pt(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),!this._colorGradients||this._colorGradients.length===0){const r=Pt(0,1);xe.LerpToRef(this.color1,this.color2,r,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}else t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new we(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new m(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new m(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[y.PositionKind,y.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return sn(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t){if(this._scene&&(no(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==0&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===as.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===9&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...gf._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==8&&this.billboardMode!==9,this._useRampGradients)),e.push(...gf._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ME(e,this._imageProcessingConfigurationDefines),DE(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Bi(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join(`
`);if(n.defines!==o){const l=[],h=[],c=[];this.fillUniformsAttributesAndSamplerNames(h,l,c),n.setEffect(this._engine.createEffect("particles",l,h,c,o),o)}return n}animate(e=!1){var i;if(!this._started)return;if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:((i=this._scene)==null?void 0:i.getAnimationRatio())||1);let t;if(this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let s=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;mr.GetCurrentGradient(r,this._emitRateGradients,(n,o,l)=>{n!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=n),s=_r(this._currentEmitRate1,this._currentEmitRate2,l)})}t=s*this._scaledUpdateSpeed>>0,this._newPartsExcess+=s*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let s=0;for(let r=0;r<this._particles.length;r++){const n=this._particles[r];this._appendParticleVertices(s,n),s+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}this.manualEmitCount===0&&this.disposeOnStop&&this.stop()}_appendParticleVertices(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))}rebuild(){var e;this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),(e=this._spriteBuffer)==null||e._rebuild(),this._createVertexBuffers(),this.resetDrawCache()}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==as.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(as.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(as.BLENDMODE_ADD).effect.isReady())return!1;return!0}_render(e){var o,l,h,c,u,d;const t=this._getWrapper(e),i=t.effect,s=this._engine;s.enableEffect(t);const r=this.defaultViewMatrix??this._scene.getViewMatrix();if(i.setTexture("diffuseSampler",this.particleTexture),i.setMatrix("view",r),i.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){const f=this.particleTexture.getBaseSize();i.setFloat3("particlesInfos",this.spriteCellWidth/f.width,this.spriteCellHeight/f.height,this.spriteCellWidth/f.width)}if(i.setVector2("translationPivot",this.translationPivot),i.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){const f=this._scene.activeCamera;i.setVector3("eyePosition",f.globalPosition)}this._rampGradientsTexture&&((!this._rampGradients||!this._rampGradients.length)&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),i.setTexture("rampSampler",this._rampGradientsTexture));const n=i.defines;switch(this._scene&&(Gr(i,this,this._scene),this.applyFog&&Go(this._scene,void 0,i)),n.indexOf("#define BILLBOARDMODE_ALL")>=0&&(r.invertToRef(U.Matrix[0]),i.setMatrix("invView",U.Matrix[0])),this._vertexArrayObject!==void 0?(o=this._scene)!=null&&o.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,(h=this._scene)!=null&&h.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&ao(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case as.BLENDMODE_ADD:s.setAlphaMode(1);break;case as.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case as.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case as.BLENDMODE_MULTIPLY:s.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?(u=this._scene)!=null&&u.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):(d=this._scene)!=null&&d.forceWireframe?s.drawElementsType(1,0,this._particles.length*10):s.drawElementsType(0,0,this._particles.length*6),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return this.blendMode===as.BLENDMODE_MULTIPLYADD?t=this._render(as.BLENDMODE_MULTIPLY)+this._render(as.BLENDMODE_ADD):t=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const s=this._scene.particleSystems.indexOf(this);s>-1&&this._scene.particleSystems.splice(s,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var Bu;(function(a){a[a.ATTACHED=0]="ATTACHED",a[a.END=1]="END"})(Bu||(Bu={}));class Ya{constructor(e){if(this.particleSystem=e,this.type=Bu.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Si("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new m;else if(e instanceof m)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Si("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new Ya(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw Ge("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new Ya(Ya._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function vC(a,e){const t=new c_;return t.direction1=a,t.direction2=e,t}function bC(a=1,e=1){return new h_(a,e)}function AC(a=1,e=1){return new nd(a,e)}function yC(a=1,e=new m(0,1,0),t=new m(0,1,0)){return new u_(a,e,t)}function RC(a=1,e=1,t=1,i=0){return new rd(a,e,t,i)}function IC(a=1,e=1,t=1,i=new m(0,1,0),s=new m(0,1,0)){return new l_(a,e,t,i,s)}function PC(a=1,e=Math.PI/4){return new o_(a,e)}class ii extends gf{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||this._subEmitters.length===0)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(i=>{if(i.type===Bu.END){const s=i.clone();e._inheritParticleInfoToSubEmitter(s),s.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(s.particleSystem),s.particleSystem.start()}})}}createPointEmitter(e,t){const i=vC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=AC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new m(0,1,0),i=new m(0,1,0)){const s=yC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=RC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new m(0,1,0),r=new m(0,1,0)){const n=IC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=PC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new Ha;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof ii?this._subEmitters.push([new Ya(e)]):e instanceof Ya?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);e!==-1&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(i=>{if(i.type===Bu.ATTACHED){const s=i.clone();e._attachedSubEmitters.push(s),s.particleSystem.start()}})}}_onDispose(e=!1,t=!1){var i;if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&((i=this.particles)==null||i.forEach(s=>{if(s._attachedSubEmitters)for(let r=s._attachedSubEmitters.length-1;r>=0;r-=1)s._attachedSubEmitters[r].dispose()})),t&&this.activeSubSystems)for(let s=this.activeSubSystems.length-1;s>=0;s-=1)this.activeSubSystems[s].dispose();if(this._subEmitters&&this._subEmitters.length){for(let s=0;s<this._subEmitters.length;s++)for(const r of this._subEmitters[s])r.dispose();this._subEmitters=[],this.subEmitters=[]}this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0)}static _Parse(e,t,i,s){let r;i instanceof pe?r=null:r=i;const n=Si("BABYLON.Texture");if(n&&r&&(e.texture?t.particleTexture=n.Parse(e.texture,r,s):e.textureName&&(t.particleTexture=new n(s+e.textureName,r,!1,e.invertY!==void 0?e.invertY:!0),t.particleTexture.name=e.textureName)),!e.emitterId&&e.emitterId!==0&&e.emitter===void 0?t.emitter=m.Zero():e.emitterId&&r?t.emitter=r.getLastMeshById(e.emitterId):t.emitter=m.FromArray(e.emitter),t.isLocal=!!e.isLocal,e.renderingGroupId!==void 0&&(t.renderingGroupId=e.renderingGroupId),e.isBillboardBased!==void 0&&(t.isBillboardBased=e.isBillboardBased),e.billboardMode!==void 0&&(t.billboardMode=e.billboardMode),e.useLogarithmicDepth!==void 0&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let l=0;l<e.animations.length;l++){const h=e.animations[l],c=Si("BABYLON.Animation");c&&t.animations.push(c.Parse(h))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&r&&r.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=e.startDelay|0,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),e.preWarmCycles!==void 0&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),e.minInitialRotation!==void 0&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=m.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=m.FromArray(e.noiseStrength)),t.color1=xe.FromArray(e.color1),t.color2=xe.FromArray(e.color2),t.colorDead=xe.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(const l of e.colorGradients)t.addColorGradient(l.gradient,xe.FromArray(l.color1),l.color2?xe.FromArray(l.color2):void 0);if(e.rampGradients){for(const l of e.rampGradients)t.addRampGradient(l.gradient,q.FromArray(l.color));t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(const l of e.colorRemapGradients)t.addColorRemapGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.alphaRemapGradients)for(const l of e.alphaRemapGradients)t.addAlphaRemapGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.sizeGradients)for(const l of e.sizeGradients)t.addSizeGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.angularSpeedGradients)for(const l of e.angularSpeedGradients)t.addAngularSpeedGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.velocityGradients)for(const l of e.velocityGradients)t.addVelocityGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.dragGradients)for(const l of e.dragGradients)t.addDragGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.emitRateGradients)for(const l of e.emitRateGradients)t.addEmitRateGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.startSizeGradients)for(const l of e.startSizeGradients)t.addStartSizeGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.lifeTimeGradients)for(const l of e.lifeTimeGradients)t.addLifeTimeGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);if(e.limitVelocityGradients){for(const l of e.limitVelocityGradients)t.addLimitVelocityGradient(l.gradient,l.factor1!==void 0?l.factor1:l.factor,l.factor2);t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&r){const l=Si("BABYLON.ProceduralTexture");t.noiseTexture=l.Parse(e.noiseTexture,r,s)}let o;if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":o=new nd;break;case"SphereDirectedParticleEmitter":o=new u_;break;case"ConeEmitter":case"ConeParticleEmitter":o=new o_;break;case"CylinderParticleEmitter":o=new rd;break;case"CylinderDirectedParticleEmitter":o=new l_;break;case"HemisphericParticleEmitter":o=new h_;break;case"PointParticleEmitter":o=new c_;break;case"MeshParticleEmitter":o=new yg;break;case"CustomParticleEmitter":o=new Xa;break;case"BoxEmitter":case"BoxParticleEmitter":default:o=new Ha;break}o.parse(e.particleEmitterType,r)}else o=new Ha,o.parse(e,r);t.particleEmitterType=o,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=e.spriteCellLoop??!0,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=e.disposeOnStop??!1,t.manualEmitCount=e.manualEmitCount??-1}static Parse(e,t,i,s=!1,r){const n=e.name;let o=null,l=null,h,c;if(t instanceof pe?h=t:(c=t,h=c.getEngine()),e.customShader&&h.createEffectForParticles){l=e.customShader;const d=l.shaderOptions.defines.length>0?l.shaderOptions.defines.join(`
`):"";o=h.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const u=new ii(n,r||e.capacity,t,o,e.isAnimationSheetEnabled);if(u.customShader=l,u._rootUrl=i,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(const d of e.subEmitters){const f=[];for(const _ of d)f.push(Ya.Parse(_,t,i));u.subEmitters.push(f)}}return ii._Parse(e,u,t,i),e.textureMask&&(u.textureMask=xe.FromArray(e.textureMask)),e.worldOffset&&(u.worldOffset=m.FromArray(e.worldOffset)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!s&&!u.preventAutoStart&&u.start(),u}serialize(e=!1){const t={};if(ii._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const r of i)s.push(r.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const g=t.emitter;e.emitterId=g.id}else{const g=t.emitter;e.emitter=g.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,_e.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const g of s){const x={gradient:g.gradient,color1:g.color1.asArray()};g.color2?x.color2=g.color2.asArray():x.color2=g.color1.asArray(),e.colorGradients.push(x)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const g of r){const x={gradient:g.gradient,color:g.color.asArray()};e.rampGradients.push(x)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const g of n){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.colorRemapGradients.push(x)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const g of o){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.alphaRemapGradients.push(x)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const g of l){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.sizeGradients.push(x)}}const h=t.getAngularSpeedGradients();if(h){e.angularSpeedGradients=[];for(const g of h){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.angularSpeedGradients.push(x)}}const c=t.getVelocityGradients();if(c){e.velocityGradients=[];for(const g of c){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.velocityGradients.push(x)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const g of u){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.dragGradients.push(x)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const g of d){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.emitRateGradients.push(x)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const g of f){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.startSizeGradients.push(x)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const g of _){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.lifeTimeGradients.push(x)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const g of p){const x={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?x.factor2=g.factor2:x.factor2=g.factor1,e.limitVelocityGradients.push(x)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&this.customShader!=null){r=this.customShader;const h=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join(`
`):"",c=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,h);s[0]?s[0].effect=c:this.setCustomEffect(c,0)}const o=this.serialize(i),l=ii.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,this.preventAutoStart||l.start(),l}}ii.BILLBOARDMODE_Y=2;ii.BILLBOARDMODE_ALL=7;ii.BILLBOARDMODE_STRETCHED=8;ii.BILLBOARDMODE_STRETCHED_LOCAL=9;Ya._ParseParticleSystem=ii.Parse;const Y1="clipPlaneFragmentDeclaration2",$1=`#ifdef CLIPPLANE
in float fClipDistance;
#endif
#ifdef CLIPPLANE2
in float fClipDistance2;
#endif
#ifdef CLIPPLANE3
in float fClipDistance3;
#endif
#ifdef CLIPPLANE4
in float fClipDistance4;
#endif
#ifdef CLIPPLANE5
in float fClipDistance5;
#endif
#ifdef CLIPPLANE6
in float fClipDistance6;
#endif
`;W.IncludesShadersStore[Y1]=$1;const K1="gpuRenderParticlesPixelShader",j1=`precision highp float;
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;
#include<clipPlaneFragmentDeclaration2> 
#include<imageProcessingDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#include<fogFragmentDeclaration>
void main() {
#include<clipPlaneFragment> 
vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;
#ifdef BLENDMULTIPLYMODE
float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);
#endif 
#include<logDepthFragment>
#include<fogFragment>(color,gl_FragColor)
#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
#else
#ifdef IMAGEPROCESSING
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);
#endif
#endif
}
`;W.ShadersStore[K1]=j1;const q1="clipPlaneVertexDeclaration2",Q1=`#ifdef CLIPPLANE
uniform vec4 vClipPlane;out float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;out float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;out float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;out float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;out float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;out float fClipDistance6;
#endif
`;W.IncludesShadersStore[q1]=Q1;const Z1="gpuRenderParticlesVertexShader",J1=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;
#ifdef LOCAL
uniform mat4 emitterWM;
#endif
attribute vec3 position;attribute float age;attribute float life;attribute vec3 size;
#ifndef BILLBOARD
attribute vec3 initialDirection;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
attribute float angle;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration2>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#ifdef COLORGRADIENTS
uniform sampler2D colorGradientSampler;
#else
uniform vec4 colorDead;attribute vec4 color;
#endif
#ifdef ANIMATESHEET
uniform vec3 sheetInfos;
#endif
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#endif
void main() {
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=uv;
#endif
float ratio=age/life;
#ifdef COLORGRADIENTS
vColor=texture2D(colorGradientSampler,vec2(ratio,0));
#else
vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);
#endif
vec2 cornerPos=(offset-translationPivot)*size.yz*size.x;
#ifdef BILLBOARD
vec4 rotatedCorner;rotatedCorner.w=0.;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));
#else
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;
#ifdef LOCAL
vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;
#else
vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;
#endif
vPositionW=(invView*viewPosition).xyz;
#endif
#else
vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);
#endif
gl_Position=projection*viewPosition;
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}`;W.ShadersStore[Z1]=J1;class El extends as{static get IsSupported(){if(!Ae.LastCreatedEngine)return!1;const e=Ae.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=vC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=AC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new m(0,1,0),i=new m(0,1,0)){const s=yC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=RC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new m(0,1,0),r=new m(0,1,0)){const n=IC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=PC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new Ha;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==ii.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(ii.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(ii.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t;return((t=this._customWrappers[e])==null?void 0:t.effect)??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Bi(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new G),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[this._targetIndex^1]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new SC(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((t,i)=>t.gradient<i.gradient?-1:t.gradient>i.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(const t in this._drawWrappers)(e=this._drawWrappers[t].drawContext)==null||e.reset()}_addFactorGradient(e,t,i){const s=new CC(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort((r,n)=>r.gradient<n.gradient?-1:r.gradient>n.gradient?1:0);const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new G,this.onStoppedObservable=new G,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||Ae.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=D.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Si("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Si("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Si("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Si("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Bi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Bi(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),t=t??{},t.randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new Ha;const l=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let h=[];for(let c=0;c<l;++c)h.push(Math.random()),h.push(Math.random()),h.push(Math.random()),h.push(Math.random());this._randomTexture=new Fi(new Float32Array(h),l,1,5,i,!1,!1,1,1),this._randomTexture.name="GPUParticleSystem_random1",this._randomTexture.wrapU=1,this._randomTexture.wrapV=1,h=[];for(let c=0;c<l;++c)h.push(Math.random()),h.push(Math.random()),h.push(Math.random()),h.push(Math.random());this._randomTexture2=new Fi(new Float32Array(h),l,1,5,i,!1,!1,1,1),this._randomTexture2.name="GPUParticleSystem_random2",this._randomTexture2.wrapU=1,this._randomTexture2.wrapV=1,this._randomTextureSize=l}_reset(){this._releaseBuffers()}_createVertexBuffers(e,t,i){const s={};s.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);let r=3;s.age=t.createVertexBuffer("age",r,1,this._attributesStrideSize,!0),r+=1,s.size=t.createVertexBuffer("size",r,3,this._attributesStrideSize,!0),r+=3,s.life=t.createVertexBuffer("life",r,1,this._attributesStrideSize,!0),r+=1,r+=4,this.billboardMode===ii.BILLBOARDMODE_STRETCHED&&(s.direction=t.createVertexBuffer("direction",r,3,this._attributesStrideSize,!0)),r+=3,this._platform.alignDataInBuffer&&(r+=1),this.particleEmitterType instanceof Xa&&(r+=3,this._platform.alignDataInBuffer&&(r+=1)),this._colorGradientsTexture||(s.color=t.createVertexBuffer("color",r,4,this._attributesStrideSize,!0),r+=4),this._isBillboardBased||(s.initialDirection=t.createVertexBuffer("initialDirection",r,3,this._attributesStrideSize,!0),r+=3,this._platform.alignDataInBuffer&&(r+=1)),this.noiseTexture&&(s.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",r,3,this._attributesStrideSize,!0),r+=3,this._platform.alignDataInBuffer&&(r+=1),s.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",r,3,this._attributesStrideSize,!0),r+=3,this._platform.alignDataInBuffer&&(r+=1)),s.angle=t.createVertexBuffer("angle",r,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?r++:r+=2,this._isAnimationSheetEnabled&&(s.cellIndex=t.createVertexBuffer("cellIndex",r,1,this._attributesStrideSize,!0),r+=1,this.spriteRandomStartCell&&(s.cellStartOffset=t.createVertexBuffer("cellStartOffset",r,1,this._attributesStrideSize,!0),r+=1)),s.offset=i.createVertexBuffer("offset",0,2),s.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(s),this._platform.createVertexBuffers(e,s),this.resetDrawCache()}_initialize(e=!1){if(this._buffer0&&!e)return;const t=this._engine,i=[];this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof Xa&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this.isBillboardBased||(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));const s=this.particleEmitterType instanceof Xa,r=U.Vector3[0];let n=0;for(let c=0;c<this._capacity;c++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),s?(this.particleEmitterType.particleDestinationGenerator(c,null,r),i.push(r.x),i.push(r.y),i.push(r.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),n+=16,s&&(this.particleEmitterType.particlePositionGenerator(c,null,r),i.push(r.x),i.push(r.y),i.push(r.z),this._platform.alignDataInBuffer&&i.push(0),n+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),n+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),n+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),n+=8),i.push(0),n+=1,this._angularSpeedGradientsTexture||(i.push(0),n+=1),this._isAnimationSheetEnabled&&(i.push(0),n+=1,this.spriteRandomStartCell&&(i.push(0),n+=1)),this._platform.alignDataInBuffer){let u=3-(n+3&3);for(n+=u;u-- >0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),l=this._platform.createParticleBuffer(i),h=this._platform.createParticleBuffer(i);this._buffer0=new Ji(t,l,!1,this._attributesStrideSize),this._buffer1=new Ji(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new Ji(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+=`
#define BILLBOARD`),this._colorGradientsTexture&&(e+=`
#define COLORGRADIENTS`),this._sizeGradientsTexture&&(e+=`
#define SIZEGRADIENTS`),this._angularSpeedGradientsTexture&&(e+=`
#define ANGULARSPEEDGRADIENTS`),this._velocityGradientsTexture&&(e+=`
#define VELOCITYGRADIENTS`),this._limitVelocityGradientsTexture&&(e+=`
#define LIMITVELOCITYGRADIENTS`),this._dragGradientsTexture&&(e+=`
#define DRAGGRADIENTS`),this.isAnimationSheetEnabled&&(e+=`
#define ANIMATESHEET`,this.spriteRandomStartCell&&(e+=`
#define ANIMATESHEETRANDOMSTART`)),this.noiseTexture&&(e+=`
#define NOISE`),this.isLocal&&(e+=`
#define LOCAL`),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e?this._platform.isUpdateBufferReady():(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new Bi(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join(`
`);if(s.defines!==r){const n=[],o=[],l=[];this.fillUniformsAttributesAndSamplerNames(o,n,l),s.setEffect(this._engine.createEffect("gpuRenderParticles",n,o,l,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[y.PositionKind,"age","life","size","angle"];return e||r.push(y.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",y.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return sn(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0){if(this._scene&&(no(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==Ee.FOGMODE_NONE&&e.push("#define FOG")),t===ii.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case ii.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case ii.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case ii.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...El._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===ii.BILLBOARDMODE_STRETCHED)),e.push(...El._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(lt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),lt.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)==null?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let r=0;r<this._rawTextureWidth;r++){const n=r/this._rawTextureWidth;mr.GetCurrentGradient(n,e,(o,l,h)=>{s[r]=ge.Lerp(o.factor1,l.factor1,h)})}this[t]=Fi.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(this._rawTextureWidth*4),t=gt.Color4[0];for(let i=0;i<this._rawTextureWidth;i++){const s=i/this._rawTextureWidth;mr.GetCurrentGradient(s,this._colorGradients,(r,n,o)=>{xe.LerpToRef(r.color1,n.color1,o,t),e[i*4]=t.r*255,e[i*4+1]=t.g*255,e[i*4+2]=t.b*255,e[i*4+3]=t.a*255})}this._colorGradientsTexture=Fi.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var o,l,h,c;const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=((o=this._scene)==null?void 0:o.getViewMatrix())||D.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const u=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/u.width,this.spriteCellHeight/u.height,u.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const u=this._scene.activeCamera;s.setVector3("eyePosition",u.globalPosition)}const n=s.defines;if(this._scene&&(Gr(s,this,this._scene),this.applyFog&&Go(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const u=r.clone();u.invert(),s.setMatrix("invView",u)}switch(this.useLogarithmicDepth&&this._scene&&ao(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case ii.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case ii.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case ii.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case ii.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,s,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),(h=this._scene)!=null&&h.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(c=this._scene)!=null&&c.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=U.Matrix[0],D.TranslationToRef(i.x,i.y,i.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,this._targetIndex===2&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let n=0;n<this.preWarmCycles;n++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){const n=this._accumulatedCount|0;this._accumulatedCount-=n,this._currentActiveCount+=n}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const n=this.emitter;i=U.Matrix[0],D.TranslationToRef(n.x,n.y,n.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return!e&&!t&&(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),this.blendMode===ii.BLENDMODE_MULTIPLYADD?r=this._render(ii.BLENDMODE_MULTIPLY,i)+this._render(ii.BLENDMODE_ADD,i):r=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{!this._recreateUpdateEffect()||!this._platform.isUpdateBufferReady()?setTimeout(e,10):(this._initialize(!0),this._rebuildingAfterContextLost=!1)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const t in this._drawWrappers)this._drawWrappers[t].dispose();if(this._drawWrappers={},this._scene){const t=this._scene.particleSystems.indexOf(this);t>-1&&this._scene.particleSystems.splice(t,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let t=0;t<this._renderVertexBuffers.length;++t){const i=this._renderVertexBuffers[t];for(const s in i)i[s].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&this.customShader!=null){r=this.customShader;const h=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join(`
`):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,h,void 0,void 0,void 0,this)}const o=this.serialize(i),l=El.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,l}serialize(e=!1){const t={};return ii._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,l;t instanceof pe?o=t:(l=t,o=l.getEngine());const h=new El(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(h._rootUrl=i,e.customShader&&o.createEffectForParticles){const c=e.customShader,u=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join(`
`):"",d=o.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,u,void 0,void 0,void 0,h);h.setCustomEffect(d,0),h.customShader=c}return e.id&&(h.id=e.id),e.activeParticleCount&&(h.activeParticleCount=e.activeParticleCount),ii._Parse(e,h,t,i),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),!s&&!h.preventAutoStart&&h.start(),h}}wi.AddParser(he.NAME_PARTICLESYSTEM,(a,e,t,i)=>{const s=wi.GetIndividualParser(he.NAME_PARTICLESYSTEM);if(s&&a.particleSystems!==void 0&&a.particleSystems!==null)for(let r=0,n=a.particleSystems.length;r<n;r++){const o=a.particleSystems[r];t.particleSystems.push(s(o,e,i))}});wi.AddIndividualParser(he.NAME_PARTICLESYSTEM,(a,e,t)=>a.activeParticleCount?El.Parse(a,e,t):ii.Parse(a,e,t));H.prototype.createEffectForParticles=function(a,e=[],t=[],i="",s,r,n,o){let l=[],h=[];const c=[];return o?o.fillUniformsAttributesAndSamplerNames(h,l,c):(l=ii._GetAttributeNamesOrOptions(),h=ii._GetEffectCreationOptions()),i.indexOf(" BILLBOARD")===-1&&(i+=`
#define BILLBOARD
`),o!=null&&o.isAnimationSheetEnabled&&i.indexOf(" ANIMATESHEET")===-1&&(i+=`
#define ANIMATESHEET
`),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(o==null?void 0:o.vertexShaderName)??"particles",fragmentElement:a},l,h.concat(e),c.concat(t),i,s,r,n)};z.prototype.getEmittedParticleSystems=function(){const a=[];for(let e=0;e<this.getScene().particleSystems.length;e++){const t=this.getScene().particleSystems[e];t.emitter===this&&a.push(t)}return a};z.prototype.getHierarchyEmittedParticleSystems=function(){const a=[],e=this.getDescendants();e.push(this);for(let t=0;t<this.getScene().particleSystems.length;t++){const i=this.getScene().particleSystems[t],s=i.emitter;s.position&&e.indexOf(s)!==-1&&a.push(i)}return a};class eL{constructor(e,t,i,s,r){this.idx=0,this.color=new xe(1,1,1,1),this.position=m.Zero(),this.rotation=m.Zero(),this.uv=new Z(0,0),this.velocity=m.Zero(),this.pivot=m.Zero(),this.translateFromPivot=!1,this._pos=0,this._ind=0,this.groupId=0,this.idxInGroup=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=m.Zero(),this.idx=e,this._group=t,this.groupId=i,this.idxInGroup=s,this._pcs=r}get size(){return this.size}set size(e){this.size=e}get quaternion(){return this.rotationQuaternion}set quaternion(e){this.rotationQuaternion=e}intersectsMesh(e,t){if(!e.hasBoundingInfo)return!1;if(!this._pcs.mesh)throw new Error("Point Cloud System doesnt contain the Mesh");if(t)return e.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));const i=e.getBoundingInfo().boundingBox,s=i.maximumWorld.x,r=i.minimumWorld.x,n=i.maximumWorld.y,o=i.minimumWorld.y,l=i.maximumWorld.z,h=i.minimumWorld.z,c=this.position.x+this._pcs.mesh.position.x,u=this.position.y+this._pcs.mesh.position.y,d=this.position.z+this._pcs.mesh.position.z;return r<=c&&c<=s&&o<=u&&u<=n&&h<=d&&d<=l}getRotationMatrix(e){let t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=U.Quaternion[0];const i=this.rotation;Q.RotationYawPitchRollToRef(i.y,i.x,i.z,t)}t.toRotationMatrix(e)}}class X_{get groupID(){return this.groupId}set groupID(e){this.groupId=e}constructor(e,t){this.groupId=e,this._positionFunction=t}}var Hs;(function(a){a[a.Color=2]="Color",a[a.UV=1]="UV",a[a.Random=0]="Random",a[a.Stated=3]="Stated"})(Hs||(Hs={}));class tL{get positions(){return this._positions32}get colors(){return this._colors32}get uvs(){return this._uvs32}constructor(e,t,i,s){this.particles=new Array,this.nbParticles=0,this.counter=0,this.vars={},this._promises=[],this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._updatable=!0,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._groups=new Array,this._groupCounter=0,this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeBoundingBox=!1,this._isReady=!1,this.name=e,this._size=t,this._scene=i||Ae.LastCreatedScene,s&&s.updatable!==void 0?this._updatable=s.updatable:this._updatable=!0}buildMeshAsync(e){return Promise.all(this._promises).then(()=>(this._isReady=!0,this._buildMesh(e)))}_buildMesh(e){this.nbParticles===0&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new le;t.set(this._positions32,y.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,y.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,y.ColorKind));const s=new z(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new de("point cloud material",this._scene),r.emissiveColor=new q(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise(n=>n(s))}_addParticle(e,t,i,s){const r=new eL(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new m(Math.random(),Math.random(),Math.random()),e.color=new xe(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(s*4)+t*4,o=[n,n+1,n+2,n+3],l=o[0],h=o[1],c=o[2],u=o[3],d=r[l],f=r[h],_=r[c],p=r[u];return new xe(d/255,f/255,_/255,p)}_setPointsColorOrUV(e,t,i,s,r,n,o,l){l=l??0,i&&e.updateFacetData();const c=2*e.getBoundingInfo().boundingSphere.radius;let u=e.getVerticesData(y.PositionKind);const d=e.getIndices(),f=e.getVerticesData(y.UVKind+(l?l+1:"")),_=e.getVerticesData(y.ColorKind),p=m.Zero();e.computeWorldMatrix();const g=e.getWorldMatrix();if(!g.isIdentity()){u=u.slice(0);for(let ks=0;ks<u.length/3;ks++)m.TransformCoordinatesFromFloatsToRef(u[3*ks],u[3*ks+1],u[3*ks+2],g,p),u[3*ks]=p.x,u[3*ks+1]=p.y,u[3*ks+2]=p.z}let x=0,T=0,S=0,C=0,v=0,b=0,A=0,P=0,L=0,w=0,$=0,J=0,ne=0;const oe=m.Zero(),re=m.Zero(),ce=m.Zero(),Se=m.Zero(),Ce=m.Zero();let ae=0,ie=0,F=0,j=0,se=0,Ie=0;const Ye=Z.Zero(),$e=Z.Zero(),fe=Z.Zero(),me=Z.Zero(),Xe=Z.Zero();let Fe=0,ke=0,Ue=0,Rt=0,hi=0,_i=0,pi=0,er=0,Os=0,Ca=0,va=0,po=0;const yn=we.Zero(),Vc=we.Zero(),Qo=we.Zero(),Zo=we.Zero(),Jo=we.Zero();let nn=0,Rn=0;o=o||0;let Qn,mo,Jt=new we(0,0,0,0),el=m.Zero(),tl=m.Zero(),In=m.Zero(),an=0,fr=m.Zero(),ba=0,Gg=0;const Ed=new tt(m.Zero(),new m(1,0,0));let C_,Sd=m.Zero();for(let ks=0;ks<d.length/3;ks++){T=d[3*ks],S=d[3*ks+1],C=d[3*ks+2],v=u[3*T],b=u[3*T+1],A=u[3*T+2],P=u[3*S],L=u[3*S+1],w=u[3*S+2],$=u[3*C],J=u[3*C+1],ne=u[3*C+2],oe.set(v,b,A),re.set(P,L,w),ce.set($,J,ne),re.subtractToRef(oe,Se),ce.subtractToRef(re,Ce),f&&(ae=f[2*T],ie=f[2*T+1],F=f[2*S],j=f[2*S+1],se=f[2*C],Ie=f[2*C+1],Ye.set(ae,ie),$e.set(F,j),fe.set(se,Ie),$e.subtractToRef(Ye,me),fe.subtractToRef($e,Xe)),_&&s&&(Fe=_[4*T],ke=_[4*T+1],Ue=_[4*T+2],Rt=_[4*T+3],hi=_[4*S],_i=_[4*S+1],pi=_[4*S+2],er=_[4*S+3],Os=_[4*C],Ca=_[4*C+1],va=_[4*C+2],po=_[4*C+3],yn.set(Fe,ke,Ue,Rt),Vc.set(hi,_i,pi,er),Qo.set(Os,Ca,va,po),Vc.subtractToRef(yn,Zo),Qo.subtractToRef(Vc,Jo));let v_,zg,Wg,Hg,Xg,il,sl,Cd;const Yg=new q(0,0,0),vd=new q(0,0,0);let rl,Kr;for(let b_=0;b_<t._groupDensity[ks];b_++)x=this.particles.length,this._addParticle(x,t,this._groupCounter,ks+b_),Kr=this.particles[x],nn=Math.sqrt(ge.RandomRange(0,1)),Rn=ge.RandomRange(0,1),Qn=oe.add(Se.scale(nn)).add(Ce.scale(nn*Rn)),i&&(el=e.getFacetNormal(ks).normalize().scale(-1),tl=Se.clone().normalize(),In=m.Cross(el,tl),an=ge.RandomRange(0,2*Math.PI),fr=tl.scale(Math.cos(an)).add(In.scale(Math.sin(an))),an=ge.RandomRange(.1,Math.PI/2),Sd=fr.scale(Math.cos(an)).add(el.scale(Math.sin(an))),Ed.origin=Qn.add(Sd.scale(1e-5)),Ed.direction=Sd,Ed.length=c,C_=Ed.intersectsMesh(e),C_.hit&&(Gg=C_.pickedPoint.subtract(Qn).length(),ba=ge.RandomRange(0,1)*Gg,Qn.addInPlace(Sd.scale(ba)))),Kr.position=Qn.clone(),this._positions.push(Kr.position.x,Kr.position.y,Kr.position.z),s!==void 0?f&&(mo=Ye.add(me.scale(nn)).add(Xe.scale(nn*Rn)),s?r&&t._groupImageData!==null?(v_=t._groupImgWidth,zg=t._groupImgHeight,rl=this._getColorIndicesForCoord(t,Math.round(mo.x*v_),Math.round(mo.y*zg),v_),Kr.color=rl,this._colors.push(rl.r,rl.g,rl.b,rl.a)):_?(Jt=yn.add(Zo.scale(nn)).add(Jo.scale(nn*Rn)),Kr.color=new xe(Jt.x,Jt.y,Jt.z,Jt.w),this._colors.push(Jt.x,Jt.y,Jt.z,Jt.w)):(Jt=yn.set(Math.random(),Math.random(),Math.random(),1),Kr.color=new xe(Jt.x,Jt.y,Jt.z,Jt.w),this._colors.push(Jt.x,Jt.y,Jt.z,Jt.w)):(Kr.uv=mo.clone(),this._uvs.push(Kr.uv.x,Kr.uv.y))):(n?(Yg.set(n.r,n.g,n.b),Wg=ge.RandomRange(-o,o),Hg=ge.RandomRange(-o,o),Cd=Yg.toHSV(),Xg=Cd.r,il=Cd.g+Wg,sl=Cd.b+Hg,il<0&&(il=0),il>1&&(il=1),sl<0&&(sl=0),sl>1&&(sl=1),q.HSVtoRGBToRef(Xg,il,sl,vd),Jt.set(vd.r,vd.g,vd.b,1)):Jt=yn.set(Math.random(),Math.random(),Math.random(),1),Kr.color=new xe(Jt.x,Jt.y,Jt.z,Jt.w),this._colors.push(Jt.x,Jt.y,Jt.z,Jt.w))}}_colorFromTexture(e,t,i){if(e.material===null){O.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const r=e.material.getActiveTextures();if(r.length===0){O.Warn(e.name+"has no usable texture."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const n=e.clone();n.setEnabled(!1),this._promises.push(new Promise(o=>{Et.WhenAllReady(r,()=>{let l=t._textureNb;l<0&&(l=0),l>r.length-1&&(l=r.length-1);const h=()=>{t._groupImgWidth=r[l].getSize().width,t._groupImgHeight=r[l].getSize().height,this._setPointsColorOrUV(n,t,i,!0,!0,void 0,void 0,r[l].coordinatesIndex),n.dispose(),o()};t._groupImageData=null;const c=r[l].readPixels();c?c.then(u=>{t._groupImageData=u,h()}):h()})}))}_calculateDensity(e,t,i){let s,r,n,o,l,h,c,u,d,f,_,p;const g=m.Zero(),x=m.Zero(),T=m.Zero(),S=m.Zero(),C=m.Zero(),v=m.Zero();let b;const A=[];let P=0;const L=i.length/3;for(let J=0;J<L;J++)s=i[3*J],r=i[3*J+1],n=i[3*J+2],o=t[3*s],l=t[3*s+1],h=t[3*s+2],c=t[3*r],u=t[3*r+1],d=t[3*r+2],f=t[3*n],_=t[3*n+1],p=t[3*n+2],g.set(o,l,h),x.set(c,u,d),T.set(f,_,p),x.subtractToRef(g,S),T.subtractToRef(x,C),m.CrossToRef(S,C,v),b=.5*v.length(),P+=b,A[J]=P;const w=new Array(L);let $=e;for(let J=L-1;J>0;J--){const ne=A[J];if(ne===0)w[J]=0;else{const re=(ne-A[J-1])/ne*$,ce=Math.floor(re),Se=re-ce,Ce=+(Math.random()<Se),ae=ce+Ce;w[J]=ae,$-=ae}}return w[0]=$,w}addPoints(e,t=this._randomUnitVector){const i=new X_(this._groupCounter,t);let s,r=this.nbParticles;for(let n=0;n<e;n++)s=this._addParticle(r,i,this._groupCounter,n),i&&i._positionFunction&&i._positionFunction(s,r,n),this._positions.push(s.position.x,s.position.y,s.position.z),s.color&&this._colors.push(s.color.r,s.color.g,s.color.b,s.color.a),s.uv&&this._uvs.push(s.uv.x,s.uv.y),r++;return this.nbParticles+=e,this._groupCounter++,this._groupCounter}addSurfacePoints(e,t,i,s,r){let n=i||Hs.Random;(isNaN(n)||n<0||n>3)&&(n=Hs.Random);const o=e.getVerticesData(y.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const h=new X_(this._groupCounter,null);switch(h._groupDensity=this._calculateDensity(t,o,l),n===Hs.Color?h._textureNb=s||0:s=s||new xe(1,1,1,1),n){case Hs.Color:this._colorFromTexture(e,h,!1);break;case Hs.UV:this._setPointsColorOrUV(e,h,!1,!1,!1);break;case Hs.Random:this._setPointsColorOrUV(e,h,!1);break;case Hs.Stated:this._setPointsColorOrUV(e,h,!1,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||Hs.Random;(isNaN(n)||n<0||n>3)&&(n=Hs.Random);const o=e.getVerticesData(y.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const h=new X_(this._groupCounter,null);switch(h._groupDensity=this._calculateDensity(t,o,l),n===Hs.Color?h._textureNb=s||0:s=s||new xe(1,1,1,1),n){case Hs.Color:this._colorFromTexture(e,h,!0);break;case Hs.UV:this._setPointsColorOrUV(e,h,!0,!1,!1);break;case Hs.Random:this._setPointsColorOrUV(e,h,!0);break;case Hs.Stated:this._setPointsColorOrUV(e,h,!0,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var S,C;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=U.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,l=this._uvs32,h=U.Vector3,c=h[5].copyFromFloats(1,0,0),u=h[6].copyFromFloats(0,1,0),d=h[7].copyFromFloats(0,0,1),f=h[8].setAll(Number.MAX_VALUE),_=h[9].setAll(-Number.MAX_VALUE);D.IdentityToRef(s);let p=0;if((S=this.mesh)!=null&&S.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const v=(C=this.mesh)==null?void 0:C.getBoundingInfo();v&&(f.copyFrom(v.minimum),_.copyFrom(v.maximum))}p=0;let g=0,x=0,T=0;for(let v=e;v<=t;v++){const b=this.particles[v];p=b.idx,g=3*p,x=4*p,T=2*p,this.updateParticle(b);const A=b._rotationMatrix,P=b.position,L=b._globalPosition;if(this._computeParticleRotation&&b.getRotationMatrix(s),b.parentId!==null){const j=this.particles[b.parentId],se=j._rotationMatrix,Ie=j._globalPosition,Ye=P.x*se[1]+P.y*se[4]+P.z*se[7],$e=P.x*se[0]+P.y*se[3]+P.z*se[6],fe=P.x*se[2]+P.y*se[5]+P.z*se[8];if(L.x=Ie.x+$e,L.y=Ie.y+Ye,L.z=Ie.z+fe,this._computeParticleRotation){const me=s.m;A[0]=me[0]*se[0]+me[1]*se[3]+me[2]*se[6],A[1]=me[0]*se[1]+me[1]*se[4]+me[2]*se[7],A[2]=me[0]*se[2]+me[1]*se[5]+me[2]*se[8],A[3]=me[4]*se[0]+me[5]*se[3]+me[6]*se[6],A[4]=me[4]*se[1]+me[5]*se[4]+me[6]*se[7],A[5]=me[4]*se[2]+me[5]*se[5]+me[6]*se[8],A[6]=me[8]*se[0]+me[9]*se[3]+me[10]*se[6],A[7]=me[8]*se[1]+me[9]*se[4]+me[10]*se[7],A[8]=me[8]*se[2]+me[9]*se[5]+me[10]*se[8]}}else if(L.x=0,L.y=0,L.z=0,this._computeParticleRotation){const j=s.m;A[0]=j[0],A[1]=j[1],A[2]=j[2],A[3]=j[4],A[4]=j[5],A[5]=j[6],A[6]=j[8],A[7]=j[9],A[8]=j[10]}const $=h[11];b.translateFromPivot?$.setAll(0):$.copyFrom(b.pivot);const J=h[0];J.copyFrom(b.position);const ne=J.x-b.pivot.x,oe=J.y-b.pivot.y,re=J.z-b.pivot.z;let ce=ne*A[0]+oe*A[3]+re*A[6],Se=ne*A[1]+oe*A[4]+re*A[7],Ce=ne*A[2]+oe*A[5]+re*A[8];ce+=$.x,Se+=$.y,Ce+=$.z;const ae=o[g]=L.x+c.x*ce+u.x*Se+d.x*Ce,ie=o[g+1]=L.y+c.y*ce+u.y*Se+d.y*Ce,F=o[g+2]=L.z+c.z*ce+u.z*Se+d.z*Ce;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(ae,ie,F),_.maximizeInPlaceFromFloats(ae,ie,F)),this._computeParticleColor&&b.color){const j=b.color,se=this._colors32;se[x]=j.r,se[x+1]=j.g,se[x+2]=j.b,se[x+3]=j.a}if(this._computeParticleTexture&&b.uv){const j=b.uv,se=this._uvs32;se[T]=j.x,se[T+1]=j.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(y.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(y.UVKind,l,!1,!1),r.updateVerticesData(y.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(f,_,r._worldMatrix):r.buildBoundingInfo(f,_,r._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){var e;(e=this.mesh)==null||e.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){var e;return this._isVisibilityBoxLocked||(e=this.mesh)==null||e.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new m(-t,-t,-t),new m(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(ut.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(a){this._physicsImpostor!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});ut.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};ut.prototype.applyImpulse=function(a,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(a,e),this):this};ut.prototype.setPhysicsLinkWith=function(a,e,t,i){return!this.physicsImpostor||!a.physicsImpostor?this:(this.physicsImpostor.createJoint(a.physicsImpostor,Qt.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class Rg{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ge("")}constructor(e,t=Rg.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new m(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new t_;return this._physicsPlugin.raycast(e,t,s,i),s}}var vT;(function(a){a[a.FREE=0]="FREE",a[a.LIMITED=1]="LIMITED",a[a.LOCKED=2]="LOCKED"})(vT||(vT={}));var bT;(function(a){a[a.LINEAR_X=0]="LINEAR_X",a[a.LINEAR_Y=1]="LINEAR_Y",a[a.LINEAR_Z=2]="LINEAR_Z",a[a.ANGULAR_X=3]="ANGULAR_X",a[a.ANGULAR_Y=4]="ANGULAR_Y",a[a.ANGULAR_Z=5]="ANGULAR_Z",a[a.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(bT||(bT={}));var AT;(function(a){a[a.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",a[a.DISTANCE=2]="DISTANCE",a[a.HINGE=3]="HINGE",a[a.SLIDER=4]="SLIDER",a[a.LOCK=5]="LOCK",a[a.PRISMATIC=6]="PRISMATIC",a[a.SIX_DOF=7]="SIX_DOF"})(AT||(AT={}));var yT;(function(a){a[a.SPHERE=0]="SPHERE",a[a.CAPSULE=1]="CAPSULE",a[a.CYLINDER=2]="CYLINDER",a[a.BOX=3]="BOX",a[a.CONVEX_HULL=4]="CONVEX_HULL",a[a.CONTAINER=5]="CONTAINER",a[a.MESH=6]="MESH",a[a.HEIGHTFIELD=7]="HEIGHTFIELD"})(yT||(yT={}));var RT;(function(a){a[a.NONE=0]="NONE",a[a.VELOCITY=1]="VELOCITY",a[a.POSITION=2]="POSITION"})(RT||(RT={}));var IT;(function(a){a.COLLISION_STARTED="COLLISION_STARTED",a.COLLISION_CONTINUED="COLLISION_CONTINUED",a.COLLISION_FINISHED="COLLISION_FINISHED",a.TRIGGER_ENTERED="TRIGGER_ENTERED",a.TRIGGER_EXITED="TRIGGER_EXITED"})(IT||(IT={}));var PT;(function(a){a[a.STATIC=0]="STATIC",a[a.ANIMATED=1]="ANIMATED",a[a.DYNAMIC=2]="DYNAMIC"})(PT||(PT={}));var MT;(function(a){a[a.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",a[a.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",a[a.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"})(MT||(MT={}));var DT;(function(a){a[a.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",a[a.MINIMUM=1]="MINIMUM",a[a.MAXIMUM=2]="MAXIMUM",a[a.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",a[a.MULTIPLY=4]="MULTIPLY"})(DT||(DT={}));Ee.prototype.getPhysicsEngine=function(){return this._physicsEngine};Ee.prototype.enablePhysics=function(a=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(he.NAME_PHYSICSENGINE);t||(t=new iL(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new NS(a,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new Rg(a,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return O.Error(i.message),!1}};Ee.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};Ee.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};Ee.prototype.deleteCompoundImpostor=function(a){const e=a.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};Ee.prototype._advancePhysicsEngineStep=function(a){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=a;this._physicsTimeAccumulator>e;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=e;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(a/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class iL{constructor(e){this.name=he.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new G,this.scene.onAfterPhysicsObservable=new G,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?this.scene._physicsEngine.getTimeStep()*1e3:1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Ke.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(a){this._physicsBody!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});Ke.prototype.getPhysicsBody=function(){return this.physicsBody};Ke.prototype.applyImpulse=function(a,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(a,e),this};m.Zero();var OT;(function(a){a[a.Constant=0]="Constant",a[a.Linear=1]="Linear"})(OT||(OT={}));var NT;(function(a){a[a.Center=0]="Center",a[a.Perpendicular=1]="Perpendicular"})(NT||(NT={}));const sL="blackAndWhitePixelShader",rL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); 
vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;W.ShadersStore[sL]=rL;class d_ extends De{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}static _Parse(e,t,i,s){return _e.Parse(()=>new d_(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}E([I()],d_.prototype,"degree",void 0);V("BABYLON.BlackAndWhitePostProcess",d_);class St{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let i=0;i<t.length;i++)if(!t[i].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;const i=X.MakeArray(e||this._cameras);if(i)for(let s=0;s<i.length;s++){const r=i[s];if(!r)continue;const n=r.name;if(this._singleInstance?t=0:t=n,!this._postProcesses[t]){const o=this._getPostProcesses();o&&(this._postProcesses[t]=Array.isArray(o)?o:[o])}this._indicesForCamera[n]||(this._indicesForCamera[n]=[]),this._postProcesses[t].forEach(o=>{const l=r.attachPostProcess(o);this._indicesForCamera[n].push(l)}),this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=X.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name,n=this._postProcesses[this._singleInstance?0:r];n&&n.forEach(o=>{s.detachPostProcess(o)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=X.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name,n=this._singleInstance?0:r;for(let o=0;o<this._indicesForCamera[r].length;o++){const l=this._indicesForCamera[r][o],h=s._postProcesses[l];h==null&&t[i].attachPostProcess(this._postProcesses[n][o],l)}}}_disable(e){const t=X.MakeArray(e||this._cameras);if(t)for(let i=0;i<t.length;i++){const s=t[i],r=s.name;this._postProcesses[this._singleInstance?0:r].forEach(n=>{s.detachPostProcess(n)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const nL="extractHighlightsPixelShader",aL=`#include<helperFunctions>
varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;W.ShadersStore[nL]=aL;class Ig extends De{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,l),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(h=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&h.setTextureFromPostProcess("textureSampler",this._inputPostProcess),h.setFloat("threshold",Math.pow(this.threshold,Kc)),h.setFloat("exposure",this._exposure)})}}E([I()],Ig.prototype,"threshold",void 0);V("BABYLON.ExtractHighlightsPostProcess",Ig);const oL="bloomMergePixelShader",lL=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }
`;W.ShadersStore[oL]=lL;class Pg extends De{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,l,h,c=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,l,h,null,c,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("bloomBlur",i),d.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}E([I()],Pg.prototype,"weight",void 0);V("BABYLON.BloomMergePostProcess",Pg);class FT extends St{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new Ig("highlights",1,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new ts("horizontal blur",new Z(1,0),10,t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new ts("vertical blur",new Z(0,1),10,t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new Pg("bloomMerge",this._downscale,this._blurY,i,t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}const hL="chromaticAberrationPixelShader",cL=`uniform sampler2D textureSampler; 
uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}
float radius2=centered_screen_pos.x*centered_screen_pos.x
+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}`;W.ShadersStore[hL]=cL;class jn extends De{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,s,r,n,o,l,h=0,c=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],s,r,n,o,l,null,h,void 0,null,c),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new Z(.707,.707),this.centerPosition=new Z(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add(u=>{u.setFloat("chromatic_aberration",this.aberrationAmount),u.setFloat("screen_width",t),u.setFloat("screen_height",i),u.setFloat("radialIntensity",this.radialIntensity),u.setFloat2("direction",this.direction.x,this.direction.y),u.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,s){return _e.Parse(()=>new jn(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}E([I()],jn.prototype,"aberrationAmount",void 0);E([I()],jn.prototype,"radialIntensity",void 0);E([I()],jn.prototype,"direction",void 0);E([I()],jn.prototype,"centerPosition",void 0);E([I()],jn.prototype,"screenWidth",void 0);E([I()],jn.prototype,"screenHeight",void 0);V("BABYLON.ChromaticAberrationPostProcess",jn);const uL="circleOfConfusionPixelShader",dL=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float depth=texture2D(depthSampler,vUV).r;
#define CUSTOM_COC_DEPTH
float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; 
#define CUSTOM_COC_PIXELDISTANCE
float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}
`;W.ShadersStore[uL]=dL;class Nc extends De{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,l=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,l,void 0,null,h),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(c=>{if(!this._depthTexture){O.Warn("No depth texture set on CircleOfConfusionPostProcess");return}c.setTexture("depthSampler",this._depthTexture);const d=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);c.setFloat("focusDistance",this.focusDistance),c.setFloat("cocPrecalculation",d);const f=this._depthTexture.activeCamera;c.setFloat2("cameraMinMaxZ",f.minZ,f.maxZ-f.minZ)})}set depthTexture(e){this._depthTexture=e}}E([I()],Nc.prototype,"lensSize",void 0);E([I()],Nc.prototype,"fStop",void 0);E([I()],Nc.prototype,"focusDistance",void 0);E([I()],Nc.prototype,"focalLength",void 0);V("BABYLON.CircleOfConfusionPostProcess",Nc);const fL="colorCorrectionPixelShader",_L=`uniform sampler2D textureSampler; 
uniform sampler2D colorTable; 
varying vec2 vUV;const float SLICE_COUNT=16.0; 
vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; 
float slicePixelSize=sliceSize/width; 
float sliceInnerSize=slicePixelSize*(width-1.0); 
float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;W.ShadersStore[fL]=_L;class f_ extends De{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const l=(s==null?void 0:s.getScene())||null;this._colorTableTexture=new k(t,l,!0,!1,k.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=k.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=k.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=h=>{h.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return _e.Parse(()=>new f_(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}E([I()],f_.prototype,"colorTableUrl",void 0);V("BABYLON.ColorCorrectionPostProcess",f_);const pL="convolutionPixelShader",mL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =
texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +
texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +
texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +
texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +
texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +
texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +
texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +
texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +
texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =
kernel[0] +
kernel[1] +
kernel[2] +
kernel[3] +
kernel[4] +
kernel[5] +
kernel[6] +
kernel[7] +
kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}
gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;W.ShadersStore[pL]=mL;class qn extends De{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,l=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,l),this.kernel=t,this.onApply=h=>{h.setFloat2("screenSize",this.width,this.height),h.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return _e.Parse(()=>new qn(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,s)}}qn.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];qn.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];qn.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];qn.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];qn.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];qn.GaussianKernel=[0,1,0,1,1,1,0,1,0];E([I()],qn.prototype,"kernel",void 0);V("BABYLON.ConvolutionPostProcess",qn);class xf extends ts{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,l=null,h=k.BILINEAR_SAMPLINGMODE,c,u,d=0,f=!1,_=5){super(e,i,s,r,n,h=2,c,u,d,`#define DOF 1
`,f,_),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(p=>{l!=null&&p.setTextureFromPostProcess("textureSampler",l),p.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}E([I()],xf.prototype,"direction",void 0);V("BABYLON.DepthOfFieldBlurPostProcess",xf);const gL="depthOfFieldMergePixelShader",xL=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;
#if BLUR_LEVEL>0
uniform sampler2D blurStep1;
#endif
#if BLUR_LEVEL>1
uniform sampler2D blurStep2;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;
#if BLUR_LEVEL==0
vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);
#endif
#if BLUR_LEVEL==1
if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}
#endif
#if BLUR_LEVEL==2
if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}
#endif
}
`;W.ShadersStore[gL]=xL;class TL extends De{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,l,h,c=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,l,h,null,c,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach((f,_)=>{d.setTextureFromPostProcessOutput("blurStep"+(s.length-_-1),f)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+`
`),super.updateEffect(e,t,i,s,r,n)}}var Ml;(function(a){a[a.Low=0]="Low",a[a.Medium=1]="Medium",a[a.High=2]="High"})(Ml||(Ml={}));class wT extends St{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=Ml.Low,s=0,r=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new Nc("circleOfConfusion",t,1,null,k.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case Ml.High:{l=3,h=51;break}case Ml.Medium:{l=2,h=31;break}default:{h=15,l=1;break}}const c=h/Math.pow(2,l-1);let u=1;for(let d=0;d<l;d++){const f=new xf("vertical blur",e,new Z(0,1),c,u,null,this._circleOfConfusion,d==0?this._circleOfConfusion:null,k.BILINEAR_SAMPLINGMODE,n,!1,s,r,d==0?o:5);f.autoClear=!1,u=.75/Math.pow(2,d);const _=new xf("horizontal blur",e,new Z(1,0),c,u,null,this._circleOfConfusion,null,k.BILINEAR_SAMPLINGMODE,n,!1,s,r);_.autoClear=!1,this._depthOfFieldBlurY.push(f),this._depthOfFieldBlurX.push(_)}this._effects=[this._circleOfConfusion];for(let d=0;d<this._depthOfFieldBlurX.length;d++)this._effects.push(this._depthOfFieldBlurY[d]),this._effects.push(this._depthOfFieldBlurX[d]);this._dofMerge=new TL("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,u,null,k.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}const EL="displayPassPixelShader",SL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(passSampler,vUV);}`;W.ShadersStore[EL]=SL;class Mg extends De{getClassName(){return"DisplayPassPostProcess"}constructor(e,t,i,s,r,n){super(e,"displayPass",["passSampler"],["passSampler"],t,i,s,r,n)}static _Parse(e,t,i,s){return _e.Parse(()=>new Mg(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}V("BABYLON.DisplayPassPostProcess",Mg);const CL="filterPixelShader",vL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;W.ShadersStore[CL]=vL;class __ extends De{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return _e.Parse(()=>new __(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}E([um()],__.prototype,"kernelMatrix",void 0);V("BABYLON.FilterPostProcess",__);const bL="fxaaPixelShader",AL=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);
#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)
void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
#ifndef MALI
if(range<rangeMaxClamped) 
{gl_FragColor=rgbyM;return;}
#endif
float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)
{lumaN=lumaW;}
if (!horzSpan) 
{lumaS=lumaE;}
if (horzSpan) 
{lengthSign=texelSize.y;}
float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)
{lengthSign=-lengthSign;}
float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) 
{posB.x+=lengthSign*0.5;}
if (horzSpan)
{posB.y+=lengthSign*0.5;}
vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) 
{lumaNN=lumaSS;}
float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) 
{posN.x-=offNP.x*3.0;}
if (!doneN) 
{posN.y-=offNP.y*3.0;}
bool doneNP=(!doneN) || (!doneP);if (!doneP) 
{posP.x+=offNP.x*3.0;}
if (!doneP)
{posP.y+=offNP.y*3.0;}
if (doneNP)
{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}
float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)
{dstN=posM.y-posN.y;}
if (!horzSpan) 
{dstP=posP.y-posM.y;}
bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan)
{posM.x+=pixelOffsetSubpix*lengthSign;}
if (horzSpan)
{posM.y+=pixelOffsetSubpix*lengthSign;}
#ifdef MALI
if(range<rangeMaxClamped) 
{gl_FragColor=rgbyM;}
else
{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);}
#else
gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);
#endif
}`;W.ShadersStore[bL]=AL;const yL="fxaaVertexShader",RL=`attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[yL]=RL;class Fc extends De{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,s,r,n,o=0){super(e,"fxaa",["texelSize"],null,t,i,s||k.BILINEAR_SAMPLINGMODE,r,n,null,o,"fxaa",void 0,!0);const l=this._getDefines();this.updateEffect(l),this.onApplyObservable.add(h=>{const c=this.texelSize;h.setFloat2("texelSize",c.x,c.y)})}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?`#define MALI 1
`:null}static _Parse(e,t,i,s){return _e.Parse(()=>new Fc(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}V("BABYLON.FxaaPostProcess",Fc);const IL="grainPixelShader",PL=`#include<helperFunctions>
uniform sampler2D textureSampler; 
uniform float intensity;uniform float animatedSeed;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;W.ShadersStore[IL]=PL;class wc extends De{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,l),this.intensity=30,this.animated=!1,this.onApplyObservable.add(h=>{h.setFloat("intensity",this.intensity),h.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,s){return _e.Parse(()=>new wc(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}E([I()],wc.prototype,"intensity",void 0);E([I()],wc.prototype,"animated",void 0);V("BABYLON.GrainPostProcess",wc);const ML="highlightsPixelShader",DL=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;W.ShadersStore[ML]=DL;const OL="imageProcessingPixelShader",NL=`varying vec2 vUV;uniform sampler2D textureSampler;
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 result=texture2D(textureSampler,vUV);
#ifdef IMAGEPROCESSING
#ifndef FROMLINEARSPACE
result.rgb=toLinearSpace(result.rgb);
#endif
result=applyImageProcessing(result);
#else
#ifdef FROMLINEARSPACE
result=applyImageProcessing(result);
#endif
#endif
gl_FragColor=result;}`;W.ShadersStore[OL]=NL;class Dg extends De{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let i=null;const s=this.getEngine(),r=this.getCamera();if(r)i=r.getScene();else if(s&&s.scenes){const n=s.scenes;i=n[n.length-1]}else i=Ae.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new lt}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,l){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},l?(l.applyByPostProcess=!0,this._attachImageProcessingConfiguration(l,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=h=>{this.imageProcessingConfiguration.bind(h,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const s in this._defines)this._defines[s]&&(e+=`#define ${s};
`);const t=["textureSampler"],i=["scale"];lt&&(lt.PrepareSamplers(t,this._defines),lt.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}E([I()],Dg.prototype,"_fromLinearSpace",void 0);const FL="mrtFragmentDeclaration",wL=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
layout(location=0) out vec4 glFragData[{X}];
#endif
`;W.IncludesShadersStore[FL]=wL;const LL="geometryPixelShader",BL=`#extension GL_EXT_draw_buffers : require
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
precision highp float;
#ifdef BUMP
varying mat4 vWorldView;varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP)
varying vec3 vPositionW;
#endif
#ifdef VELOCITY
varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#ifdef NEED_UV
varying vec2 vUV;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#if defined(REFLECTIVITY)
#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;
#endif
#ifdef ALBEDOTEXTURE
varying vec2 vAlbedoUV;uniform sampler2D albedoSampler;
#endif
#ifdef REFLECTIVITYCOLOR
uniform vec3 reflectivityColor;
#endif
#ifdef ALBEDOCOLOR
uniform vec3 albedoColor;
#endif
#ifdef METALLIC
uniform float metallic;
#endif
#if defined(ROUGHNESS) || defined(GLOSSINESS)
uniform float glossiness;
#endif
#endif
#if defined(ALPHATEST) && defined(NEED_UV)
uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<helperFunctions>
void main() {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
vec3 normalOutput;
#ifdef BUMP
vec3 normalW=normalize(vNormalW);
#include<bumpFragment>
#ifdef NORMAL_WORLDSPACE
normalOutput=normalW;
#else
normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));
#endif
#else
normalOutput=normalize(vNormalV);
#endif
#ifdef ENCODE_NORMAL
normalOutput=normalOutput*0.5+0.5;
#endif
#ifdef PREPASS
#ifdef PREPASS_DEPTH
gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);
#endif
#ifdef PREPASS_NORMAL
gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);
#endif
#else
gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);
#endif
#ifdef POSITION
gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);
#endif
#ifdef VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);
#endif
#ifdef REFLECTIVITY
vec4 reflectivity=vec4(0.0,0.0,0.0,1.0);
#ifdef METALLICWORKFLOW
float metal=1.0;float roughness=1.0;
#ifdef ORMTEXTURE
metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;
#endif
#ifdef METALLIC
metal*=metallic;
#endif
#ifdef ROUGHNESS
roughness*=(1.0-glossiness); 
#endif
reflectivity.a-=roughness;vec3 color=vec3(1.0);
#ifdef ALBEDOTEXTURE
color=texture2D(albedoSampler,vAlbedoUV).rgb;
#ifdef GAMMAALBEDO
color=toLinearSpace(color);
#endif
#endif
#ifdef ALBEDOCOLOR
color*=albedoColor.xyz;
#endif
reflectivity.rgb=mix(vec3(0.04),color,metal);
#else
#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
reflectivity=texture2D(reflectivitySampler,vReflectivityUV);
#ifdef GAMMAREFLECTIVITYTEXTURE
reflectivity.rgb=toLinearSpace(reflectivity.rgb);
#endif
#else 
#ifdef REFLECTIVITYCOLOR
reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;
#endif
#endif
#ifdef GLOSSINESSS
reflectivity.a*=glossiness; 
#endif
#endif
gl_FragData[REFLECTIVITY_INDEX]=reflectivity;
#endif
}
`;W.ShadersStore[LL]=BL;const UL="geometryVertexDeclaration",VL="uniform mat4 viewProjection;uniform mat4 view;";W.IncludesShadersStore[UL]=VL;const kL="geometryUboDeclaration",GL=`#include<sceneUboDeclaration>
`;W.IncludesShadersStore[kL]=GL;const zL="geometryVertexShader",WL=`precision highp float;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
#include<__decl__geometryVertex>
#include<clipPlaneVertexDeclaration>
attribute vec3 position;attribute vec3 normal;
#ifdef NEED_UV
varying vec2 vUV;
#ifdef ALPHATEST
uniform mat4 diffuseMatrix;
#endif
#ifdef BUMP
uniform mat4 bumpMatrix;varying vec2 vBumpUV;
#endif
#ifdef REFLECTIVITY
uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef BUMP
varying mat4 vWorldView;
#endif
#ifdef BUMP
varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP)
varying vec3 vPositionW;
#endif
#ifdef VELOCITY
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;vec3 normalUpdated=normal;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));
#ifdef BUMP
vWorldView=view*finalWorld;vNormalW=normalUpdated;
#else
#ifdef NORMAL_WORLDSPACE
vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));
#else
vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));
#endif
#endif
vViewPos=view*worldPos;
#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
#if defined(POSITION) || defined(BUMP)
vPositionW=worldPos.xyz/worldPos.w;
#endif
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
#ifdef NEED_UV
#ifdef UV1
#if defined(ALPHATEST) && defined(ALPHATEST_UV1)
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#else
vUV=uv;
#endif
#ifdef BUMP_UV1
vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV1
vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef ALBEDO_UV1
vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#endif
#ifdef UV2
#if defined(ALPHATEST) && defined(ALPHATEST_UV2)
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#else
vUV=uv2;
#endif
#ifdef BUMP_UV2
vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV2
vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));
#endif
#ifdef ALBEDO_UV2
vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#endif
#include<bumpVertex>
}
`;W.ShadersStore[zL]=WL;const MC=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];sn(MC);class wt{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===wt.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===wt.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===wt.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===wt.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===wt.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case wt.POSITION_TEXTURE_TYPE:return this._positionIndex;case wt.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case wt.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case wt.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case wt.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new xe(0,0,0,0),this._clearDepthColor=new xe(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},wt._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[y.PositionKind,y.NormalKind],n=e.getMesh();if(i){let f=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),f=!0),i.bumpTexture&&ue.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let _=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture!==null&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),f=!0,_=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),_=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),_=!0),_&&(i.baseTexture!==null&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),f=!0),i.baseColor!==null&&s.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture!==null?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),f=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor!==null&&s.push("#define REFLECTIVITYCOLOR"),i.glossiness!==null&&s.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture!==null&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),f=!0,_=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),_=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),_=!0),_?(i.albedoTexture!==null&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),f=!0),i.albedoColor!==null&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture!==null?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0):i.reflectivityColor!==null&&s.push("#define REFLECTIVITYCOLOR"),i.microSurface!==null&&s.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture!==null&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0),i.specularColor!==null&&s.push("#define REFLECTIVITYCOLOR"))}f&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(y.UVKind)&&(r.push(y.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(y.UV2Kind)&&(r.push(y.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),this._depthIndex!==-1&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(n)===-1&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(y.MatricesIndicesKind),r.push(y.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(y.MatricesIndicesExtraKind),r.push(y.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let l=0;o&&(l=o.numMaxInfluencers||o.numInfluencers,l>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+l),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),$u(r,n,l))),t&&(s.push("#define INSTANCES"),oo(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),no(i,this._scene,s);const h=this._scene.getEngine(),c=e._getDrawWrapper(void 0,!0),u=c.defines,d=s.join(`
`);return u!==d&&c.setEffect(h.createEffect("geometry",{attributes:r,uniformsNames:MC,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:d,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:l}},h),d),c.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[wt.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[wt.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[wt.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[wt.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[wt.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[];for(const g of s)g?(o.push(g.textureType),l.push(g.textureFormat)):(o.push(r),l.push(5));if(this._normalsAreUnsigned=o[wt.NORMAL_TEXTURE_TYPE]===11||o[wt.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new vo("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=k.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=k.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const h=[!0],c=[!1],u=[!0];for(let g=1;g<t;++g)h.push(!0),u.push(!1),c.push(!0);const d=e.buildTextureLayout(h),f=e.buildTextureLayout(c),_=e.buildTextureLayout(u);this._multiRenderTarget.onClearObservable.add(g=>{g.bindAttachments(this.useSpecificClearForDepthTexture?f:d),g.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(g.bindAttachments(_),g.clear(this._clearDepthColor,!0,!0,!0)),g.bindAttachments(d)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const g=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(g)}});const p=g=>{const x=g.getRenderingMesh(),T=g.getEffectiveMesh(),S=this._scene,C=S.getEngine(),v=g.getMaterial();if(!v)return;if(T._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[T.uniqueId]&&(this._previousTransformationMatrices[T.uniqueId]={world:D.Identity(),viewProjection:S.getTransformMatrix()},x.skeleton)){const L=x.skeleton.getTransformMatrices(x);this._previousBonesTransformationMatrices[x.uniqueId]=this._copyBonesTransformationMatrices(L,new Float32Array(L.length))}const b=x._getInstancesRenderList(g._id,!!g.getReplacementMesh());if(b.mustReturn)return;const A=C.getCaps().instancedArrays&&(b.visibleInstances[g._id]!==null||x.hasThinInstances),P=T.getWorldMatrix();if(this.isReady(g,A)){const L=g._getDrawWrapper();if(!L)return;const w=L.effect;C.enableEffect(L),A||x._bind(g,w,v.fillMode),this._useUbo?(bf(w,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(w.setMatrix("viewProjection",S.getTransformMatrix()),w.setMatrix("view",S.getViewMatrix()));let $;const J=x._instanceDataStorage;if(!J.isFrozen&&(v.backFaceCulling||x.overrideMaterialSideOrientation!==null)){const ne=T._getWorldMatrixDeterminant();$=x.overrideMaterialSideOrientation,$===null&&($=v.sideOrientation),ne<0&&($=$===ee.ClockWiseSideOrientation?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation)}else $=J.sideOrientation;if(v._preBind(L,$),v.needAlphaTesting()){const ne=v.getAlphaTestTexture();ne&&(w.setTexture("diffuseSampler",ne),w.setMatrix("diffuseMatrix",ne.getTextureMatrix()))}if(v.bumpTexture&&S.getEngine().getCaps().standardDerivatives&&ue.BumpTextureEnabled&&(w.setFloat3("vBumpInfos",v.bumpTexture.coordinatesIndex,1/v.bumpTexture.level,v.parallaxScaleBias),w.setMatrix("bumpMatrix",v.bumpTexture.getTextureMatrix()),w.setTexture("bumpSampler",v.bumpTexture),w.setFloat2("vTangentSpaceParams",v.invertNormalMapX?-1:1,v.invertNormalMapY?-1:1)),this._enableReflectivity&&(v.getClassName()==="PBRMetallicRoughnessMaterial"?(v.metallicRoughnessTexture!==null&&(w.setTexture("reflectivitySampler",v.metallicRoughnessTexture),w.setMatrix("reflectivityMatrix",v.metallicRoughnessTexture.getTextureMatrix())),v.metallic!==null&&w.setFloat("metallic",v.metallic),v.roughness!==null&&w.setFloat("glossiness",1-v.roughness),v.baseTexture!==null&&(w.setTexture("albedoSampler",v.baseTexture),w.setMatrix("albedoMatrix",v.baseTexture.getTextureMatrix())),v.baseColor!==null&&w.setColor3("albedoColor",v.baseColor)):v.getClassName()==="PBRSpecularGlossinessMaterial"?(v.specularGlossinessTexture!==null?(w.setTexture("reflectivitySampler",v.specularGlossinessTexture),w.setMatrix("reflectivityMatrix",v.specularGlossinessTexture.getTextureMatrix())):v.specularColor!==null&&w.setColor3("reflectivityColor",v.specularColor),v.glossiness!==null&&w.setFloat("glossiness",v.glossiness)):v.getClassName()==="PBRMaterial"?(v.metallicTexture!==null&&(w.setTexture("reflectivitySampler",v.metallicTexture),w.setMatrix("reflectivityMatrix",v.metallicTexture.getTextureMatrix())),v.metallic!==null&&w.setFloat("metallic",v.metallic),v.roughness!==null&&w.setFloat("glossiness",1-v.roughness),v.roughness!==null||v.metallic!==null||v.metallicTexture!==null?(v.albedoTexture!==null&&(w.setTexture("albedoSampler",v.albedoTexture),w.setMatrix("albedoMatrix",v.albedoTexture.getTextureMatrix())),v.albedoColor!==null&&w.setColor3("albedoColor",v.albedoColor)):(v.reflectivityTexture!==null?(w.setTexture("reflectivitySampler",v.reflectivityTexture),w.setMatrix("reflectivityMatrix",v.reflectivityTexture.getTextureMatrix())):v.reflectivityColor!==null&&w.setColor3("reflectivityColor",v.reflectivityColor),v.microSurface!==null&&w.setFloat("glossiness",v.microSurface))):v.getClassName()==="StandardMaterial"&&(v.specularTexture!==null&&(w.setTexture("reflectivitySampler",v.specularTexture),w.setMatrix("reflectivityMatrix",v.specularTexture.getTextureMatrix())),v.specularColor!==null&&w.setColor3("reflectivityColor",v.specularColor))),Gr(w,v,this._scene),x.useBones&&x.computeBonesUsingShaders&&x.skeleton){const ne=x.skeleton;if(ne.isUsingTextureForMatrices&&w.getUniformIndex("boneTextureWidth")>-1){const oe=ne.getTransformMatrixTexture(x);w.setTexture("boneSampler",oe),w.setFloat("boneTextureWidth",4*(ne.bones.length+1))}else w.setMatrices("mBones",x.skeleton.getTransformMatrices(x));this._enableVelocity&&w.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[x.uniqueId])}Sa(x,w),x.morphTargetManager&&x.morphTargetManager.isUsingTextureForTargets&&x.morphTargetManager._bind(w),this._enableVelocity&&(w.setMatrix("previousWorld",this._previousTransformationMatrices[T.uniqueId].world),w.setMatrix("previousViewProjection",this._previousTransformationMatrices[T.uniqueId].viewProjection)),A&&x.hasThinInstances&&w.setMatrix("world",P),x._processRendering(T,g,w,v.fillMode,b,A,(ne,oe)=>{ne||w.setMatrix("world",oe)})}this._enableVelocity&&(this._previousTransformationMatrices[T.uniqueId].world=P.clone(),this._previousTransformationMatrices[T.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),x.skeleton&&this._copyBonesTransformationMatrices(x.skeleton.getTransformMatrices(x),this._previousBonesTransformationMatrices[T.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(g,x,T)=>{if((T||x===0)&&g.subMeshes)for(let S=0;S<g.subMeshes.length;++S){const C=g.subMeshes[S],v=C.getMaterial(),b=C.getRenderingMesh();if(!v)continue;const A=b._getInstancesRenderList(C._id,!!C.getReplacementMesh()),P=e.getCaps().instancedArrays&&(A.visibleInstances[C._id]!==null||b.hasThinInstances);if(!this.isReady(C,P))return!1}return!0},this._multiRenderTarget.customRenderFunction=(g,x,T,S)=>{let C;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(S.length){for(e.setColorWrite(!1),C=0;C<S.length;C++)p(S.data[C]);e.setColorWrite(!0)}for(C=0;C<g.length;C++)p(g.data[C]);for(e.setDepthWrite(!1),C=0;C<x.length;C++)p(x.data[C]);if(this.renderTransparentMeshes)for(C=0;C<T.length;C++)p(T.data[C]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}}wt.DEPTH_TEXTURE_TYPE=0;wt.NORMAL_TEXTURE_TYPE=1;wt.POSITION_TEXTURE_TYPE=2;wt.VELOCITY_TEXTURE_TYPE=3;wt.REFLECTIVITY_TEXTURE_TYPE=4;wt._SceneComponentInitialization=a=>{throw Ge("GeometryBufferRendererSceneComponent")};class HL{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Ee.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(a){a&&a.isSupported&&(this._geometryBufferRenderer=a)},enumerable:!0,configurable:!0});Ee.prototype.enableGeometryBufferRenderer=function(a=1,e=15,t){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new wt(this,a,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};Ee.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class XL{constructor(e){this.name=he.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(he.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}wt._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_GEOMETRYBUFFERRENDERER);e||(e=new XL(a),a._addComponent(e))};const YL="motionBlurPixelShader",$L=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;
#ifdef OBJECT_BASED
uniform sampler2D velocitySampler;
#else
uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#ifdef GEOMETRY_SUPPORTED
#ifdef OBJECT_BASED
vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i)
{if (i>=samplesCount)
break;vec2 offset=vUV+velocity*(hlim+float(i));
#if defined(WEBGPU)
result+=texture2DLodEXT(textureSampler,offset,0.0);
#else
result+=texture2D(textureSampler,offset);
#endif
}
gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;
#else
vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; 
vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples)
break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);
#if defined(WEBGPU)
result+=texture2DLodEXT(textureSampler,offset1,0.0);
#else
result+=texture2D(textureSampler,offset1);
#endif
}
gl_FragColor=result/float(nSamples);
#endif
#else
gl_FragColor=texture2D(textureSampler,vUV);
#endif
}
`;W.ShadersStore[YL]=$L;class Ko extends De{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,l=0,h=!1,c=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,`#define GEOMETRY_SUPPORTED
#define SAMPLES 64.0
#define OBJECT_BASED`,l,void 0,null,h),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=c,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new HL)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else if(this._prePassRenderer)t=this._prePassRenderer.excludedSkinnedMesh;else return;const i=t.indexOf(e);i!==-1&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return O.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=D.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new Z(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(wt.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=U.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new Z(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(wt.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[i])}else if(this._prePassRenderer){const i=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[i])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join(`
`))}}static _Parse(e,t,i,s){return _e.Parse(()=>new Ko(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}E([I()],Ko.prototype,"motionStrength",void 0);E([I()],Ko.prototype,"motionBlurSamples",null);E([I()],Ko.prototype,"isObjectBased",null);V("BABYLON.MotionBlurPostProcess",Ko);const KL="refractionPixelShader",jL="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";W.ShadersStore[KL]=jL;class jo extends De{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,l,h,c){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,l,h,c),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add(u=>{this._refTexture=this._refTexture||new k(t,u.getScene())}),this.onApplyObservable.add(u=>{u.setColor3("baseColor",this.color),u.setFloat("depth",this.depth),u.setFloat("colorLevel",this.colorLevel),u.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return _e.Parse(()=>new jo(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}E([I()],jo.prototype,"color",void 0);E([I()],jo.prototype,"depth",void 0);E([I()],jo.prototype,"colorLevel",void 0);E([I()],jo.prototype,"refractionTextureUrl",void 0);V("BABYLON.RefractionPostProcess",jo);const qL="sharpenPixelShader",QL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +
texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(0,1)) -
color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;W.ShadersStore[qL]=QL;class Lc extends De{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,l),this.colorAmount=1,this.edgeAmount=.3,this.onApply=h=>{h.setFloat2("screenSize",this.width,this.height),h.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return _e.Parse(()=>new Lc(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}E([I()],Lc.prototype,"colorAmount",void 0);E([I()],Lc.prototype,"edgeAmount",void 0);V("BABYLON.SharpenPostProcess",Lc);class qo{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(X.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(X.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=X.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r<i.length;r++){const n=i[r];n&&(this._cameras.indexOf(n)===-1?this._cameras.push(n):t&&s.push(r))}for(r=0;r<s.length;r++)i.splice(s[r],1);for(const n in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,n)&&this._renderEffects[n]._attachCameras(i)}_detachCameras(e){const t=X.MakeArray(e||this._cameras);if(t){for(const i in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,i)&&this._renderEffects[i]._detachCameras(t);for(let i=0;i<t.length;i++)this._cameras.splice(this._cameras.indexOf(t[i]),1)}}_update(){for(const e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;const t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;const t=Object.keys(this._renderEffects);if(t.length>0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const i=this._renderEffects[t].getPostProcesses();if(i)for(const s of i)s.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}E([I()],qo.prototype,"_name",void 0);class ZL{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(Ee.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let a=this._getComponent(he.NAME_POSTPROCESSRENDERPIPELINEMANAGER);a||(a=new JL(this),this._addComponent(a)),this._postProcessRenderPipelineManager=new ZL}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class JL{constructor(e){this.name=he.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(he.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class ys extends qo{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new FT(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;const t=this.depthOfField;this.depthOfField=new wT(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let i=0;i<this._cameras.length;i++)t.disposeEffects(this._cameras[i]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new Ur("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return this._glowLayer!=null}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=Ae.LastCreatedScene,s,r=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=Ml.Low,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new G,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=s||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=r,this._scene=i;const n=this._scene.getEngine().getCaps();this._hdr=t&&(n.textureHalfFloatRender||n.textureFloatRender),this._hdr?n.textureHalfFloatRender?this._defaultPipelineTextureType=2:n.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);const o=this._scene.getEngine();this.sharpen=new Lc("sharpen",1,null,k.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new St(o,this.SharpenPostProcessId,()=>this.sharpen,!0),this.depthOfField=new wT(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add(()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new FT(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new jn("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,k.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new St(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new wc("Grain",1,null,k.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new St(o,this.GrainPostProcessId,()=>this.grain,!0);let l=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,l?X.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),l=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const t of this._cameras){const i=this._scene.enableDepthRenderer(t);i.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(t=>{this._cameras.indexOf(t.activeCamera)>-1&&(this.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const t=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=t.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Dg("imageProcessing",1,null,k.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new St(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,(!this._cameras||this._cameras.length===0)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new Fc("fxaa",1,null,k.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new St(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1)&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&this._cameras.indexOf(this._scene.activeCamera)===-1&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&O.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;t<this._cameras.length;t++){const i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){const e=_e.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return _e.Parse(()=>new ys(e._name,e._name._hdr,t),e,t,i)}}E([I()],ys.prototype,"sharpenEnabled",null);E([I()],ys.prototype,"bloomKernel",null);E([I()],ys.prototype,"_bloomWeight",void 0);E([I()],ys.prototype,"_bloomThreshold",void 0);E([I()],ys.prototype,"_hdr",void 0);E([I()],ys.prototype,"bloomWeight",null);E([I()],ys.prototype,"bloomThreshold",null);E([I()],ys.prototype,"bloomScale",null);E([I()],ys.prototype,"bloomEnabled",null);E([I()],ys.prototype,"depthOfFieldEnabled",null);E([I()],ys.prototype,"depthOfFieldBlurLevel",null);E([I()],ys.prototype,"fxaaEnabled",null);E([I()],ys.prototype,"samples",null);E([I()],ys.prototype,"imageProcessingEnabled",null);E([I()],ys.prototype,"glowLayerEnabled",null);E([I()],ys.prototype,"chromaticAberrationEnabled",null);E([I()],ys.prototype,"grainEnabled",null);V("BABYLON.DefaultRenderingPipeline",ys);const eB="lensHighlightsPixelShader",tB=`uniform sampler2D textureSampler; 
uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }
else { lum_threshold=0.5+0.44*threshold; }
luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}
float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);
#ifdef PENTAGON
blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));
#else
blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));
#endif
blurred/=39.0;gl_FragColor=blurred;}`;W.ShadersStore[eB]=tB;const iB="depthOfFieldPixelShader",sB=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; 
uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;
#define PI 3.14159265
#define TWOPI 6.28318530
#define inverse_focal_length 0.1 
vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)
{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}
vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }
vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}
float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}
float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}
vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}
if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}
col/=total_weight; 
if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}
return col;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); 
vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); 
float depth=texture2D(depthSampler,distorted_coords).r; 
float distance=near+(far-near)*depth; 
vec4 color=texture2D(textureSampler,vUV); 
float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }
float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}
float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}
else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}
if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}
if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}
`;W.ShadersStore[iB]=sB;class rB{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const nB="ssao2PixelShader",aB=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSAO
float scales[16]=float[16](
0.1,
0.11406250000000001,
0.131640625,
0.15625,
0.187890625,
0.2265625,
0.272265625,
0.325,
0.384765625,
0.4515625,
0.525390625,
0.60625,
0.694140625,
0.7890625,
0.891015625,
1.0
);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main()
{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;}
float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}
occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}
#endif
#ifdef BLUR
uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;
#ifndef BLUR_BYPASS
uniform sampler2D depthSampler;
#ifdef BLUR_LEGACY
#define inline
float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}
#endif
#endif
void main()
{float result=0.0;
#ifdef BLUR_BYPASS
result=textureLod(textureSampler,vUV,0.0).r;
#else
#ifdef BLUR_H
vec2 step=vec2(1.0/outSize,0.0);
#else
vec2 step=vec2(0.0,1.0/outSize);
#endif
#ifdef BLUR_LEGACY
result=blur13Bilateral(textureSampler,vUV,step);
#else
float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2)
{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0,
float(samples),
float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;}
result/=weightSum;
#endif
#endif
gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;}
#endif
`;W.ShadersStore[nB]=aB;const oB="ssaoCombinePixelShader",lB=`uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor;
#define CUSTOM_FRAGMENT_MAIN_END
}
`;W.ShadersStore[oB]=lB;class is extends qo{set epsilon(e){this._epsilon=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO())}get epsilon(){return this._epsilon}set samples(e){this._samples=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()),this._sampleSphere=this._generateHemisphere()}get samples(){return this._samples}set textureSamples(e){this._textureSamples=e,this._prePassRenderer?this._prePassRenderer.samples=e:this._originalColorPostProcess.samples=e}get textureSamples(){return this._textureSamples}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}set bypassBlur(e){const t=this._getDefinesForBlur(this.expensiveBlur,e),i=this._getSamplersForBlur(e);this._blurHPostProcess.updateEffect(t.h,null,i),this._blurVPostProcess.updateEffect(t.v,null,i),this._bypassBlur=e}get bypassBlur(){return this._bypassBlur}set expensiveBlur(e){const t=this._getDefinesForBlur(e,this._bypassBlur);this._blurHPostProcess.updateEffect(t.h),this._blurVPostProcess.updateEffect(t.v),this._expensiveBlur=e}get expensiveBlur(){return this._expensiveBlur}static get IsSupported(){const e=Ae.LastCreatedEngine;return e?e._features.supportSSAO2:!1}get scene(){return this._scene}constructor(e,t,i,s,r=!1,n=0){var h,c;if(super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.maxZ=100,this.minZAspect=.2,this._epsilon=.02,this._samples=8,this._textureSamples=1,this._forceGeometryBuffer=!1,this.radius=2,this.base=0,this._bypassBlur=!1,this._expensiveBlur=!0,this.bilateralSamples=16,this.bilateralSoften=0,this.bilateralTolerance=0,this._bits=new Uint32Array(1),this._scene=t,this._ratio=i,this._textureType=n,this._forceGeometryBuffer=r,!this.isSupported){O.Error("The current engine does not support SSAO 2.");return}const o=this._ratio.ssaoRatio||i,l=this._ratio.blurRatio||i;this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),(h=t.geometryBufferRenderer)!=null&&h.generateNormalsInWorldSpace&&O.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!")):(t.enablePrePassRenderer(),(c=t.prePassRenderer)!=null&&c.generateNormalsInWorldSpace&&O.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!")),this._createRandomTexture(),this._originalColorPostProcess=new An("SSAOOriginalSceneColor",1,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,n),this._createBlurPostProcess(o,l,this._textureType),this._createSSAOCombinePostProcess(l,this._textureType),this.addEffect(new St(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t<this._scene.cameras.length;t++){const i=this._scene.cameras[t];this._originalColorPostProcess.dispose(i),this._ssaoPostProcess.dispose(i),this._blurHPostProcess.dispose(i),this._blurVPostProcess.dispose(i),this._ssaoCombinePostProcess.dispose(i)}this._randomTexture.dispose(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_rebuild(){super._rebuild()}_getSamplersForBlur(e){return e?["textureSampler"]:["textureSampler","depthSampler"]}_getDefinesForBlur(e,t){let i=`#define BLUR
`;return t&&(i+=`#define BLUR_BYPASS
`),e||(i+=`#define BLUR_LEGACY
`),{h:i+`#define BLUR_H
`,v:i}}_createBlurPostProcess(e,t,i){const s=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),r=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",r,e,s.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",r,t,s.v,i,!1)}_createBlurFilter(e,t,i,s,r,n){const o=new De(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,s,r);return o.onApply=l=>{if(!this._scene.activeCamera)return;const h=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,c=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;l.setFloat("outSize",h>0?h:c),l.setInt("samples",this.bilateralSamples),l.setFloat("soften",this.bilateralSoften),l.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?l.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&l.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(this._bits[0]&1431655765)<<1|(this._bits[0]&2863311530)>>>1>>>0,this._bits[0]=(this._bits[0]&858993459)<<2|(this._bits[0]&3435973836)>>>2>>>0,this._bits[0]=(this._bits[0]&252645135)<<4|(this._bits[0]&4042322160)>>>4>>>0,this._bits[0]=(this._bits[0]&16711935)<<8|(this._bits[0]&4278255360)>>>8>>>0,this._bits[0]*23283064365386963e-26}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=t*2*Math.PI,s=1-e*.85,r=Math.sqrt(1-s*s);return new m(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s<e;){if(e<16)i=this._hemisphereSample_uniform(Math.random(),Math.random());else{const r=this._hammersley(s,e);i=this._hemisphereSample_uniform(r[0],r[1])}t.push(i.x,i.y,i.z),s++}return t}_getDefinesForSSAO(){return`#define SSAO
#define SAMPLES ${this.samples}
#define EPSILON ${this.epsilon.toFixed(4)}`}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();const i=this._getDefinesForSSAO(),s=["randomSampler","depthSampler","normalSampler"];this._ssaoPostProcess=new De("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],s,e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=r=>{if(this._scene.activeCamera){if(r.setArray3("sampleSphere",this._sampleSphere),r.setFloat("randTextureTiles",32),r.setFloat("samplesFactor",1/this.samples),r.setFloat("totalStrength",this.totalStrength),r.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),r.setFloat("radius",this.radius),r.setFloat("maxZ",this.maxZ),r.setFloat("minZAspect",this.minZAspect),r.setFloat("base",this.base),r.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===ve.PERSPECTIVE_CAMERA)r.setMatrix3x3("depthProjection",is.PERSPECTIVE_DEPTH_PROJECTION),r.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),r.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const n=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,l=this._scene.activeCamera.orthoLeft??-n,h=this._scene.activeCamera.orthoRight??n,c=this._scene.activeCamera.orthoBottom??-o,u=this._scene.activeCamera.orthoTop??o;r.setMatrix3x3("depthProjection",is.ORTHO_DEPTH_PROJECTION),r.setFloat("xViewport",(h-l)*.5),r.setFloat("yViewport",(u-c)*.5)}r.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(r.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),r.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(r.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),r.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),r.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new rB)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new De("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const s=this._scene.activeCamera.viewport;i.setVector4("viewport",U.Vector4[0].copyFromFloats(s.x,s.y,s.width,s.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=Z.Zero();for(let r=0;r<t.length;)i.set(ge.RandomRange(0,1),ge.RandomRange(0,1)).normalize().scaleInPlace(255),t[r++]=Math.floor(i.x),t[r++]=Math.floor(i.y),t[r++]=0,t[r++]=255;const s=Fi.CreateRGBATexture(t,128,128,this._scene,!1,!1,2);s.name="SSAORandomTexture",s.wrapU=k.WRAP_ADDRESSMODE,s.wrapV=k.WRAP_ADDRESSMODE,this._randomTexture=s}serialize(){const e=_e.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return _e.Parse(()=>new is(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}is.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];is.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];E([I()],is.prototype,"totalStrength",void 0);E([I()],is.prototype,"maxZ",void 0);E([I()],is.prototype,"minZAspect",void 0);E([I("epsilon")],is.prototype,"_epsilon",void 0);E([I("samples")],is.prototype,"_samples",void 0);E([I("textureSamples")],is.prototype,"_textureSamples",void 0);E([I()],is.prototype,"_forceGeometryBuffer",void 0);E([I()],is.prototype,"_ratio",void 0);E([I()],is.prototype,"_textureType",void 0);E([I()],is.prototype,"radius",void 0);E([I()],is.prototype,"base",void 0);E([I("bypassBlur")],is.prototype,"_bypassBlur",void 0);E([I("expensiveBlur")],is.prototype,"_expensiveBlur",void 0);E([I()],is.prototype,"bilateralSamples",void 0);E([I()],is.prototype,"bilateralSoften",void 0);E([I()],is.prototype,"bilateralTolerance",void 0);V("BABYLON.SSAO2RenderingPipeline",is);const hB="ssaoPixelShader",cB=`uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSAO
uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)
{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}
void main()
{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++)
{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));}
float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;}
#endif
`;W.ShadersStore[hB]=cB;class ad extends qo{get scene(){return this._scene}constructor(e,t,i,s){super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=t,this._createRandomTexture();const r=i.ssaoRatio||i,n=i.combineRatio||i;this._originalColorPostProcess=new An("SSAOOriginalSceneColor",n,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(r),this._createBlurPostProcess(r),this._createSSAOCombinePostProcess(n),this.addEffect(new St(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new St(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const i of this._cameras)this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let t=0;t<this._scene.cameras.length;t++){const i=this._scene.cameras[t];this._originalColorPostProcess.dispose(i),this._ssaoPostProcess.dispose(i),this._blurHPostProcess.dispose(i),this._blurVPostProcess.dispose(i),this._ssaoCombinePostProcess.dispose(i)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_createBlurPostProcess(e){this._blurHPostProcess=new ts("BlurH",new Z(1,0),16,e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurVPostProcess=new ts("BlurV",new Z(0,1),16,e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurHPostProcess.onActivateObservable.add(()=>{const i=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*i}),this._blurVPostProcess.onActivateObservable.add(()=>{const i=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*i})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const i=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271],s=1/16;this._ssaoPostProcess=new De("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define SAMPLES 16
#define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=r=>{this._firstUpdate&&(r.setArray3("sampleSphere",i),r.setFloat("samplesFactor",s),r.setFloat("randTextureTiles",4)),r.setFloat("totalStrength",this.totalStrength),r.setFloat("radius",this.radius),r.setFloat("area",this.area),r.setFloat("fallOff",this.fallOff),r.setFloat("base",this.base),r.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),r.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new De("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,k.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",U.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let s=0;s<t.length;)t[s++]=Math.floor(Math.max(0,ge.RandomRange(-1,1))*255),t[s++]=Math.floor(Math.max(0,ge.RandomRange(-1,1))*255),t[s++]=Math.floor(Math.max(0,ge.RandomRange(-1,1))*255),t[s++]=255;const i=Fi.CreateRGBATexture(t,512,512,this._scene,!1,!1,2);i.name="SSAORandomTexture",i.wrapU=k.WRAP_ADDRESSMODE,i.wrapV=k.WRAP_ADDRESSMODE,this._randomTexture=i}}E([I()],ad.prototype,"totalStrength",void 0);E([I()],ad.prototype,"radius",void 0);E([I()],ad.prototype,"area",void 0);E([I()],ad.prototype,"fallOff",void 0);E([I()],ad.prototype,"base",void 0);class uB{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}}const dB="screenSpaceReflectionPixelShader",fB=`uniform sampler2D textureSampler;
#ifdef SSR_SUPPORTED
uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;
#endif
uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV;
#ifdef SSR_SUPPORTED
struct ReflectionInfo {vec3 color;vec4 coords;};/**
* According to specular,see https:
*/
vec3 fresnelSchlick(float cosTheta,vec3 F0)
{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);}
/**
* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit
* by sampling multiple reflection pixels.
*/
ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)
{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++)
{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0)
hitCoord-=dir;else
hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}
projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}
/**
* Tests the given world position (hitCoord) according to the given reflection vector (dir)
* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!").
*/
ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)
{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++)
{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;
#ifdef RIGHT_HANDED_SCENE
depth*=-1.0;
#endif
if(((depth-dir.z)<threshold) && depth<=0.0)
{
#ifdef ENABLE_SMOOTH_REFLECTIONS
return smoothReflectionInfo(dir,hitCoord);
#else
info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;
#endif
}}
info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;}
vec3 hash(vec3 a)
{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}
#endif
void main()
{
#ifdef SSR_SUPPORTED
vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;}
vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0);
#ifdef RIGHT_HANDED_SCENE
reflected.z*=-1.0;
#endif
float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a);
#else
gl_FragColor=texture2D(textureSampler,vUV);
#endif
}
`;W.ShadersStore[dB]=fB;class rn extends De{get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"ScreenSpaceReflectionPostProcess"}constructor(e,t,i,s,r,n,o,l=0,h=!1,c=!1){if(super(e,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],i,s,r,n,o,`#define SSR_SUPPORTED
#define REFLECTION_SAMPLES 64
#define SMOOTH_STEPS 5
`,l,void 0,null,h),this.threshold=1.2,this.strength=1,this.reflectionSpecularFalloffExponent=3,this.step=1,this.roughnessFactor=.2,this._forceGeometryBuffer=!1,this._enableSmoothReflections=!1,this._reflectionSamples=64,this._smoothSteps=5,this._forceGeometryBuffer=c,this._forceGeometryBuffer){const u=t.enableGeometryBufferRenderer();u&&u.isSupported&&(u.enablePosition=!0,u.enableReflectivity=!0,u.generateNormalsInWorldSpace&&O.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{const u=t.enablePrePassRenderer();u==null||u.markAsDirty(),u!=null&&u.generateNormalsInWorldSpace&&O.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!"),this._prePassEffectConfiguration=new uB}this._updateEffectDefines(),this.onApply=u=>{const d=this._geometryBufferRenderer,f=this._prePassRenderer;if(!f&&!d)return;if(d){const x=d.getTextureIndex(wt.POSITION_TEXTURE_TYPE),T=d.getTextureIndex(wt.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",d.getGBuffer().textures[1]),u.setTexture("positionSampler",d.getGBuffer().textures[x]),u.setTexture("reflectivitySampler",d.getGBuffer().textures[T])}else if(f){const x=f.getIndex(1),T=f.getIndex(3),S=f.getIndex(6);u.setTexture("normalSampler",f.getRenderTarget().textures[S]),u.setTexture("positionSampler",f.getRenderTarget().textures[x]),u.setTexture("reflectivitySampler",f.getRenderTarget().textures[T])}const _=t.activeCamera;if(!_)return;const p=_.getViewMatrix(!0),g=_.getProjectionMatrix(!0);u.setMatrix("projection",g),u.setMatrix("view",p),u.setFloat("threshold",this.threshold),u.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),u.setFloat("strength",this.strength),u.setFloat("stepSize",this.step),u.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join(`
`))}static _Parse(e,t,i,s){return _e.Parse(()=>new rn(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}E([I()],rn.prototype,"threshold",void 0);E([I()],rn.prototype,"strength",void 0);E([I()],rn.prototype,"reflectionSpecularFalloffExponent",void 0);E([I()],rn.prototype,"step",void 0);E([I()],rn.prototype,"roughnessFactor",void 0);E([I()],rn.prototype,"enableSmoothReflections",null);E([I()],rn.prototype,"reflectionSamples",null);E([I()],rn.prototype,"smoothSteps",null);V("BABYLON.ScreenSpaceReflectionPostProcess",rn);const _B="standardPixelShader",pB=`uniform sampler2D textureSampler;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
#if defined(PASS_POST_PROCESS)
void main(void)
{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}
#endif
#if defined(DOWN_SAMPLE_X4)
uniform vec2 dsOffsets[16];void main(void)
{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}
#endif
#if defined(BRIGHT_PASS)
uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)
{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);}
gl_FragColor=average;}
#endif
#if defined(TEXTURE_ADDER)
uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void)
{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;}
#endif
#if defined(VLS)
#define PI 3.1415926535897932384626433832795
uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView)
{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;}
void main(void)
{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++)
{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth)
accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}
accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}
#endif
#if defined(VLSMERGE)
uniform sampler2D originalSampler;void main(void)
{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}
#endif
#if defined(LUMINANCE)
uniform vec2 lumOffsets[4];void main()
{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)
{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));
#ifdef WEIGHTED_AVERAGE
float GreyValue=dot(color.rgb,weight);
#endif
#ifdef BRIGHTNESS
float GreyValue=max(color.r,max(color.g,color.b));
#endif
#ifdef HSL_COMPONENT
float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));
#endif
#ifdef MAGNITUDE
float GreyValue=length(color.rgb);
#endif
maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}
average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}
#endif
#if defined(LUMINANCE_DOWN_SAMPLE)
uniform vec2 dsOffsets[9];uniform float halfDestPixelSize;
#ifdef FINAL_DOWN_SAMPLER
#include<packingFunctions>
#endif
void main()
{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)
{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}
average/=9.0;
#ifdef FINAL_DOWN_SAMPLER
gl_FragColor=pack(average);
#else
gl_FragColor=vec4(average,average,0.0,1.0);
#endif
}
#endif
#if defined(HDR)
uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()
{vec4 color=texture2D(textureAdderSampler,vUV);
#ifndef AUTO_EXPOSURE
vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;
#endif
gl_FragColor=color;}
#endif
#if defined(LENS_FLARE)
#define GHOSTS 3
uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)
{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}
float noise(in vec2 p)
{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),
hash(i+vec2(1.0,0.0)),u.x),
mix(hash(i+vec2(0.0,1.0)),
hash(i+vec2(1.0,1.0)),u.x),u.y);}
float fbm(vec2 p)
{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}
vec3 pattern(vec2 uv)
{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}
float luminance(vec3 color)
{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}
vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)
{return vec4(
texture2D(tex,texcoord+direction*distortion.r).r,
texture2D(tex,texcoord+direction*distortion.g).g,
texture2D(tex,texcoord+direction*distortion.b).b,
1.0
);}
void main(void)
{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i)
{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;}
vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;}
#endif
#if defined(LENS_FLARE_COMPOSE)
uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void)
{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;}
#endif
#if defined(DEPTH_OF_FIELD)
uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void)
{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05)
factor=1.0;else if (dist<0.1)
factor=20.0*(0.1-dist);else if (dist<0.5)
factor=0.0;else
factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);}
#endif
#if defined(MOTION_BLUR)
uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void)
{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples)
break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}
gl_FragColor=result/float(nSamples);}
#endif
`;W.ShadersStore[_B]=pB;class yt extends qo{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join(`
`))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer()){O.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect(`#define VLS
#define NB_STEPS `+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect(`#define MOTION_BLUR
#define MAX_MOTION_SAMPLES `+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new rn("HDRPass",t,e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new St(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new De("HDRPass","standard",[],[],e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new St(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new De("HDRDepthOfFieldSource","standard",[],[],e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new St(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new De("HDRVLSFinal","standard",[],[],e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new St(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new De("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new St(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new De("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new St(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new Fc("fxaa",1,null,k.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new St(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&O.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new De("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=s=>{let r=0;const n=this.downSampleX4PostProcess.width,o=this.downSampleX4PostProcess.height;for(let l=-2;l<2;l++)for(let h=-2;h<2;h++)i[r]=(l+.5)*(1/n),i[r+1]=(h+.5)*(1/o),r+=2;s.setArray2("dsOffsets",i)},this.addEffect(new St(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new De("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=s=>{const r=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*r,i[1]=.5*n,i[2]=.5*r,i[3]=.5*n,i[4]=-.5*r,i[5]=-.5*n,i[6]=.5*r,i[7]=-.5*n,s.setArray2("dsOffsets",i),s.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new St(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new ts("HDRBlurH_"+i,new Z(1,0),this[s],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new ts("HDRBlurV_"+i,new Z(0,1),this[s],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{const l=n.width/r.getRenderWidth();n.kernel=this[s]*l}),o.onActivateObservable.add(()=>{const l=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*l:this[s]*l}),this.addEffect(new St(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new St(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new De("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),i.setTexture("lensSampler",this.lensTexture),i.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new St(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new De("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS
#define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const r=Z.Zero();this.volumetricLightPostProcess.onApply=n=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const o=this.sourceLight.getShadowGenerator();n.setTexture("shadowMapSampler",o.getShadowMap()),n.setTexture("positionSampler",s.textures[2]),n.setColor3("sunColor",this.sourceLight.diffuse),n.setVector3("sunDirection",this.sourceLight.getShadowDirection()),n.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),n.setMatrix("shadowViewProjection",o.getTransformMatrix()),n.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),n.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),n.setVector2("depthValues",r)}},this.addEffect(new St(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new De("HDRVLSMerge","standard",[],["originalSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=n=>{n.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new St(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,yt.LuminanceSteps);this.luminancePostProcess=new De("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=n=>{const o=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;s[0]=-.5*o,s[1]=.5*l,s[2]=.5*o,s[3]=.5*l,s[4]=-.5*o,s[5]=-.5*l,s[6]=.5*o,s[7]=-.5*l,n.setArray2("lumOffsets",s)},this.addEffect(new St(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let n=yt.LuminanceSteps-1;n>=0;n--){i=Math.pow(3,n);let o=`#define LUMINANCE_DOWN_SAMPLE
`;n===0&&(o+="#define FINAL_DOWN_SAMPLER");const l=new De("HDRLuminanceDownSample"+n,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(l)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((n,o)=>{const l=new Array(18);n.onApply=h=>{if(!r)return;let c=0;for(let u=-1;u<2;u++)for(let d=-1;d<2;d++)l[c]=u/r.width,l[c+1]=d/r.height,c+=2;h.setArray2("dsOffsets",l),h.setFloat("halfDestPixelSize",.5/r.width),o===this.luminanceDownSamplePostProcesses.length-1?r=this.luminancePostProcess:r=n},o===this.luminanceDownSamplePostProcesses.length-1&&(n.onAfterRender=()=>{const h=e.getEngine().readPixels(0,0,1,1),c=new we(1/(255*255*255),1/(255*255),1/255,1);h.then(u=>{const d=new Uint8Array(u.buffer);this._hdrCurrentLuminance=(d[0]*c.x+d[1]*c.y+d[2]*c.z+d[3]*c.w)/100})}),this.addEffect(new St(e.getEngine(),"HDRLuminanceDownSample"+o,()=>n,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new De("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(`
`),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const l=(n-r)/1e3;this._hdrCurrentLuminance<s+this.hdrDecreaseRate*l?s+=this.hdrDecreaseRate*l:this._hdrCurrentLuminance>s-this.hdrIncreaseRate*l?s-=this.hdrIncreaseRate*l:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=ge.Clamp(s,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new St(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new De("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new St(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new De("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new St(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new Z(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=n=>{n.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),n.setTexture("lensColorSampler",this.lensColorTexture),n.setFloat("strength",this.lensFlareStrength),n.setFloat("ghostDispersal",this.lensFlareGhostDispersal),n.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,n.setVector2("resolution",i),n.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=D.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=D.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=n=>{if(!this._scene.activeCamera)return;n.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),n.setTexture("lensDirtSampler",this.lensFlareDirtTexture),n.setTexture("lensStarSampler",this.lensStarTexture);const o=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let h=m.Dot(o.toVector3(),new m(1,0,0))+m.Dot(l.toVector3(),new m(0,0,1));h*=4;const c=D.FromValues(Math.cos(h)*.5,-Math.sin(h),0,0,Math.sin(h),Math.cos(h)*.5,0,0,0,0,1,0,0,0,0,1),u=r.multiply(c).multiply(s);n.setMatrix("lensStarMatrix",u),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new De("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=i=>{i.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),i.setTexture("depthSampler",this._getDepthTexture()),i.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new St(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new Ko("HDRMotionBlur",e,t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new De("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,k.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR
#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,s=D.Identity();const r=D.Identity();let n=D.Identity();const o=Z.Zero();this.motionBlurPostProcess.onApply=l=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),l.setMatrix("inverseViewProjection",r),l.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,l.setVector2("screenSize",o),i=e.getEngine().getFps()/60,l.setFloat("motionScale",i),l.setFloat("motionStrength",this.motionStrength),l.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new St(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;e<this._cameras.length;e++){const t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(let i=0;i<this.luminanceDownSamplePostProcesses.length;i++)this.luminanceDownSamplePostProcesses[i].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(let i=0;i<this.blurHPostProcesses.length;i++)this.blurHPostProcesses[i].dispose(t);for(let i=0;i<this.blurVPostProcesses.length;i++)this.blurVPostProcesses[i].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}serialize(){const e=_e.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=_e.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e}static Parse(e,t,i){const s=_e.Parse(()=>new yt(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&_e.Parse(()=>s.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),s}}yt.LuminanceSteps=6;E([I()],yt.prototype,"brightThreshold",void 0);E([I()],yt.prototype,"blurWidth",void 0);E([I()],yt.prototype,"horizontalBlur",void 0);E([I()],yt.prototype,"exposure",null);E([ht("lensTexture")],yt.prototype,"lensTexture",void 0);E([I()],yt.prototype,"volumetricLightCoefficient",void 0);E([I()],yt.prototype,"volumetricLightPower",void 0);E([I()],yt.prototype,"volumetricLightBlurScale",void 0);E([I()],yt.prototype,"hdrMinimumLuminance",void 0);E([I()],yt.prototype,"hdrDecreaseRate",void 0);E([I()],yt.prototype,"hdrIncreaseRate",void 0);E([I()],yt.prototype,"hdrAutoExposure",null);E([ht("lensColorTexture")],yt.prototype,"lensColorTexture",void 0);E([I()],yt.prototype,"lensFlareStrength",void 0);E([I()],yt.prototype,"lensFlareGhostDispersal",void 0);E([I()],yt.prototype,"lensFlareHaloWidth",void 0);E([I()],yt.prototype,"lensFlareDistortionStrength",void 0);E([I()],yt.prototype,"lensFlareBlurWidth",void 0);E([ht("lensStarTexture")],yt.prototype,"lensStarTexture",void 0);E([ht("lensFlareDirtTexture")],yt.prototype,"lensFlareDirtTexture",void 0);E([I()],yt.prototype,"depthOfFieldDistance",void 0);E([I()],yt.prototype,"depthOfFieldBlurWidth",void 0);E([I()],yt.prototype,"motionStrength",null);E([I()],yt.prototype,"objectBasedMotionBlur",null);E([I()],yt.prototype,"_ratio",void 0);E([I()],yt.prototype,"BloomEnabled",null);E([I()],yt.prototype,"DepthOfFieldEnabled",null);E([I()],yt.prototype,"LensFlareEnabled",null);E([I()],yt.prototype,"HDREnabled",null);E([I()],yt.prototype,"VLSEnabled",null);E([I()],yt.prototype,"MotionBlurEnabled",null);E([I()],yt.prototype,"fxaaEnabled",null);E([I()],yt.prototype,"screenSpaceReflectionsEnabled",null);E([I()],yt.prototype,"volumetricLightStepsCount",null);E([I()],yt.prototype,"motionBlurSamples",null);E([I()],yt.prototype,"samples",null);V("BABYLON.StandardRenderingPipeline",yt);class mB{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const gB="screenSpaceRayTrace",xB=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }
/**
param csOrigin Camera-space ray origin,which must be 
within the view volume and must have z>0.01 and project within the valid screen rectangle
param csDirection Unit length camera-space ray direction
param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates 
(**not** [-1,+1] normalized device coordinates).
param csZBuffer The camera-space Z buffer
param csZBufferSize Dimensions of csZBuffer
param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer
param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value
for clipping rays headed towards the camera
param stride Step in horizontal or vertical pixels between samples. This is a float
because integer math is slow on GPUs,but should be set to an integer>=1
param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units
to conceal banding artifacts,plus the stride ray offset.
param maxSteps Maximum number of iterations. Higher gives better images but may be slow
param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss
param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.
1 is a reasonable value,depending on the scene you may need to set this value to 2
param hitPixel Pixel coordinates of the first intersection with the scene
param numIterations number of iterations performed
param csHitPoint Camera space location of the ray hit
*/
#define inline
bool traceScreenSpaceRay1(
vec3 csOrigin,
vec3 csDirection,
mat4 projectToPixelMatrix,
sampler2D csZBuffer,
vec2 csZBufferSize,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
sampler2D csZBackBuffer,
float csZBackSizeFactor,
#endif
float csZThickness,
float nearPlaneZ,
float stride,
float jitterFraction,
float maxSteps,
float maxRayTraceDistance,
float selfCollisionNumSkip,
out vec2 startPixel,
out vec2 hitPixel,
out vec3 csHitPoint,
out float numIterations
#ifdef SSRAYTRACE_DEBUG
,out vec3 debugColor
#endif
)
{
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;
#else
float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;
#endif
vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1;
#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM
float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);}
if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));}
P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);
#endif
P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { 
permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; }
float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip ||
(pqk.x*stepDirection)<=end &&
stepCount<maxSteps &&
!hit &&
sceneZMax != 0.0; 
pqk+=dPQK,++stepCount)
{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { 
float t=rayZMin; rayZMin=rayZMax; rayZMax=t;}
sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);
#else
hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);
#endif
#else
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);
#else
hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);
#endif
#endif
}
pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}
#ifdef SSRAYTRACE_ENABLE_REFINEMENT
if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||
(refinementStepCount<=stride*1.4) &&
(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0)
{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;}
pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}
#endif
Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0;
#ifdef SSRAYTRACE_DEBUG
if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}
#endif
return hit;}
/**
texCoord: in the [0,1] range
depth: depth in view space (range [znear,zfar]])
*/
vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
ndc.z=-projection[2].z-projection[3].z/depth;
#else
ndc.z=projection[2].z+projection[3].z/depth;
#endif
ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}
`;W.IncludesShadersStore[gB]=xB;const TB="screenSpaceReflection2PixelShader",EB=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSR_SUPPORTED
uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
uniform sampler2D backDepthSampler;uniform float backSizeFactor;
#endif
#ifdef SSR_USE_ENVIRONMENT_CUBE
uniform samplerCube envCubeSampler;
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
vec3 hash(vec3 a)
{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}
float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;
#ifdef SSR_ATTENUATE_SCREEN_BORDERS
vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE
attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS
attenuation*=1.0-(numIterations/maxSteps);
#endif
#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION
vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;
#endif
return attenuation;}
#endif
void main()
{
#ifdef SSR_SUPPORTED
vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {
#ifdef SSR_USE_BLUR
gl_FragColor=vec4(0.);
#else
gl_FragColor=colorFull;
#endif
return;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpace(color);
#endif
vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; 
#ifdef SSR_DECODE_NORMAL
csNormal=csNormal*2.0-1.0;
#endif
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
csNormal=(view*vec4(csNormal,0.0)).xyz;
#endif
float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal);
#ifdef SSR_USE_ENVIRONMENT_CUBE
vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);
#endif
#ifdef SSR_INVERTCUBICMAP
wReflectedVector.y*=-1.0;
#endif
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
wReflectedVector.z*=-1.0;
#endif
vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;
#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE
envColor=toLinearSpace(envColor);
#endif
#else
vec3 envColor=color;
#endif
float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;
#ifdef SSRAYTRACE_DEBUG
vec3 debugColor;
#endif
#ifdef SSR_ATTENUATE_FACING_CAMERA
reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));
#endif
if (reflectionAttenuation>0.0) {
#ifdef SSR_USE_BLUR
vec3 jitt=vec3(0.);
#else
float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; 
#endif
vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); 
rayHasHit=traceScreenSpaceRay1(
csPosition,
normalize(csReflectedVector+jitt),
projectionPixel,
depthSampler,
texSize,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
backDepthSampler,
backSizeFactor,
#endif
thickness,
nearPlaneZ,
stepSize,
jitter,
maxSteps,
maxDistance,
selfCollisionNumSkip,
startPixel,
hitPixel,
hitPoint,
numIterations
#ifdef SSRAYTRACE_DEBUG
,debugColor
#endif
);}
#ifdef SSRAYTRACE_DEBUG
gl_FragColor=vec4(debugColor,1.);return;
#endif
vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;
#ifdef SSR_INPUT_IS_GAMMA_SPACE
reflectedColor=toLinearSpace(reflectedColor);
#endif
reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}
#ifndef SSR_BLEND_WITH_FRESNEL
SSR*=fresnel;
#endif
#ifdef SSR_USE_BLUR
float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; 
float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}
gl_FragColor=vec4(SSR,blur_radius/255.0); 
#else
#ifdef SSR_BLEND_WITH_FRESNEL
vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#else
vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#endif
vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpace(finalColor);
#endif
gl_FragColor=vec4(finalColor,colorFull.a);
#endif
#else
gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);
#endif
}
`;W.ShadersStore[TB]=EB;const SB="screenSpaceReflection2BlurPixelShader",CB=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)
{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}
void main()
{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}
float blurRadius=colorFull.a*255.0; 
vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}
`;W.ShadersStore[SB]=CB;const vB="screenSpaceReflection2BlurCombinerPixelShader",bB=`uniform sampler2D textureSampler; 
uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;
#include<helperFunctions>
#ifdef SSR_BLEND_WITH_FRESNEL
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;
#endif
void main()
{
#ifdef SSRAYTRACE_DEBUG
gl_FragColor=texture2D(textureSampler,vUV);
#else
vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpace(color);
#endif
#ifdef SSR_BLEND_WITH_FRESNEL
vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#else
vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#endif
vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpace(finalColor);
#endif
gl_FragColor=vec4(finalColor,color.a);
#endif
}
`;W.ShadersStore[vB]=bB;const AB=D.Compose(new m(.5,.5,.5),Q.Identity(),new m(.5,.5,.5)),yB=D.Compose(new m(.5,.5,1),Q.Identity(),new m(.5,.5,0));class jt extends qo{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(e===0&&this._reflectivityThreshold!==0||e!==0&&this._reflectivityThreshold===0?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=e===0&&this._blurDispersionStrength!==0||e!==0&&this._blurDispersionStrength===0;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const n=t.enableGeometryBufferRenderer();n&&(n.enableReflectivity=!0,n.useSpecificClearForDepthTexture=!0)}else{const n=t.enablePrePassRenderer();n&&(n.useSpecificClearForDepthTexture=!0,n.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var s,r;const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&((s=this._scene.activeCamera)==null?void 0:s._getFirstPostProcess())===this._ssrPostProcess){const n=t.getRenderTarget();n&&n.textures&&(i=n.textures[t.getIndex(4)].getSize())}else(r=this._ssrPostProcess)!=null&&r.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){var t,i,s,r;const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(((t=this._geometryBufferRenderer)==null?void 0:t.generateNormalsInWorldSpace)??((i=this._prePassRenderer)==null?void 0:i.generateNormalsInWorldSpace))&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(s=this._geometryBufferRenderer)!=null&&s.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL"),(r=this._ssrPostProcess)==null||r.updateEffect(e.join(`
`))}_buildPipeline(){var t;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const i=(t=this._cameras)==null?void 0:t[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new Yo(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),i.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new St(e,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new St(e,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new St(e,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==s)&&this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;e!==-1&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,s;for(let r=0;r<this._cameras.length;r++){const n=this._cameras[r];(e=this._ssrPostProcess)==null||e.dispose(n),(t=this._blurPostProcessX)==null||t.dispose(n),(i=this._blurPostProcessY)==null||i.dispose(n),(s=this._blurCombinerPostProcess)==null||s.dispose(n)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null}_createSSRPostProcess(){this._ssrPostProcess=new De("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(wt.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[l]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const l=i.getIndex(5),h=i.getIndex(3),c=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[c]),e.setTexture("depthSampler",i.getRenderTarget().textures[l]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[h])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(U.Matrix[0]),r.invertToRef(U.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",U.Matrix[1]),e.setMatrix("invProjectionMatrix",U.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();D.ScalingToRef(o.width,o.height,1,U.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?yB:AB,U.Matrix[3]),U.Matrix[3].multiplyToRef(U.Matrix[2],U.Matrix[4]),e.setMatrix("projectionPixel",U.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new mB)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new De("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(r=>{var o;const n=((o=this._blurPostProcessX)==null?void 0:o.inputTexture.width)??this._scene.getEngine().getRenderWidth();r.setFloat2("texelOffsetScale",this._blurDispersionStrength/n,0)}),this._blurPostProcessY=new De("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(r=>{var o;const n=((o=this._blurPostProcessY)==null?void 0:o.inputTexture.height)??this._scene.getEngine().getRenderHeight();r.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/n)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+=`#define SSRAYTRACE_DEBUG
`),this._inputTextureColorIsInGammaSpace&&(s+=`#define SSR_INPUT_IS_GAMMA_SPACE
`),this._generateOutputInGammaSpace&&(s+=`#define SSR_OUTPUT_IS_GAMMA_SPACE
`),this.useFresnel&&(s+=`#define SSR_BLEND_WITH_FRESNEL
`,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new De("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(r=>{var l;const n=this._geometryBufferRenderer,o=this._prePassRenderer;if(!(!o&&!n)){if(o&&((l=this._scene.activeCamera)==null?void 0:l._getFirstPostProcess())===this._ssrPostProcess){const h=o.getRenderTarget();h&&h.textures&&r.setTexture("mainSampler",h.textures[o.getIndex(4)])}else r.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(n){const h=n.getTextureIndex(wt.REFLECTIVITY_TEXTURE_TYPE);r.setTexture("reflectivitySampler",n.getGBuffer().textures[h]),this.useFresnel&&(r.setTexture("normalSampler",n.getGBuffer().textures[1]),r.setTexture("depthSampler",n.getGBuffer().textures[0]))}else if(o){const h=o.getIndex(3);if(r.setTexture("reflectivitySampler",o.getRenderTarget().textures[h]),this.useFresnel){const c=o.getIndex(5),u=o.getIndex(6);r.setTexture("normalSampler",o.getRenderTarget().textures[u]),r.setTexture("depthSampler",o.getRenderTarget().textures[c])}}if(r.setFloat("strength",this.strength),r.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),r.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const h=this._scene.activeCamera;if(h){const c=h.getProjectionMatrix();c.invertToRef(U.Matrix[0]),r.setMatrix("projection",c),r.setMatrix("invProjectionMatrix",U.Matrix[0])}}}})}serialize(){const e=_e.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return _e.Parse(()=>new jt(e._name,t,e._ratio),e,t,i)}}E([I()],jt.prototype,"samples",null);E([I()],jt.prototype,"maxDistance",void 0);E([I()],jt.prototype,"step",void 0);E([I()],jt.prototype,"thickness",void 0);E([I()],jt.prototype,"strength",void 0);E([I()],jt.prototype,"reflectionSpecularFalloffExponent",void 0);E([I()],jt.prototype,"maxSteps",void 0);E([I()],jt.prototype,"roughnessFactor",void 0);E([I()],jt.prototype,"selfCollisionNumSkip",void 0);E([I()],jt.prototype,"_reflectivityThreshold",void 0);E([I("_ssrDownsample")],jt.prototype,"_ssrDownsample",void 0);E([I()],jt.prototype,"ssrDownsample",null);E([I("blurDispersionStrength")],jt.prototype,"_blurDispersionStrength",void 0);E([I("blurDownsample")],jt.prototype,"_blurDownsample",void 0);E([I("enableSmoothReflections")],jt.prototype,"_enableSmoothReflections",void 0);E([I("environmentTexture")],jt.prototype,"_environmentTexture",void 0);E([I("environmentTextureIsProbe")],jt.prototype,"_environmentTextureIsProbe",void 0);E([I("attenuateScreenBorders")],jt.prototype,"_attenuateScreenBorders",void 0);E([I("attenuateIntersectionDistance")],jt.prototype,"_attenuateIntersectionDistance",void 0);E([I("attenuateIntersectionIterations")],jt.prototype,"_attenuateIntersectionIterations",void 0);E([I("attenuateFacingCamera")],jt.prototype,"_attenuateFacingCamera",void 0);E([I("attenuateBackfaceReflection")],jt.prototype,"_attenuateBackfaceReflection",void 0);E([I("clipToFrustum")],jt.prototype,"_clipToFrustum",void 0);E([I("useFresnel")],jt.prototype,"_useFresnel",void 0);E([I("enableAutomaticThicknessComputation")],jt.prototype,"_enableAutomaticThicknessComputation",void 0);E([I("backfaceDepthTextureDownsample")],jt.prototype,"_backfaceDepthTextureDownsample",void 0);E([I("backfaceForceDepthWriteTransparentMeshes")],jt.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);E([I("isEnabled")],jt.prototype,"_isEnabled",void 0);E([I("inputTextureColorIsInGammaSpace")],jt.prototype,"_inputTextureColorIsInGammaSpace",void 0);E([I("generateOutputInGammaSpace")],jt.prototype,"_generateOutputInGammaSpace",void 0);E([I("debug")],jt.prototype,"_debug",void 0);V("BABYLON.SSRRenderingPipeline",jt);const RB="taaPixelShader",IB=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}
`;W.ShadersStore[RB]=IB;class uo extends qo{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():this._cameras!==null&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new vw(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){var s,r;const i=this._scene.getEngine();(s=this._ping)==null||s.dispose(),(r=this._pong)==null||r.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){var t;const e=[];(t=this._taaPostProcess)==null||t.updateEffect(e.join(`
`))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),this._cameras!==null&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new St(e,this.TAARenderEffect,()=>this._taaPostProcess,!0)),this._createPassPostProcess(),this.addEffect(new St(e,this.TAAPassEffect,()=>this._passPostProcess,!0)),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){var e,t;for(let i=0;i<this._cameras.length;i++){const s=this._cameras[i];(e=this._taaPostProcess)==null||e.dispose(s),(t=this._passPostProcess)==null||t.dispose(s),s.getProjectionMatrix(!0)}this._taaPostProcess=null,this._passPostProcess=null}_createTAAPostProcess(){this._taaPostProcess=new De("TAA","taa",{uniforms:["factor"],samplers:["historySampler"],size:1,engine:this._scene.getEngine(),textureType:this._textureType}),this._taaPostProcess.samples=this._msaaSamples,this._updateEffectDefines(),this._taaPostProcess.onActivateObservable.add(()=>{var t,i;const e=this._scene.activeCamera;if(((t=this._taaPostProcess)==null?void 0:t.width)!==this._ping.width||((i=this._taaPostProcess)==null?void 0:i.height)!==this._ping.height){const s=this._scene.getEngine();this._createPingPongTextures(s.getRenderWidth(),s.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===ve.PERSPECTIVE_CAMERA){const s=e.getProjectionMatrix();s.setRowFromFloats(2,this._hs.x,this._hs.y,s.m[10],s.m[11])}else{const s=e.getProjectionMatrix(!0);s.setRowFromFloats(3,this._hs.x+s.m[12],this._hs.y+s.m[13],s.m[14],s.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=this._pingpong^1,this._hs.next()}),this._taaPostProcess.onApplyObservable.add(e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t!=null&&t.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1})}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new An("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=_e.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return _e.Parse(()=>new uo(e._name,t,e._ratio),e,t,i)}}E([I("samples")],uo.prototype,"_samples",void 0);E([I("msaaSamples")],uo.prototype,"_msaaSamples",void 0);E([I()],uo.prototype,"factor",void 0);E([I()],uo.prototype,"disableOnCameraMove",void 0);E([I("isEnabled")],uo.prototype,"_isEnabled",void 0);V("BABYLON.TAARenderingPipeline",uo);const PB="tonemapPixelShader",MB=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;
#if defined(HABLE_TONEMAPPING)
const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;
#endif
float Luminance(vec3 c)
{return dot(c,vec3(0.22,0.707,0.071));}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec3 colour=texture2D(textureSampler,vUV).rgb;
#if defined(REINHARD_TONEMAPPING)
float lum=Luminance(colour.rgb); 
float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); 
colour*=scale/lum;
#elif defined(HABLE_TONEMAPPING)
colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;
#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)
colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;
#elif defined(PHOTOGRAPHIC_TONEMAPPING)
colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);
#endif
gl_FragColor=vec4(colour.rgb,1.0);}`;W.ShadersStore[PB]=MB;var LT;(function(a){a[a.Hable=0]="Hable",a[a.Reinhard=1]="Reinhard",a[a.HejiDawson=2]="HejiDawson",a[a.Photographic=3]="Photographic"})(LT||(LT={}));const DB="volumetricLightScatteringPixelShader",OB=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;}
vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));
#define CUSTOM_FRAGMENT_MAIN_END
}
`;W.ShadersStore[DB]=OB;const NB="volumetricLightScatteringPassVertexShader",FB=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
}
`;W.ShadersStore[NB]=FB;const wB="volumetricLightScatteringPassPixelShader",LB=`#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;
#endif
#if defined(ALPHATEST)
uniform sampler2D diffuseSampler;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#if defined(ALPHATEST)
vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4)
discard;
#endif
gl_FragColor=vec4(0.0,0.0,0.0,1.0);}
`;W.ShadersStore[wB]=LB;class Yr extends De{get useDiffuseColor(){return O.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){O.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,s,r=100,n=k.BILINEAR_SAMPLINGMODE,o,l,h){super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,o,l,"#define NUM_SAMPLES "+r),this._screenCoordinates=Z.Zero(),this.customMeshPosition=m.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,h=(i==null?void 0:i.getScene())??h??this._scene,o=h.getEngine(),this._viewPort=new Vr(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=s??Yr.CreateDefaultMesh("VolumetricLightScatteringMesh",h),this._createPass(h,t.passRatio||t),this.onActivate=c=>{this.isSupported||this.dispose(c),this.onActivate=null},this.onApplyObservable.add(c=>{this._updateMeshScreenCoordinates(h),c.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),c.setFloat("exposure",this.exposure),c.setFloat("decay",this.decay),c.setFloat("weight",this.weight),c.setFloat("density",this.density),c.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var u;const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=(u=i._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:u[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[y.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(y.UVKind)&&(n.push(y.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(y.UV2Kind)&&(n.push(y.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(y.MatricesIndicesKind),n.push(y.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),oo(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),h=l.defines,c=r.join(`
`);return h!==c&&l.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);t!==-1&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&this.includedMeshes.indexOf(e)===-1||this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new oi("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=k.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=k.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=l=>{var g;const h=l.getRenderingMesh(),c=l.getEffectiveMesh();if(this._meshExcluded(h))return;c._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const u=l.getMaterial();if(!u)return;const d=h.getScene(),f=d.getEngine();f.setState(u.backFaceCulling,void 0,void 0,void 0,u.cullBackFaces);const _=h._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(_.mustReturn)return;const p=f.getCaps().instancedArrays&&(_.visibleInstances[l._id]!==null||h.hasThinInstances);if(this._isReady(l,p)){const x=(g=c._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:g[f.currentRenderPassId];let T=l._getDrawWrapper();if(h===this.mesh&&!T&&(T=u._getDrawWrapper()),!T)return;const S=T.effect;if(f.enableEffect(T),p||h._bind(l,S,u.fillMode),h===this.mesh)u.bind(c.getWorldMatrix(),h);else if(x)x.bindForSubMesh(c.getWorldMatrix(),c,l);else{if(S.setMatrix("viewProjection",d.getTransformMatrix()),u&&u.needAlphaTesting()){const C=u.getAlphaTestTexture();S.setTexture("diffuseSampler",C),C&&S.setMatrix("diffuseMatrix",C.getTextureMatrix())}h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&S.setMatrices("mBones",h.skeleton.getTransformMatrices(h))}p&&h.hasThinInstances&&S.setMatrix("world",c.getWorldMatrix()),h._processRendering(c,l,S,ee.TriangleFillMode,_,p,(C,v)=>{C||S.setMatrix("world",v)})}};let n;const o=new xe(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{n=e.clearColor,e.clearColor=o}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=n}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,h,c)=>{if((c||h===0)&&l.subMeshes)for(let u=0;u<l.subMeshes.length;++u){const d=l.subMeshes[u],f=d.getMaterial(),_=d.getRenderingMesh();if(!f)continue;const p=_._getInstancesRenderList(d._id,!!d.getReplacementMesh()),g=i.getCaps().instancedArrays&&(p.visibleInstances[d._id]!==null||_.hasThinInstances);if(!this._isReady(d,g))return!1}return!0},this._volumetricLightScatteringRTT.customRenderFunction=(l,h,c,u)=>{const d=e.getEngine();let f;if(u.length){for(d.setColorWrite(!1),f=0;f<u.length;f++)r(u.data[f]);d.setColorWrite(!0)}for(f=0;f<l.length;f++)r(l.data[f]);for(f=0;f<h.length;f++)r(h.data[f]);if(c.length){for(f=0;f<c.length;f++){const p=c.data[f],g=p.getBoundingInfo();g&&e.activeCamera&&(p._alphaIndex=p.getMesh().alphaIndex,p._distanceToCamera=g.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}const _=c.data.slice(0,c.length);for(_.sort((p,g)=>p._alphaIndex>g._alphaIndex?1:p._alphaIndex<g._alphaIndex?-1:p._distanceToCamera<g._distanceToCamera?1:p._distanceToCamera>g._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f<_.length;f++)r(_[f]);d.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){const t=e.getTransformMatrix();let i;this.useCustomMeshPosition?i=this.customMeshPosition:this.attachedNode?i=this.attachedNode.position:i=this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;const s=m.Project(i,D.Identity(),t,this._viewPort);this._screenCoordinates.x=s.x/this._viewPort.width,this._screenCoordinates.y=s.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){const i=Im(e,{size:1},t);i.billboardMode=ut.BILLBOARDMODE_ALL;const s=new de(e+"Material",t);return s.emissiveColor=new q(1,1,1),i.material=s,i}}E([bs()],Yr.prototype,"customMeshPosition",void 0);E([I()],Yr.prototype,"useCustomMeshPosition",void 0);E([I()],Yr.prototype,"invert",void 0);E([Wu()],Yr.prototype,"mesh",void 0);E([I()],Yr.prototype,"excludedMeshes",void 0);E([I()],Yr.prototype,"includedMeshes",void 0);E([I()],Yr.prototype,"exposure",void 0);E([I()],Yr.prototype,"decay",void 0);E([I()],Yr.prototype,"weight",void 0);E([I()],Yr.prototype,"density",void 0);V("BABYLON.VolumetricLightScatteringPostProcess",Yr);const BB="screenSpaceCurvaturePixelShader",UB=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley;
#ifndef CURVATURE_OFFSET
#define CURVATURE_OFFSET 1
#endif
float curvature_soft_clamp(float curvature,float control)
{if (curvature<0.5/control)
return curvature*(1.0-curvature*control);return 0.25/control;}
float calculate_curvature(ivec2 texel,float ridge,float valley)
{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0)
return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;W.ShadersStore[BB]=UB;class od extends De{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,s,r,n,o,l=0,h=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,s,r,n,o,void 0,l,void 0,null,h),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?(this._geometryBufferRenderer.generateNormalsInWorldSpace&&O.Error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"),this.onApply=c=>{c.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),c.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const u=this._geometryBufferRenderer.getGBuffer().textures[1];c.setTexture("normalSampler",u)}):O.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=Ae.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,s){return _e.Parse(()=>new od(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}E([I()],od.prototype,"ridge",void 0);E([I()],od.prototype,"valley",void 0);V("BABYLON.ScreenSpaceCurvaturePostProcess",od);const VB="boundingBoxRendererFragmentDeclaration",kB=`uniform vec4 color;
`;W.IncludesShadersStore[VB]=kB;const GB="boundingBoxRendererUboDeclaration",zB=`#ifdef WEBGL2
uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#else
layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};
#endif
`;W.IncludesShadersStore[GB]=zB;const WB="boundingBoxRendererPixelShader",HB=`#include<__decl__boundingBoxRendererFragment>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[WB]=HB;const XB="boundingBoxRendererVertexDeclaration",YB=`uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
`;W.IncludesShadersStore[XB]=YB;const $B="boundingBoxRendererVertexShader",KB=`attribute vec3 position;
#include<__decl__boundingBoxRendererVertex>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec4 worldPos=world*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}
`;W.ShadersStore[$B]=KB;Object.defineProperty(Ee.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(a){this._forceShowBoundingBoxes=a,a&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Ee.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new jB(this)),this._boundingBoxRenderer};Object.defineProperty(ut.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(a){this._showBoundingBox=a,a&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class jB{constructor(e){this.name=he.NAME_BOUNDINGBOXRENDERER,this.frontColor=new q(1,1,1),this.backColor=new q(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new G,this.onAfterBoxRenderingObservable=new G,this.onResourcesReadyObservable=new G,this.enabled=!0,this.renderList=new Wi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new be(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new be(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(he.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(he.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(he.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(he.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Qs("colorShader",this.scene,"boundingBoxRenderer",{attributes:[y.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Qs("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[y.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=Xm({size:1});this._vertexBuffers[y.PositionKind]=new y(e,t.positions,y.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[y.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s<this.renderList.length;s++){const r=this.renderList.data[s];if(r._tag!==e)continue;this._createWrappersForBoundingBox(r),this.onBeforeBoxRenderingObservable.notifyObservers(r);const n=r.minimum,l=r.maximum.subtract(n),h=n.add(l.scale(.5)),c=D.Scaling(l.x,l.y,l.z).multiply(D.Translation(h.x,h.y,h.z)).multiply(r.getWorldMatrix()),u=t.useReverseDepthBuffer;if(this.showBackLines){const f=r._drawWrapperBack??this._colorShader._getDrawWrapper();this._colorShader._preBind(f),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),u?t.setDepthFunctionToLessOrEqual():t.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(f.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",c),this._uniformBufferBack.updateMatrix("viewProjection",i),this._uniformBufferBack.update(),t.drawElementsType(ee.LineListDrawMode,0,24)}const d=r._drawWrapperFront??this._colorShader._getDrawWrapper();this._colorShader._preBind(d),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),u?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(d.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",i),this._uniformBufferFront.update(),t.drawElementsType(ee.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(r)}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){const t=this.scene.getEngine();e._drawWrapperFront=new Bi(t),e._drawWrapperBack=new Bi(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){const t=this.scene.getEngine();this._renderPassIdForOcclusionQuery===void 0&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));const i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();const s=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,s)||!e.hasBoundingInfo){t.currentRenderPassId=i;return}this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));const r=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);const n=e.getBoundingInfo().boundingBox,o=n.minimum,h=n.maximum.subtract(o),c=o.add(h.scale(.5)),u=D.Scaling(h.x,h.y,h.z).multiply(D.Translation(c.x,c.y,c.z)).multiply(n.getWorldMatrix()),d=s._drawWrapper;this._colorShaderForOcclusionQuery._preBind(d),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,d.effect),r?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(d.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(ee.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}dispose(){if(this._renderPassIdForOcclusionQuery!==void 0&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();const e=this._vertexBuffers[y.PositionKind];e&&(e.dispose(),this._vertexBuffers[y.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}}Ee.prototype.enableDepthRenderer=function(a,e=!1,t=!1,i=3,s=!1){if(a=a||this.activeCamera,!a)throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[a.id]){const r=!!this.getEngine().getCaps().textureFloatRender;let n=0;this.getEngine().getCaps().textureHalfFloatRender&&(!t||!r)?n=2:r?n=1:n=0,this._depthRenderer[a.id]=new Yo(this,n,a,e,i,s)}return this._depthRenderer[a.id]};Ee.prototype.disableDepthRenderer=function(a){a=a||this.activeCamera,!(!a||!this._depthRenderer||!this._depthRenderer[a.id])&&this._depthRenderer[a.id].dispose()};class qB{constructor(e){this.name=he.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(he.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(he.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(const e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(const t in this.scene._depthRenderer){const i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}}Yo._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_DEPTHRENDERER);e||(e=new qB(a),a._addComponent(e))};const QB="oitFinalPixelShader",ZB=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(
frontColor.rgb+alphaMultiplier*backColor.rgb,
frontColor.a+backColor.a
);}`;W.ShadersStore[QB]=ZB;const JB="oitBackBlendPixelShader",e2=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { 
discard;}}`;W.ShadersStore[JB]=e2;class t2{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class ha{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){this._excludedMeshes.indexOf(e.uniqueId)===-1&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);t!==-1&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Wi(10),this._excludedSubMeshes=new Wi(10),this._excludedMeshes=[],this._colorCache=[new xe(ha._DEPTH_CLEAR_VALUE,ha._DEPTH_CLEAR_VALUE,0,0),new xe(-ha._MIN_DEPTH,ha._MAX_DEPTH,0,0),new xe(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){O.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i<this._layoutCacheFormat.length;++i)this._layoutCache[i]=this._engine.buildTextureLayout(this._layoutCacheFormat[i]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new t2,this._createTextures(),this._createEffects()}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_createTextures(){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new vo("depthPeelingDepth0MRT",e,3,this._scene,void 0,["depthPeelingDepth0MRT_depth","depthPeelingDepth0MRT_frontColor","depthPeelingDepth0MRT_backColor"]),new vo("depthPeelingDepth1MRT",e,3,this._scene,void 0,["depthPeelingDepth1MRT_depth","depthPeelingDepth1MRT_frontColor","depthPeelingDepth1MRT_backColor"])],this._colorMrts=[new vo("depthPeelingColor0MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor0MRT_frontColor","depthPeelingColor0MRT_backColor"]),new vo("depthPeelingColor1MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor1MRT_frontColor","depthPeelingColor1MRT_backColor"])],this._blendBackMrt=new vo("depthPeelingBackMRT",e,1,this._scene,{generateDepthBuffer:!1},["depthPeelingBackMRT_blendBack"]),this._outputRT=new oi("depthPeelingOutputRTT",e,this._scene,!1);const t=[{format:7,samplingMode:1,type:this._engine.getCaps().textureFloatLinearFiltering?1:2,label:"DepthPeelingRenderer-DepthTexture"},{format:5,samplingMode:1,type:2,label:"DepthPeelingRenderer-ColorTexture"}];for(let i=0;i<2;i++){const s=this._engine._createInternalTexture(e,t[0],!1),r=this._engine._createInternalTexture(e,t[1],!1),n=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(s,0),this._depthMrts[i].setInternalTexture(r,1),this._depthMrts[i].setInternalTexture(n,2),this._colorMrts[i].setInternalTexture(r,0),this._colorMrts[i].setInternalTexture(n,1),this._thinTextures.push(new Ao(s),new Ao(r),new Ao(n))}}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)e!==6&&this._thinTextures[e].dispose();for(let e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_updateTextures(){return(this._depthMrts[0].getSize().width!==this._engine.getRenderWidth()||this._depthMrts[0].getSize().height!==this._engine.getRenderHeight())&&(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()}_updateTextureReferences(){var s;const e=this._scene.prePassRenderer;if(!e)return!1;const t=e.getIndex(4),i=(s=e.defaultRT.textures)!=null&&s.length?e.defaultRT.textures[t].getInternalTexture():null;return i?(this._blendBackTexture!==i&&(this._blendBackTexture=i,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new Ao(this._blendBackTexture),e.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget)),!0):!1}_createEffects(){this._blendBackEffectWrapper=new da({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new da({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new da({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new Nf(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[this._currentPingPongState*3]),e.setTexture("oitFrontColorSampler",this._thinTextures[this._currentPingPongState*3+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i<e.length;i++){const s=e.data[i].getMaterial();let r=!0,n=!1;const o=e.data[i];let l,h=!1;if(this._useRenderPasses&&(l=o._getDrawWrapper(),h=!l),s&&(r=s.allowShaderHotSwapping,n=s.backFaceCulling,s.allowShaderHotSwapping=!1,s.backFaceCulling=!1),o.render(!1),h&&(l=o._getDrawWrapper(),l.materialContext)){let c=t[l.materialContext.uniqueId];c||(c=t[l.materialContext.uniqueId]=this._engine.createMaterialContext()),o._getDrawWrapper().materialContext=c}s&&(s.allowShaderHotSwapping=r,s.backFaceCulling=n)}}_finalCompose(e){var i;((i=this._scene.prePassRenderer)==null?void 0:i.setCustomOutput(this._outputRT))?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(0),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[e*3+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)}isReady(){return this._blendBackEffectWrapper.effect.isReady()&&this._blendBackEffectWrapperPingPong.effect.isReady()&&this._finalEffectWrapper.effect.isReady()&&this._updateTextures()}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this.isReady())return this._excludedSubMeshes;this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport);for(let r=0;r<e.length;r++){const n=e.data[r],o=n.getMaterial(),l=o&&n.getRenderingMesh()._getRenderingFillMode(o.fillMode);o&&(l===ee.TriangleFanDrawMode||l===ee.TriangleFillMode||l===ee.TriangleStripDrawMode)&&this._excludedMeshes.indexOf(n.getMesh().uniqueId)===-1?this._candidateSubMeshes.push(n):this._excludedSubMeshes.push(n)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;const t=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0,s=0;for(let r=0;r<this._passCount;r++){i=r%2,s=1-i,this._currentPingPongState=i,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[r+1]),this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport),this._engine.bindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindFramebuffer(this._colorMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[s].renderTarget),this._engine.bindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[s].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(0),this._engine.setAlphaMode(17),this._engine.applyStates();const n=s===0||!this._useRenderPasses?this._blendBackEffectWrapper:this._blendBackEffectWrapperPingPong;this._engine.enableEffect(n._drawWrapper),n.effect.setTexture("uBackColor",this._thinTextures[s*3+2]),this._effectRenderer.render(n),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(s),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}}ha._DEPTH_CLEAR_VALUE=-99999;ha._MIN_DEPTH=0;ha._MAX_DEPTH=1;Object.defineProperty(Ee.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){let a=this._getComponent(he.NAME_DEPTHPEELINGRENDERER);a||(a=new i2(this),this._addComponent(a))}return this._depthPeelingRenderer},set:function(a){this._depthPeelingRenderer=a},enumerable:!0,configurable:!0});Object.defineProperty(Ee.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(a){var e;this._useOrderIndependentTransparency!==a&&(this._useOrderIndependentTransparency=a,this.markAllMaterialsAsDirty(63),(e=this.prePassRenderer)==null||e.markAsDirty())},enumerable:!0,configurable:!0});class i2{constructor(e){this.name=he.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new ha(e)}register(){}rebuild(){}dispose(){var e;(e=this.scene.depthPeelingRenderer)==null||e.dispose(),this.scene.depthPeelingRenderer=null}}const s2="linePixelShader",r2=`#include<clipPlaneFragmentDeclaration>
uniform vec4 color;
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<logDepthFragment>
#include<clipPlaneFragment>
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[s2]=r2;const n2="lineVertexShader",a2=`#include<instancesDeclaration>
#include<clipPlaneVertexDeclaration>
attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#include<instancesVertex>
mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
vec4 worldPos=finalWorld*vec4(position,1.0);
#include<clipPlaneVertex>
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[n2]=a2;ut.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};ut.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new p_(this,a,e,!0,t),this};Object.defineProperty(ut.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});to.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new l2(this,a,e),this};_S.prototype.enableEdgesRendering=function(a=.95,e=!1){return to.prototype.enableEdgesRendering.apply(this,arguments),this};class o2{constructor(){this.edges=[],this.edgesConnectedCount=0}}class p_{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new Qs("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Wi(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Bi(e.getEngine())),this._prepareRessources(),s&&((r==null?void 0:r.useAlternateEdgeFinder)??!0?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=p_._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[y.PositionKind];e&&e._rebuild(),e=this._buffers[y.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var t;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[y.PositionKind];e&&(e.dispose(),this._buffers[y.PositionKind]=null),e=this._buffers[y.NormalKind],e&&(e.dispose(),this._buffers[y.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)?1:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)?2:-1}_checkEdge(e,t,i,s,r){let n;t===void 0?n=!0:n=m.Dot(i[e],i[t])<this._epsilon,n&&this.createLine(s,r,this._linesPositions.length/3)}createLine(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)}_tessellateTriangle(e,t,i,s){const r=(P,L,w)=>{w>=0&&L.push(w);for(let $=0;$<P.length;++$)L.push(P[$][0])};let n=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let P=0;P<3;++P)P===n?e[P].sort((L,w)=>L[1]<w[1]?-1:L[1]>w[1]?1:0):e[P].sort((L,w)=>L[1]>w[1]?-1:L[1]<w[1]?1:0);const o=[],l=[];r(e[n],o,-1);const h=o.length;for(let P=n+2;P>=n+1;--P)r(e[P%3],l,P!==n+2?s[i[t+(P+1)%3]]:-1);const c=l.length,u=0,d=0;i.push(s[i[t+n]],o[0],l[0]),i.push(s[i[t+(n+1)%3]],l[c-1],o[h-1]);const f=h<=c,_=f?h:c,p=f?c:h,g=f?h-1:c-1,x=f?0:1;let T=h+c-2,S=f?u:d,C=f?d:u;const v=f?o:l,b=f?l:o;let A=0;for(;T-- >0;){x?i.push(v[S],b[C]):i.push(b[C],v[S]),A+=_;let P;A>=p&&S<g?(P=v[++S],A-=p):P=b[++C],i.push(P)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var h,c,u,d,f,_;const e=this._source.getVerticesData(y.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=((h=this._options)==null?void 0:h.useFastVertexMerger)??!0,s=i?Math.round(-Math.log(((c=this._options)==null?void 0:c.epsilonVertexMerge)??1e-6)/Math.log(10)):((u=this._options)==null?void 0:u.epsilonVertexMerge)??1e-6,r=[],n=[];if(i){const p={};for(let g=0;g<e.length;g+=3){const x=e[g+0],T=e[g+1],S=e[g+2],C=x.toFixed(s)+"|"+T.toFixed(s)+"|"+S.toFixed(s);if(p[C]!==void 0)r.push(p[C]);else{const v=g/3;p[C]=v,r.push(v),n.push(v)}}}else for(let p=0;p<e.length;p+=3){const g=e[p+0],x=e[p+1],T=e[p+2];let S=!1;for(let C=0;C<p&&!S;C+=3){const v=e[C+0],b=e[C+1],A=e[C+2];if(Math.abs(g-v)<s&&Math.abs(x-b)<s&&Math.abs(T-A)<s){r.push(C/3),S=!0;break}}S||(r.push(p/3),n.push(p/3))}if((d=this._options)!=null&&d.applyTessellation){const p=((f=this._options)==null?void 0:f.epsilonVertexAligned)??1e-6,g=[];for(let x=0;x<t.length;x+=3){let T;for(let S=0;S<3;++S){const C=r[t[x+S]],v=r[t[x+(S+1)%3]],b=r[t[x+(S+2)%3]];if(C===v)continue;const A=e[C*3+0],P=e[C*3+1],L=e[C*3+2],w=e[v*3+0],$=e[v*3+1],J=e[v*3+2],ne=Math.sqrt((w-A)*(w-A)+($-P)*($-P)+(J-L)*(J-L));for(let oe=0;oe<n.length-1;oe++){const re=n[oe];if(re===C||re===v||re===b)continue;const ce=e[re*3+0],Se=e[re*3+1],Ce=e[re*3+2],ae=Math.sqrt((ce-A)*(ce-A)+(Se-P)*(Se-P)+(Ce-L)*(Ce-L)),ie=Math.sqrt((ce-w)*(ce-w)+(Se-$)*(Se-$)+(Ce-J)*(Ce-J));Math.abs(ae+ie-ne)<p&&(T||(T={index:x,edgesPoints:[[],[],[]]},g.push(T)),T.edgesPoints[S].push([re,ae]))}}}for(let x=0;x<g.length;++x){const T=g[x];this._tessellateTriangle(T.edgesPoints,T.index,t,r)}g.length=0}const o={};for(let p=0;p<t.length;p+=3){let g;for(let x=0;x<3;++x){let T=r[t[p+x]],S=r[t[p+(x+1)%3]];const C=r[t[p+(x+2)%3]];if(T===S||(T===C||S===C)&&((_=this._options)!=null&&_.removeDegeneratedTriangles))continue;if(U.Vector3[0].copyFromFloats(e[T*3+0],e[T*3+1],e[T*3+2]),U.Vector3[1].copyFromFloats(e[S*3+0],e[S*3+1],e[S*3+2]),U.Vector3[2].copyFromFloats(e[C*3+0],e[C*3+1],e[C*3+2]),g||(U.Vector3[1].subtractToRef(U.Vector3[0],U.Vector3[3]),U.Vector3[2].subtractToRef(U.Vector3[1],U.Vector3[4]),g=m.Cross(U.Vector3[3],U.Vector3[4]),g.normalize()),T>S){const A=T;T=S,S=A}const v=T+"_"+S,b=o[v];b?b.done||(m.Dot(g,b.normal)<this._epsilon&&this.createLine(U.Vector3[0],U.Vector3[1],this._linesPositions.length/3),b.done=!0):o[v]={normal:g,done:!1,index:p,i:x}}}for(const p in o){const g=o[p];if(!g.done){const x=r[t[g.index+g.i]],T=r[t[g.index+(g.i+1)%3]];U.Vector3[0].copyFromFloats(e[x*3+0],e[x*3+1],e[x*3+2]),U.Vector3[1].copyFromFloats(e[T*3+0],e[T*3+1],e[T*3+2]),this.createLine(U.Vector3[0],U.Vector3[1],this._linesPositions.length/3)}}const l=this._source.getScene().getEngine();this._buffers[y.PositionKind]=new y(l,this._linesPositions,y.PositionKind,!1),this._buffers[y.NormalKind]=new y(l,this._linesNormals,y.NormalKind,!1,!1,4),this._buffersForInstances[y.PositionKind]=this._buffers[y.PositionKind],this._buffersForInstances[y.NormalKind]=this._buffers[y.NormalKind],this._ib=l.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}_generateEdgesLines(){const e=this._source.getVerticesData(y.PositionKind),t=this._source.getIndices();if(!t||!e)return;const i=[],s=[];let r,n;for(r=0;r<t.length;r+=3){n=new o2;const l=t[r],h=t[r+1],c=t[r+2];n.p0=new m(e[l*3],e[l*3+1],e[l*3+2]),n.p1=new m(e[h*3],e[h*3+1],e[h*3+2]),n.p2=new m(e[c*3],e[c*3+1],e[c*3+2]);const u=m.Cross(n.p1.subtract(n.p0),n.p2.subtract(n.p1));u.normalize(),s.push(u),i.push(n)}for(r=0;r<i.length;r++){n=i[r];for(let l=r+1;l<i.length;l++){const h=i[l];if(n.edgesConnectedCount===3)break;if(h.edgesConnectedCount===3)continue;const c=t[l*3],u=t[l*3+1],d=t[l*3+2];for(let f=0;f<3;f++){let _=0;if(n.edges[f]===void 0){switch(f){case 0:this._checkVerticesInsteadOfIndices?_=this._processEdgeForAdjacenciesWithVertices(n.p0,n.p1,h.p0,h.p1,h.p2):_=this._processEdgeForAdjacencies(t[r*3],t[r*3+1],c,u,d);break;case 1:this._checkVerticesInsteadOfIndices?_=this._processEdgeForAdjacenciesWithVertices(n.p1,n.p2,h.p0,h.p1,h.p2):_=this._processEdgeForAdjacencies(t[r*3+1],t[r*3+2],c,u,d);break;case 2:this._checkVerticesInsteadOfIndices?_=this._processEdgeForAdjacenciesWithVertices(n.p2,n.p0,h.p0,h.p1,h.p2):_=this._processEdgeForAdjacencies(t[r*3+2],t[r*3],c,u,d);break}if(_!==-1&&(n.edges[f]=l,h.edges[_]=r,n.edgesConnectedCount++,h.edgesConnectedCount++,n.edgesConnectedCount===3))break}}}}for(r=0;r<i.length;r++){const l=i[r];this._checkEdge(r,l.edges[0],s,l.p0,l.p1),this._checkEdge(r,l.edges[1],s,l.p1,l.p2),this._checkEdge(r,l.edges[2],s,l.p2,l.p0)}const o=this._source.getScene().getEngine();this._buffers[y.PositionKind]=new y(o,this._linesPositions,y.PositionKind,!1),this._buffers[y.NormalKind]=new y(o,this._linesNormals,y.NormalKind,!1,!1,4),this._buffersForInstances[y.PositionKind]=this._buffers[y.PositionKind],this._buffersForInstances[y.NormalKind]=this._buffers[y.NormalKind],this._ib=o.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}isReady(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const o=this._source._instanceDataStorage;if(r=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let h=0;h<r;++h)this.customInstances.data[h].copyToArray(o.instancesData,l),l+=16;o.instancesBuffer.updateDirectly(o.instancesData,0,r)}}else r=this._source.thinInstanceCount;const n=e.getEngine();this._lineShader._preBind(),this._source.edgesColor.a!==1?n.setAlphaMode(2):n.setAlphaMode(0),n.bindBuffers(s?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===ve.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",n.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),n.drawElementsType(ee.TriangleFillMode,0,this._indicesCount,r),this._lineShader.unbind(),s&&n.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}}class l2 extends p_{constructor(e,t=.95,i=!1){super(e,t,i,!1),this._generateEdgesLines()}_generateEdgesLines(){const e=this._source.getVerticesData(y.PositionKind),t=this._source.getIndices();if(!t||!e)return;const i=U.Vector3[0],s=U.Vector3[1],r=t.length-1;for(let o=0,l=0;o<r;o+=2,l+=4)m.FromArrayToRef(e,3*t[o],i),m.FromArrayToRef(e,3*t[o+1],s),this.createLine(i,s,l);const n=this._source.getScene().getEngine();this._buffers[y.PositionKind]=new y(n,this._linesPositions,y.PositionKind,!1),this._buffers[y.NormalKind]=new y(n,this._linesNormals,y.NormalKind,!1,!1,4),this._ib=n.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}}class h2 extends vo{constructor(e,t,i,s,r,n){super(e,i,s,r,n),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new Dg("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){const e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),s=this.getRenderHeight();(i!==e||s!==t)&&(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){const e=this._scene;if(super.dispose(),e&&e.prePassRenderer){const t=e.prePassRenderer.renderTargets.indexOf(this);t!==-1&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}}class Is{get generateNormalsInWorldSpace(){return this._generateNormalsInWorldSpace}set generateNormalsInWorldSpace(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())}getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){var t;e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=((t=this._scene.activeCamera)==null?void 0:t.renderPassId)??this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer){this.doNotUseGeometryRendererFallback=!0;return}this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new xe(0,0,0,0),this._clearDepthColor=new xe(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2);for(let i=0;i<Is.TextureFormats.length;++i){const s=Is.TextureFormats[i].format;Is.TextureFormats[i].type===1&&(Is.TextureFormats[5].type=t,(s===6||s===7||s===5)&&!this._engine._caps.supportFloatTexturesResolve&&(Is.TextureFormats[5].type=2))}Is._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}_createRenderTarget(e,t){const i=new h2(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:0,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),this._enabled&&this._update(),i}get isSupported(){return this._scene.getEngine().getCaps().drawBuffersExtension}bindAttachmentsForEffect(e,t){const i=t.getMaterial(),s=i&&i.isPrePassCapable,r=i&&this.excludedMaterials.indexOf(i)!==-1;this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&s&&!r?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!r&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))}_reinitializeAttachments(){const e=[],t=[!1],i=[!1],s=[!0];for(let r=0;r<this.mrtCount;r++)e.push(!0),r>0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[r]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;e<Is.TextureFormats.length;e++)this._textureIndices[Is.TextureFormats[e].purpose]=-1;this._textureIndices[4]=0,this._mrtLayout=[4],this._mrtTypes=[Is.TextureFormats[4].type],this._mrtFormats=[Is.TextureFormats[4].format],this._mrtNames=[Is.TextureFormats[4].name],this.mrtCount=1}_updateGeometryBufferLayout(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();const e=[];for(let i=0;i<this._mrtLayout.length;i++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());const t=[{prePassConstant:5,geometryBufferConstant:wt.DEPTH_TEXTURE_TYPE},{prePassConstant:6,geometryBufferConstant:wt.NORMAL_TEXTURE_TYPE},{prePassConstant:1,geometryBufferConstant:wt.POSITION_TEXTURE_TYPE},{prePassConstant:3,geometryBufferConstant:wt.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:2,geometryBufferConstant:wt.VELOCITY_TEXTURE_TYPE}];for(let i=0;i<t.length;i++){const s=this._mrtLayout.indexOf(t[i].prePassConstant);s!==-1&&(this._geometryBuffer._forceTextureType(t[i].geometryBufferConstant,s),e[s]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}}restoreAttachments(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())}_beforeDraw(e,t,i){this._isDirty&&this._update(),!(!this._enabled||!this._currentTarget.enabled)&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))}_prepareFrame(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()}setCustomOutput(e){const t=this._postProcessesSourceForThisPass[0];return t?(t.inputTexture=e.renderTarget,!0):!1}_renderPostProcesses(e,t){var n;const i=this._postProcessesSourceForThisPass[0],s=i?i.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null;let r=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(r=r.concat([this._currentTarget.imageProcessingPostProcess])),r.length&&(this._scene.postProcessManager._prepareFrame((n=this._currentTarget.renderTarget)==null?void 0:n.texture,r),this._scene.postProcessManager.directRender(r,s,!1,t))}_afterDraw(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))}_clear(){this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))}_bindFrameBuffer(){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();const e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}}_setEnabled(e){this._enabled=e}_setRenderTargetEnabled(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)}addEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e}getEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e)return this._effectConfigurations[t];return null}_enable(){const e=this.mrtCount;for(let t=0;t<this._effectConfigurations.length;t++)this._effectConfigurations[t].enabled&&this._enableTextures(this._effectConfigurations[t].texturesRequired);for(let t=0;t<this.renderTargets.length;t++){(this.mrtCount!==e||this.renderTargets[t].count!==this.mrtCount)&&this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(let i=0;i<this._effectConfigurations.length;i++)this._effectConfigurations[i].enabled&&(!this._effectConfigurations[i].postProcess&&this._effectConfigurations[i].createPostProcess&&this._effectConfigurations[i].createPostProcess(),this._effectConfigurations[i].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[i].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()}_disable(){this._setEnabled(!1);for(let e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);this._resetLayout();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1}_getPostProcessesSource(e,t){if(t)return t._postProcesses;if(e.renderTargetTexture)if(e.renderTargetTexture.useCameraPostProcesses){const i=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return i?i._postProcesses:[]}else return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[];else return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[]}_setupOutputForThisPass(e,t){const i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&this._scene.activeCameras.indexOf(t)!==0;this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter(l=>l!=null),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1}_hasImageProcessing(e){var i;let t=!1;if(e){for(let s=0;s<e.length;s++)if(((i=e[s])==null?void 0:i.getClassName())==="ImageProcessingPostProcess"){t=!0;break}}return t}_getFirstPostProcess(e){for(let t=0;t<e.length;t++)if(e[t]!==null)return e[t];return null}markAsDirty(){this._isDirty=!0}_enableTextures(e){this._scene.needsPreviousWorldMatrices=!1;for(let t=0;t<e.length;t++){const i=e[t];this._textureIndices[i]===-1&&(this._textureIndices[i]=this._mrtLayout.length,this._mrtLayout.push(i),this._mrtTypes.push(Is.TextureFormats[i].type),this._mrtFormats.push(Is.TextureFormats[i].format),this._mrtNames.push(Is.TextureFormats[i].name),this.mrtCount++),i===2&&(this._scene.needsPreviousWorldMatrices=!0)}}update(){this._isDirty&&this._update()}_update(){this._disable();let e=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),e=!0);for(let i=0;i<this._scene.materials.length;i++)this._scene.materials[i].setPrePassRenderer(this)&&(e=!0);e&&this._setRenderTargetEnabled(this.defaultRT,!0);let t;for(let i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)t=this._getPostProcessesSource(this.renderTargets[i]);else{const s=this._scene.activeCamera;if(!s)continue;t=s._postProcesses}if(t&&(t=t.filter(s=>s!=null),t)){for(let s=0;s<t.length;s++)t[s].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),e=!0);this._hasImageProcessing(t)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,e&&this._enable()}_markAllMaterialsAsPrePassDirty(){const e=this._scene.materials;for(let t=0;t<e.length;t++)e[t].markAsDirty(ee.PrePassDirtyFlag)}dispose(){for(let e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()}}Is._SceneComponentInitialization=a=>{throw Ge("PrePassRendererSceneComponent")};Is.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}];Object.defineProperty(Ee.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(a){a&&a.isSupported&&(this._prePassRenderer=a)},enumerable:!0,configurable:!0});Ee.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new Is(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,O.Error(`PrePassRenderer needs WebGL 2 support.
Maybe you tried to use the following features that need the PrePassRenderer :
 + Subsurface Scattering`)),this._prePassRenderer)};Ee.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class c2{constructor(e){this.name=he.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(he.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(he.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(he.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(he.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(he.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(he.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}Is._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_PREPASSRENDERER);e||(e=new c2(a),a._addComponent(e))};const u2="fibonacci",d2=`#define rcp(x) 1./x
#define GOLDEN_RATIO 1.618033988749895
#define TWO_PI 6.2831855
vec2 Golden2dSeq(int i,float n)
{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}
vec2 SampleDiskGolden(int i,int sampleCount)
{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;W.IncludesShadersStore[u2]=d2;const f2="diffusionProfile",_2="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";W.IncludesShadersStore[f2]=_2;const p2="subSurfaceScatteringPixelShader",m2=`#include<fibonacci>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<diffusionProfile>
varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;
#define rcp(x) 1./x
#define Sq(x) x*x
#define SSS_BILATERAL_FILTER true
vec3 EvalBurleyDiffusionProfile(float r,vec3 S)
{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); 
vec3 expSum=exp_13*(1.+exp_13*exp_13); 
return (S*rcp(8.*PI))*expSum; }
vec2 SampleBurleyDiffusionProfile(float u,float rcpS)
{u=1.-u; 
float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); 
float p=(g*n)*n; 
float c=1.+p+n; 
float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); 
float x=(3./LOG2_E)*log2(c)-d; 
float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; 
return vec2(r,rcpPdf);}
vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)
{
#ifndef SSS_BILATERAL_FILTER
z=0.;
#endif
float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;
#if SSS_CLAMP_ARTIFACT
return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);
#else
return EvalBurleyDiffusionProfile(r,S)*area;
#endif
}
void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,
float phase,inout vec3 totalIrradiance,inout vec3 totalWeight)
{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; 
float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; 
vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; 
float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))
{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}
else
{}}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)
{centerDepth=texture2D(depthSampler,vUV).r;}
if (!passedStencilTest) { 
gl_FragColor=inputColor;return;}
float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; 
vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; 
float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)
{
#ifdef DEBUG_SSS_SAMPLES
vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;
#endif
gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}
#ifdef DEBUG_SSS_SAMPLES
vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;
#endif
float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); 
vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++)
{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm,
phase,totalIrradiance,totalWeight);}
totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;W.ShadersStore[p2]=m2;class g2 extends De{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,s=null,r,n,o,l=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,s,r||k.BILINEAR_SAMPLINGMODE,n,o,null,l,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add(h=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration){O.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}const c=this.texelSize;h.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),h.setFloat2("texelSize",c.x,c.y),h.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),h.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),h.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),h.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),h.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),h.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),h.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class ld{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=he.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new q(1,1,1)),this._scene=e,ld._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return O.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[t*3]===e.r&&this._ssDiffusionS[t*3+1]===e.g&&this._ssDiffusionS[t*3+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1}createPostProcess(){return this.postProcess=new g2("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess}clearAllDiffusionProfiles(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]}dispose(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()}getDiffusionProfileParameters(e){const i=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,i)}_sampleBurleyDiffusionProfile(e,t){e=1-e;const i=1+4*e*(2*e+Math.sqrt(1+4*e*e)),s=Math.pow(i,-1/3),n=1+i*s*s+s;return 3*Math.log(n/(4*e))*t}}ld._SceneComponentInitialization=a=>{throw Ge("SubSurfaceSceneComponent")};wi.AddParser(he.NAME_SUBSURFACE,(a,e)=>{if(a.ssDiffusionProfileColors!==void 0&&a.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=a.ssDiffusionProfileColors.length;t<i;t++){const s=a.ssDiffusionProfileColors[t];e.subSurfaceConfiguration.addDiffusionProfile(new q(s.r,s.g,s.b))}});Object.defineProperty(Ee.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(a){a&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=a)},enumerable:!0,configurable:!0});Ee.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;const a=this.enablePrePassRenderer();return a?(this._subSurfaceConfiguration=new ld(this),a.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null};Ee.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};class x2{constructor(e){this.name=he.NAME_PREPASSRENDERER,this.scene=e}register(){}serialize(e){if(!this.scene.subSurfaceConfiguration)return;const t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(let i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}addFromContainer(){}removeFromContainer(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()}rebuild(){}dispose(){}}ld._SceneComponentInitialization=a=>{let e=a._getComponent(he.NAME_SUBSURFACE);e||(e=new x2(a),a._addComponent(e))};const T2="outlinePixelShader",E2=`#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
uniform vec4 color;
#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#include<logDepthFragment>
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[T2]=E2;const S2="outlineVertexShader",C2=`attribute vec3 position;attribute vec3 normal;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
uniform float offset;
#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef ALPHATEST
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;vec3 normalUpdated=normal;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
vec3 offsetPosition=positionUpdated+(normalUpdated*offset);
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;
#ifdef ALPHATEST
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
#include<logDepthVertex>
}
`;W.ShadersStore[S2]=C2;Ee.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new Uu(this)),this._outlineRenderer};Object.defineProperty(z.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOutline=a},enumerable:!0,configurable:!0});Object.defineProperty(z.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOverlay=a},enumerable:!0,configurable:!0});class Uu{constructor(e){this.name=he.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId(`Outline Renderer (${t})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(he.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(he.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,s){s=s??this._passIdForDrawWrapper[0];const r=this.scene,n=r.getEngine(),o=n.getCaps().instancedArrays&&(t.visibleInstances[e._id]!==null&&t.visibleInstances[e._id]!==void 0||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,o,s))return;const l=e.getMesh(),h=l._internalAbstractMeshDataInfo._actAsRegularMesh?l:null,c=e.getRenderingMesh(),u=h||c,d=e.getMaterial();if(!d||!r.activeCamera)return;const f=e._getDrawWrapper(s),_=Bi.GetEffect(f);if(n.enableEffect(f),d.useLogarithmicDepth&&_.setFloat("logarithmicDepthConstant",2/(Math.log(r.activeCamera.maxZ+1)/Math.LN2)),_.setFloat("offset",i?0:c.outlineWidth),_.setColor4("color",i?c.overlayColor:c.outlineColor,i?c.overlayAlpha:d.alpha),_.setMatrix("viewProjection",r.getTransformMatrix()),_.setMatrix("world",u.getWorldMatrix()),c.useBones&&c.computeBonesUsingShaders&&c.skeleton&&_.setMatrices("mBones",c.skeleton.getTransformMatrices(c)),c.morphTargetManager&&c.morphTargetManager.isUsingTextureForTargets&&c.morphTargetManager._bind(_),Sa(c,_),o||c._bind(e,_,d.fillMode),d&&d.needAlphaTesting()){const p=d.getAlphaTestTexture();p&&(_.setTexture("diffuseSampler",p),_.setMatrix("diffuseMatrix",p.getTextureMatrix()))}Gr(_,d,r),n.setZOffset(-this.zOffset),n.setZOffsetUnits(-this.zOffsetUnits),c._processRendering(u,e,_,d.fillMode,t,o,(p,g)=>{_.setMatrix("world",g)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[y.PositionKind,y.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const l=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(y.UVKind)&&(r.push(y.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(y.UV2Kind)&&(r.push(y.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),no(o,l,s),n.useBones&&n.computeBonesUsingShaders?(r.push(y.MatricesIndicesKind),r.push(y.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(y.MatricesIndicesExtraKind),r.push(y.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const h=n.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),$u(r,n,c))),t&&(s.push("#define INSTANCES"),oo(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),d=u.defines,f=s.join(`
`);if(d!==f){const _=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];sn(_),u.setEffect(this.scene.getEngine().createEffect("outline",r,_,["diffuseSampler","morphTargets"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),f)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(Uu._StencilReference),this._engine.setStencilFunctionReference(Uu._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const s=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(s),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}Uu._StencilReference=4;class DC{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity===e||!this._hasVelocity()||(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!((e=this.vertexBuffers)!=null&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new G,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new da({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new da({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||e===0)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||e===0)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;(e=this._depthEffectWrapper)==null||e.dispose(),(t=this._thicknessEffectWrapper)==null||t.dispose()}}class v2 extends DC{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class Y_{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,this._blurPostProcesses!==null)){const t=this._blurPostProcesses[0],i=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let s=0;s<this._blurNumIterations*2;++s)this._blurPostProcesses[s]=s&1?i:t}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,l=6,h=1,c=6,u=!1,d=null,f=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new G,this._name=e,this._scene=t,this._camera=d,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=l,this._blurTextureType=h,this._blurTextureFormat=c,this._useStandardBlur=u,this._generateDepthBuffer=f,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=r!==0&&n!==0,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new k(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=k.CLAMP_ADDRESSMODE,this._texture.wrapV=k.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),l=new Z(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),h=t===1&&o.getCaps().textureFloatLinearFiltering||t===2&&o.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:i,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),u=c.texture;u.incrementReferences();const d=new k(null,this._scene);if(d.name="rttBlurred"+r,d._texture=u,d.wrapU=k.CLAMP_ADDRESSMODE,d.wrapV=k.CLAMP_ADDRESSMODE,d.anisotropicFilteringLevel=1,n){const f=new De("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);f.samples=this._samples,f.externalTextureSamplerBinding=!0,f.onApplyObservable.add(g=>{this._postProcessRunningIndex===0?g.setTexture("textureSampler",e):g._bindTexture("textureSampler",f.inputTexture.texture),g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(g=>{g.texture.wrapU=k.CLAMP_ADDRESSMODE,g.texture.wrapV=k.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const _=new De("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(g=>{g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(g=>{g.texture.wrapU=k.CLAMP_ADDRESSMODE,g.texture.wrapV=k.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),f.autoClear=!1,_.autoClear=!1;const p=[];for(let g=0;g<this._blurNumIterations*2;++g)p[g]=g&1?_:f;return[c,d,p]}else{const f=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],_=new De("BilateralBlurX","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.externalTextureSamplerBinding=!0,_.onApplyObservable.add(x=>{this._postProcessRunningIndex===0?x.setTexture("textureSampler",e):x._bindTexture("textureSampler",_.inputTexture.texture),x.setInt("maxFilterSize",this.blurMaxFilterSize),x.setFloat2("blurDir",1/this._blurTextureSizeX,0),x.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),x.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(x=>{x.texture.wrapU=k.CLAMP_ADDRESSMODE,x.texture.wrapV=k.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_);const p=new De("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);p.samples=this._samples,p.onApplyObservable.add(x=>{x.setInt("maxFilterSize",this.blurMaxFilterSize),x.setFloat2("blurDir",0,1/this._blurTextureSizeY),x.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),x.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(x=>{x.texture.wrapU=k.CLAMP_ADDRESSMODE,x.texture.wrapV=k.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),_.autoClear=!1,p.autoClear=!1;const g=[];for(let x=0;x<this._blurNumIterations*2;++x)g[x]=x&1?p:_;return[c,d,g]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((((e=this._camera)==null?void 0:e.fov)??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,s;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),(e=this._rt)==null||e.dispose(),this._rt=null,(t=this._texture)==null||t.dispose(),this._texture=null,(i=this._rtBlur)==null||i.dispose(),this._rtBlur=null,(s=this._textureBlurred)==null||s.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var Ir;(function(a){a[a.DepthTexture=0]="DepthTexture",a[a.DepthBlurredTexture=1]="DepthBlurredTexture",a[a.ThicknessTexture=2]="ThicknessTexture",a[a.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",a[a.DiffuseTexture=4]="DiffuseTexture",a[a.Normals=5]="Normals",a[a.DiffuseRendering=6]="DiffuseRendering"})(Ir||(Ir={}));class BT{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new q(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new m(-2,-1,1).normalize(),this._debugFeature=Ir.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new G,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new D,this._depthClearColor=new xe(1e6,1e6,1e6,1),this._thicknessClearColor=new xe(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Y_("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const r=this._diffuseMapSize??this._engine.getRenderWidth(),n=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Y_("Diffuse",this._scene,r,n,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Y_("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(e===null||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(e===null||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new Z(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===Ir.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===Ir.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),(this._debugFeature===Ir.DepthTexture||this._debugFeature===Ir.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new De("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join(`
`)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(o=>{var l,h,c,u,d,f,_,p,g,x;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),e.isWebGPU&&o.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(o.setTexture("depthSampler",this._depthRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((h=this._depthRenderTarget.textureBlur)==null?void 0:h.getInternalTexture())??null)):(o.setTexture("depthSampler",this._depthRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((l=this._depthRenderTarget.texture)==null?void 0:l.getInternalTexture())??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(o.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((u=this._diffuseRenderTarget.textureBlur)==null?void 0:u.getInternalTexture())??null)):(o.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((c=this._diffuseRenderTarget.texture)==null?void 0:c.getInternalTexture())??null)):o.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(o.setFloat("thickness",this.minimumThickness),o._bindTexture("bgDepthSampler",this._bgDepthTexture),e.isWebGPU&&o.setTextureSampler("bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(o.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((f=this._thicknessRenderTarget.textureBlur)==null?void 0:f.getInternalTexture())??null)):(o.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((d=this._thicknessRenderTarget.texture)==null?void 0:d.getInternalTexture())??null)),o.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const T=this._environmentMap??this._scene.environmentTexture;T&&(o.setTexture("reflectionSampler",T),e.isWebGPU&&o.setTextureSampler("reflectionSamplerSampler",(T==null?void 0:T.getInternalTexture())??null))}if(o.setMatrix("viewMatrix",this._scene.getViewMatrix()),o.setMatrix("invProjectionMatrix",this._invProjectionMatrix),o.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),o.setVector2("texelSize",n),o.setFloat("density",this.density),o.setFloat("refractionStrength",this.refractionStrength),o.setFloat("fresnelClamp",this.fresnelClamp),o.setFloat("specularPower",this.specularPower),o.setVector3("dirLight",this.dirLight),o.setFloat("cameraFar",this._camera.maxZ),this._debug){let T=null;switch(this._debugFeature){case Ir.DepthTexture:T=this._depthRenderTarget.texture;break;case Ir.DepthBlurredTexture:T=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case Ir.ThicknessTexture:T=((_=this._thicknessRenderTarget)==null?void 0:_.texture)??null;break;case Ir.ThicknessBlurredTexture:T=(p=this._thicknessRenderTarget)!=null&&p.enableBlur?((g=this._thicknessRenderTarget)==null?void 0:g.textureBlur)??null:((x=this._thicknessRenderTarget)==null?void 0:x.texture)??null;break;case Ir.DiffuseTexture:this._diffuseRenderTarget&&(T=this._diffuseRenderTarget.texture);break}this._debugFeature!==Ir.Normals&&(o.setTexture("debugSampler",T),e.isWebGPU&&o.setTextureSampler("debugSamplerSampler",(T==null?void 0:T.getInternalTexture())??null))}})}_clearTargets(){var e,t,i;(e=this._depthRenderTarget)!=null&&e.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(t=this._diffuseRenderTarget)!=null&&t.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(i=this._thicknessRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var i,s,r,n,o,l;if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(i=this._depthRenderTarget)!=null&&i.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(s=this._diffuseRenderTarget)!=null&&s.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(r=this._thicknessRenderTarget)!=null&&r.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(n=this._depthRenderTarget)==null||n.applyBlurPostProcesses(),(o=this._diffuseRenderTarget)==null||o.applyBlurPostProcesses(),(l=this._thicknessRenderTarget)==null||l.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){var t,i,s,r;e||((t=this._depthRenderTarget)==null||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)==null||i.dispose(),this._diffuseRenderTarget=null,(s=this._thicknessRenderTarget)==null||s.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(r=this._renderPostProcess)==null||r.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class b2 extends DC{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1;break}this._vertexBuffers[t]=new y(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new da({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new y(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(((e=this._diffuseEffectWrapper)==null?void 0:e.effect.isReady())??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||e===0)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),this._particleSize!==null&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;super.dispose(),(e=this._diffuseEffectWrapper)==null||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const A2="copyTextureToTexturePixelShader",y2=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;
#include<helperFunctions>
void main(void) 
{vec4 color=texture2D(textureSampler,vUV);
#ifdef DEPTH_TEXTURE
gl_FragDepth=color.r;
#else
if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}
gl_FragColor=color;
#endif
}
`;W.ShadersStore[A2]=y2;var Sp;(function(a){a[a.None=0]="None",a[a.ToLinearSpace=1]="ToLinearSpace",a[a.ToGammaSpace=2]="ToGammaSpace"})(Sp||(Sp={}));class R2{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new Nf(e),this._effectWrapper=new da({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=Sp.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class I2{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new R2(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"});const r=this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil");r.label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const P2="fluidRenderingParticleDepthVertexShader",M2=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;
#ifdef FLUIDRENDERING_VELOCITY
attribute vec3 velocity;varying float velocityNorm;
#endif
void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;
#ifdef FLUIDRENDERING_VELOCITY
velocityNorm=length(velocity);
#endif
}
`;W.ShadersStore[P2]=M2;const D2="fluidRenderingParticleDepthPixelShader",O2=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;
#ifdef FLUIDRENDERING_VELOCITY
varying float velocityNorm;
#endif
void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);
#ifndef FLUIDRENDERING_RHS
normal.z=-normal.z;
#endif
vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;
#ifdef WEBGPU
gl_FragDepth=clipSpacePos.z/clipSpacePos.w;
#else
gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;
#endif
#ifdef FLUIDRENDERING_RHS
realViewPos.z=-realViewPos.z;
#endif
#ifdef FLUIDRENDERING_VELOCITY
glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);
#else
glFragColor=vec4(realViewPos.z,0.,0.,1.);
#endif
}
`;W.ShadersStore[D2]=O2;const N2="fluidRenderingParticleThicknessVertexShader",F2=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}
`;W.ShadersStore[N2]=F2;const w2="fluidRenderingParticleThicknessPixelShader",L2=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}
`;W.ShadersStore[w2]=L2;const B2="fluidRenderingParticleDiffuseVertexShader",U2=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}
`;W.ShadersStore[B2]=U2;const V2="fluidRenderingParticleDiffusePixelShader",k2=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}
`;W.ShadersStore[V2]=k2;const G2="fluidRenderingBilateralBlurPixelShader",z2=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}
int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}
glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}
`;W.ShadersStore[G2]=z2;const W2="fluidRenderingStandardBlurPixelShader",H2=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}
float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}
sum/=wsum;glFragColor=vec4(sum.rgb,1.);}
`;W.ShadersStore[W2]=H2;const X2="fluidRenderingRenderPixelShader",Y2=`/* disable_uniformity_analysis */
#define IOR 1.333
#define ETA 1.0/IOR
#define F0 0.02
uniform sampler2D textureSampler;uniform sampler2D depthSampler;
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
uniform sampler2D diffuseSampler;
#else
uniform vec3 diffuseColor;
#endif
#ifdef FLUIDRENDERING_FIXED_THICKNESS
uniform float thickness;uniform sampler2D bgDepthSampler;
#else
uniform float minimumThickness;uniform sampler2D thicknessSampler;
#endif
#ifdef FLUIDRENDERING_ENVIRONMENT
uniform samplerCube reflectionSampler;
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
uniform sampler2D debugSampler;
#endif
uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;
#ifdef FLUIDRENDERING_RHS
ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;
#else
ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;
#endif
ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}
vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}
void main(void) {vec2 texCoord=vUV;
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
vec4 color=texture2D(debugSampler,texCoord);
#ifdef FLUIDRENDERING_DEBUG_DEPTH
glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}
#else
glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}
#endif
return;
#endif
vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;
#ifndef FLUIDRENDERING_FIXED_THICKNESS
float thickness=texture2D(thicknessSampler,texCoord).x;
#else
float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;
#endif
vec4 backColor=texture2D(textureSampler,texCoord);
#ifndef FLUIDRENDERING_FIXED_THICKNESS
if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {
#else
if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {
#endif
glFragColor=backColor;return;}
vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}
vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}
vec3 normal=normalize(cross(ddy,ddx));
#ifdef FLUIDRENDERING_RHS
normal=-normal;
#endif
#ifndef WEBGPU
if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)
glFragColor=vec4(normal*0.5+0.5,1.0);return;
#endif
vec3 rayDir=normalize(viewPos); 
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;
#endif
vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);
#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING
float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;
#endif
vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); 
vec3 refractionColor=transmitted.rgb*transmittance;
#ifdef FLUIDRENDERING_ENVIRONMENT
vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;
#else
vec3 finalColor=refractionColor+specular;
#endif
#ifdef FLUIDRENDERING_VELOCITY
float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));
#endif
glFragColor=vec4(finalColor,transmitted.a);}
`;W.ShadersStore[X2]=Y2;Object.defineProperty(Ee.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(a){this._fluidRenderer=a},enumerable:!0,configurable:!0});Ee.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new Og(this),this._fluidRenderer)};Ee.prototype.disableFluidRenderer=function(){var a;(a=this._fluidRenderer)==null||a.dispose(),this._fluidRenderer=null};function $2(a){return!!a.particleSystem}function K2(a){return!!a.addBuffers}class j2{constructor(e){this.name=he.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(he.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(he.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;(t=this.scene.fluidRenderer)==null||t._prepareRendering()}_afterCameraDraw(e){var t;(t=this.scene.fluidRenderer)==null||t._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i<e.renderObjects.length;++i){const s=e.renderObjects[i].object;if(K2(s)){const r=s.vertexBuffers;for(const n in r)t.add(r[n].getWrapperBuffer())}}t.forEach(i=>{i._rebuild()})}dispose(){this.scene.disableFluidRenderer()}}class Og{static _SceneComponentInitialization(e){let t=e._getComponent(he.NAME_FLUIDRENDERER);t||(t=new j2(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,Og._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return t!==-1?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new v2(this._scene,e);r.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new BT(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),t!==void 0&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new b2(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),s||(s=new BT(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return i===-1?!1:(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0)}_removeUnusedTargetRenderers(){const e={};for(let s=0;s<this.renderObjects.length;++s){const r=this.renderObjects[s].targetRenderer;e[this.targetRenderers.indexOf(r)]=!0}let t=!1;const i=[];for(let s=0;s<this.targetRenderers.length;++s)e[s]?i.push(this.targetRenderers[s]):(this.targetRenderers[s].dispose(),t=!0);return t&&(this.targetRenderers.length=0,this.targetRenderers.push(...i)),t}_getParticleSystemIndex(e){for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t].object;if($2(i)&&i.particleSystem===e)return t}return-1}_initialize(){for(let i=0;i<this.targetRenderers.length;++i)this.targetRenderers[i].dispose();const e=new Map;for(let i=0;i<this.targetRenderers.length;++i){const s=this.targetRenderers[i];if(s._initialize(),s.camera&&s._renderPostProcess){let r=e.get(s.camera);r||(r=[[],{}],e.set(s.camera,r)),r[0].push(s),s.camera.attachPostProcess(s._renderPostProcess,i)}}let t=e.keys();for(let i=t.next();i.done!==!0;i=t.next()){const s=i.value,r=e.get(s),n=s._getFirstPostProcess();if(!n)continue;const[o,l]=r;n.onSizeChangedObservable.add(()=>{var h;n.inputTexture.depthStencilTexture||n.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,o[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${n.name}`);for(const c of o){const u=(h=c._thicknessRenderTarget)==null?void 0:h.renderTarget,d=u==null?void 0:u.texture;if(u&&d){const f=d.width+"_"+d.height;let _=l[f];_||(_=l[f]=new I2(this._engine,d.width,d.height)),_.depthRTWrapper._shareDepth(u)}}})}t=this._cameras.keys();for(let i=t.next();i.done!==!0;i=t.next()){const s=i.value,n=this._cameras.get(s)[1],o=e.get(s);if(o)for(const l in n)o[1][l]||n[l].dispose();else for(const l in n)n[l].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t<this.renderObjects.length;++t){const i=this.renderObjects[t];let s=e.get(i.targetRenderer);s===void 0&&(s=0),e.set(i.targetRenderer,Math.max(s,i.object.particleSize))}e.forEach((t,i)=>{i._depthRenderTarget&&(i._depthRenderTarget.particleSize=t)})}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var i;for(let s=0;s<this.targetRenderers.length;++s)(!e||this.targetRenderers[s].camera===e)&&this.targetRenderers[s]._clearTargets();const t=this._cameras.keys();for(let s=t.next();s.done!==!0;s=t.next()){const r=s.value,n=this._cameras.get(r);if(e&&r!==e)continue;const o=r._getFirstPostProcess();if(!o)continue;const l=(i=o.inputTexture)==null?void 0:i.depthStencilTexture;if(l){const[h,c]=n;for(const u of h)u._bgDepthTexture=l;for(const u in c)c[u].copy(l)}}for(let s=0;s<this.renderObjects.length;++s){const r=this.renderObjects[s];(!e||r.targetRenderer.camera===e)&&r.targetRenderer._render(r.object)}}dispose(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(let e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach(e=>{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class q2 extends Vs{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class Bc extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,Bc.Name,300,new q2),this._lightColor=new q,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof At?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===st.LIGHTTYPEID_SPOTLIGHT;if(t){const i=this.light;this._hasProjectionTexture=i.projectionTexture?i.projectionTexture.isReady():!1}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:`#ifdef RSMCREATE
                    uniform mat4 rsmTextureProjectionMatrix;
                    uniform vec4 rsmSpotInfo;
                    uniform vec3 rsmLightColor;
                    unfiorm vec3 rsmLightPosition;
                #endif`}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===st.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=U.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(t.angle*.5))}}getCustomCode(e){return e==="vertex"?null:{CUSTOM_FRAGMENT_BEGIN:`
                #ifdef RSMCREATE
                    #extension GL_EXT_draw_buffers : require
                #endif
            `,CUSTOM_FRAGMENT_DEFINITIONS:`
                #ifdef RSMCREATE
                    #ifdef RSMCREATE_PROJTEXTURE
                        uniform highp sampler2D rsmTextureProjectionSampler;                    
                    #endif
                    layout(location = 0) out highp vec4 glFragData[3];
                    vec4 glFragColor;
                #endif
            `,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`
                #ifdef RSMCREATE
                    vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;
                    #ifdef RSMCREATE_PROJTEXTURE
                    {
                        vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);
                        strq /= strq.w;
                        rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;
                    }
                    #endif
                    #ifdef RSMCREATE_LIGHT_IS_SPOT
                    {
                        float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));
                        rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;
                    }
                    #endif
                    glFragData[0] = vec4(vPositionW, 1.);
                    glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);
                    glFragData[2] = vec4(rsmColor, 1.);
                #endif
            `}}}Bc.Name="RSMCreate";E([I()],Bc.prototype,"light",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],Bc.prototype,"isEnabled",void 0);V("BABYLON.RSMCreatePluginMaterial",Bc);const Q2="bilateralBlurPixelShader",Z2=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}
vec3 normal=textureLod(normalSampler,vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
float r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}
glFragColor=vec4(sum/wsum,1.);}
`;W.ShadersStore[Q2]=Z2;const J2="bilateralBlurQualityPixelShader",eU=`uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}
vec3 normal=textureLod(normalSampler,vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}
glFragColor=vec4(sum/wsum,1.);}
`;W.ShadersStore[J2]=eU;const tU="rsmGlobalIlluminationPixelShader",iU=`/**
* The implementation is an application of the formula found in http:
* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).
*/
precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;
#ifdef TRANSFORM_NORMAL
uniform mat4 invView;
#endif
float mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}
float noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}
vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i<numSamples; i++) {vec3 rsmSample=texelFetch(rsmSamples,ivec2(i,0),0).xyz;float weightSquare=rsmSample.z;if (rsmInfo2.y==1.0) rsmSample.xy=vec2(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c);vec2 uv=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}
return clamp(indirectDiffuse*intensity,0.0,1.0);}
void main(void) 
{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(invView*vec4(normalW,0.)).xyz;
#endif
gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}
`;W.ShadersStore[tU]=iU;const sU="rsmFullGlobalIlluminationPixelShader",rU=`/**
* The implementation is a direct application of the formula found in http:
*/
precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;
#ifdef TRANSFORM_NORMAL
uniform mat4 invView;
#endif
vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j<height; j++) {for (int i=0; i<width; i++) {ivec2 uv=ivec2(i,j);vec3 vplPositionW=texelFetch(rsmPositionW,uv,0).xyz;vec3 vplNormalW=texelFetch(rsmNormalW,uv,0).xyz*2.0-1.0;vec3 vplFlux=texelFetch(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}
return clamp(indirectDiffuse*intensity,0.0,1.0);}
void main(void) 
{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(invView*vec4(normalW,0.)).xyz;
#endif
gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}
`;W.ShadersStore[sU]=rU;class nU extends Vs{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class fo extends Zs{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,fo.Name,310,new nU),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof At}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:`#ifdef RENDER_WITH_GIRSM
                    uniform vec2 girsmTextureOutputSize;
                #endif`}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:`
                #ifdef RENDER_WITH_GIRSM
                    uniform sampler2D girsmTextureGIContrib;

                    vec3 computeIndirect() {
                        vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;
                        return texture2D(girsmTextureGIContrib, uv).rgb;
                    }
                #endif
            `,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:`
                #ifdef RENDER_WITH_GIRSM
                    finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;
                #endif
            `};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR=`
                #ifdef RENDER_WITH_GIRSM
                    color.rgb += computeIndirect() * baseColor.rgb;
                #endif
            `),e==="vertex"?null:t}}fo.Name="GIRSMRender";E([I()],fo.prototype,"textureGIContrib",void 0);E([I()],fo.prototype,"outputTextureWidth",void 0);E([I()],fo.prototype,"outputTextureHeight",void 0);E([I(),te("_markAllSubMeshesAsTexturesDirty")],fo.prototype,"isEnabled",void 0);V("BABYLON.GIRSMRenderPluginMaterial",fo);const aU="spriteMapPixelShader",oU=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(
texture2D(frameMap,vec2(fX,0.),0.),
texture2D(frameMap,vec2(fX,fdStep*1.),0.),
texture2D(frameMap,vec2(fX,fdStep*2.),0.),
vec4(0.)
);}
void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);
#ifdef FLIPU
tileUV.y=1.0-tileUV.y;
#endif
vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID;
#define LAYER_ID_SWITCH
vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;}
animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}
mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}
vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}
color.xyz*=colorMul;gl_FragColor=color;}`;W.ShadersStore[aU]=oU;const lU="spriteMapVertexShader",hU=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; 
gl_Position=worldViewProjection*p;}`;W.ShadersStore[lU]=hU;var UT;(function(a){a[a.INIT=0]="INIT",a[a.RUNNING=1]="RUNNING",a[a.DONE=2]="DONE",a[a.ERROR=3]="ERROR"})(UT||(UT={}));class Yc{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}G.prototype.notifyObserversWithPromise=async function(a,e=-1,t,i,s){let r=Promise.resolve(a);if(!this.observers.length)return r;const n=this._eventState;return n.mask=e,n.target=t,n.currentTarget=i,n.skipNextObservers=!1,n.userInfo=s,this.observers.forEach(o=>{n.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?r=r.then(l=>(n.lastReturnValue=l,o.callback.apply(o.scope,[a,n]))):r=r.then(l=>(n.lastReturnValue=l,o.callback(a,n))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await r,a};let Aa=null;function OC(a,e,t,i,s="image/png",r=!1,n){const{height:o,width:l}=NC(a,e,t);if(!(o&&l)){O.Error("Invalid 'size' parameter !");return}Aa||(Aa=document.createElement("canvas")),Aa.width=l,Aa.height=o;const h=Aa.getContext("2d"),c=a.getRenderWidth()/a.getRenderHeight();let u=l,d=u/c;d>o&&(d=o,u=d*c);const f=Math.max(0,l-u)/2,_=Math.max(0,o-d)/2;e.getScene().activeCamera!==e?Ng(a,e,t,g=>{if(r){const x=new Blob([g]);X.DownloadBlob(x),i&&i("")}else i&&i(g)},s,1,a.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):a.onEndFrameObservable.addOnce(()=>{const g=a.getRenderingCanvas();h&&g&&h.drawImage(g,f,_,u,d),Aa&&(r?(X.EncodeScreenshotCanvasData(Aa,void 0,s,void 0,n),i&&i("")):X.EncodeScreenshotCanvasData(Aa,i,s,void 0,n))})}function cU(a,e,t,i="image/png",s){return new Promise((r,n)=>{OC(a,e,t,o=>{typeof o<"u"?r(o):n(new Error("Data is undefined"))},i,void 0,s)})}function Ng(a,e,t,i,s="image/png",r=1,n=!1,o,l=!1,h=!1,c=!0,u,d){const{height:f,width:_,finalWidth:p,finalHeight:g}=NC(a,e,t),x={width:_,height:f};if(!(f&&_)){O.Error("Invalid 'size' parameter !");return}const T={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(_,f);const S=e.getScene(),C=new oi("screenShot",x,S,!1,!1,0,!1,k.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);C.renderList=S.meshes.slice(),C.samples=r,C.renderSprites=l,C.activeCamera=e,C.forceLayerMaskCheck=c,d==null||d(C);const v=()=>{C.isReadyForRendering()&&e.isReady(!0)?(a.onEndFrameObservable.addOnce(()=>{p===_&&g===f?C.readPixels(void 0,void 0,void 0,!1).then(A=>{Fs.DumpData(_,f,A,i,s,o,!0,void 0,u),C.dispose()}):Zm("pass",C.getInternalTexture(),S,void 0,void 0,void 0,p,g).then(A=>{a._readTexturePixels(A,p,g,-1,0,null,!0,!1,0,0).then(P=>{Fs.DumpData(p,g,P,i,s,o,!0,void 0,u),A.dispose()})})}),C.render(!0),S.incrementRenderId(),S.resetCachedMaterial(),a.setSize(T.width,T.height),e.getProjectionMatrix(!0),S.render()):setTimeout(v,16)},b=()=>{S.incrementRenderId(),S.resetCachedMaterial(),v()};if(n){const A=new Fc("antialiasing",1,S.activeCamera);C.addPostProcess(A),A.getEffect().isReady()?b():A.getEffect().onCompiled=()=>{b()}}else b()}function uU(a,e,t,i="image/png",s=1,r=!1,n,o=!1,l=!1,h=!0,c){return new Promise((u,d)=>{Ng(a,e,t,f=>{typeof f<"u"?u(f):d(new Error("Data is undefined"))},i,s,r,n,o,l,h,c)})}function NC(a,e,t){let i=0,s=0,r=0,n=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,s=t.width*o):t.width&&!t.height?(s=t.width*o,i=Math.round(s/a.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,s=Math.round(i*a.getAspectRatio(e))):(s=Math.round(a.getRenderWidth()*o),i=Math.round(s/a.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(n=t.finalHeight,r=t.finalWidth):t.finalWidth&&!t.finalHeight?(r=t.finalWidth,n=Math.round(r/a.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(n=t.finalHeight,r=Math.round(n*a.getAspectRatio(e))):(r=s,n=i)}else isNaN(t)||(i=t,s=t,r=t,n=t);return s&&(s=Math.floor(s)),i&&(i=Math.floor(i)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),{height:i|0,width:s|0,finalWidth:r|0,finalHeight:n|0}}const dU=()=>{X.CreateScreenshot=OC,X.CreateScreenshotAsync=cU,X.CreateScreenshotUsingRenderTarget=Ng,X.CreateScreenshotUsingRenderTargetAsync=uU};dU();var VT;(function(a){a[a.Checkbox=0]="Checkbox",a[a.Slider=1]="Slider",a[a.Vector3=2]="Vector3",a[a.Quaternion=3]="Quaternion",a[a.Color3=4]="Color3",a[a.String=5]="String",a[a.Button=6]="Button",a[a.Options=7]="Options",a[a.Tab=8]="Tab",a[a.FileButton=9]="FileButton",a[a.Vector2=10]="Vector2"})(VT||(VT={}));class Bd{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then(t=>{this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0})}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return Cv(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class kT{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return i===void 0?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return i!==null?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return i!==null?i==="true":t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return i!==null?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}kT._Storage=kT._GetStorage();var GT;(function(a){class e{serialize(){const s={},r=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((n,o)=>{r[n]=o}),s.characters=r,s.insertionCosts=this._insertionCosts,s.deletionCosts=this._deletionCosts,s.substitutionCosts=this._substitutionCosts,JSON.stringify(s)}static Deserialize(s){const r=JSON.parse(s),n=new e(r.characters);return n._insertionCosts=r.insertionCosts,n._deletionCosts=r.deletionCosts,n._substitutionCosts=r.substitutionCosts,n}constructor(s,r=null,n=null,o=null){r=r??(()=>1),n=n??(()=>1),o=o??((h,c)=>h===c?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(s.length),this._deletionCosts=new Array(s.length),this._substitutionCosts=new Array(s.length);let l;for(let h=0;h<s.length;++h){l=s[h],this._characterToIdx.set(l,h),this._insertionCosts[h]=r(l),this._deletionCosts[h]=n(l),this._substitutionCosts[h]=new Array(s.length);for(let c=h;c<s.length;++c)this._substitutionCosts[h][c]=o(l,s[c])}}getCharacterIdx(s){return this._characterToIdx.get(s)}getInsertionCost(s){return this._insertionCosts[s]}getDeletionCost(s){return this._deletionCosts[s]}getSubstitutionCost(s,r){const n=Math.min(s,r),o=Math.max(s,r);return this._substitutionCosts[n][o]}}a.Alphabet=e;class t{serialize(){return JSON.stringify(this._characters)}static Deserialize(s,r){const n=new t([],r);return n._characters=JSON.parse(s),n}constructor(s,r){if(s.length>t._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+t._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=r,this._characters=s.map(n=>this._alphabet.getCharacterIdx(n))}distance(s){return t._Distance(this,s)}static _Distance(s,r){const n=s._alphabet;if(n!==r._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=s._characters,l=r._characters,h=o.length,c=l.length,u=t._CostMatrix;u[0][0]=0;for(let d=0;d<h;++d)u[d+1][0]=u[d][0]+n.getInsertionCost(o[d]);for(let d=0;d<c;++d)u[0][d+1]=u[0][d]+n.getInsertionCost(l[d]);for(let d=0;d<h;++d)for(let f=0;f<c;++f)t._InsertionCost=u[d+1][f]+n.getInsertionCost(l[f]),t._DeletionCost=u[d][f+1]+n.getDeletionCost(o[d]),t._SubstitutionCost=u[d][f]+n.getSubstitutionCost(o[d],l[f]),u[d+1][f+1]=Math.min(t._InsertionCost,t._DeletionCost,t._SubstitutionCost);return u[h][c]}}t._MAX_SEQUENCE_LENGTH=256,t._CostMatrix=[...Array(t._MAX_SEQUENCE_LENGTH+1)].map(()=>new Array(t._MAX_SEQUENCE_LENGTH+1)),a.Sequence=t})(GT||(GT={}));new D;const fU=1.5;class ya{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(this._view.length*fU),t=new Float32Array(e);t.set(this._view),this._view=t}}const Ra=1800,_U=24,pU="0",zT="timestamp",WT="numPoints",mU=/\r/g,$_="@";class cn{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=Zi.Now-this._startingTimestamp,s=this.datasets.ids.length,r=this.datasets.startingIndices.itemLength;let n=0;if(r>0){const o=this.datasets.startingIndices.at(r-1);n=o+this.datasets.data.at(o+cn.NumberOfPointsOffset)+cn.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(i),this.datasets.data.push(s),this.datasets.ids.forEach(o=>{const l=this._strategies.get(o);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const o=[i,s];for(let l=0;l<s;l++)o.push(this.datasets.data.at(n+cn.SliceDataOffset+l));this.datasetObservable.notifyObservers(o)}},this.datasets={ids:[],data:new ya(Ra),startingIndices:new ya(Ra)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new G,this.datasetObservable=new G,this.metadataObservable=new G(i=>i.callback(this._datasetMeta,new aE(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((n=this._strategies.get(e))==null||n.dispose(),this._strategies.delete(e));const s=o=>{let l=0,h=0;const c=o.onAfterRenderObservable.add(()=>{h=l,l=0}),u=this._customEventObservable.add(d=>{e===d.name&&(d.value!==void 0?l=d.value:l++)});return{id:e,getData:()=>h,dispose:()=>{o.onAfterRenderObservable.remove(c),this._customEventObservable.remove(u)}}},r={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:s,category:i}),r}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const r=t(this._scene);if(this._strategies.has(r.id)){r.dispose();continue}this.datasets.ids.push(r.id),i&&(i=i.replace(new RegExp($_,"g"),"")),this._datasetMeta.set(r.id,{color:this._getHexColorFromId(r.id),category:i,hidden:s}),this._strategies.set(r.id,r)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);let i="#";for(let s=0;s<_U;s+=8){const r=t>>s&255;i+=(pU+r.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=Zi.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(s=>{const r=this._strategies.get(s);r&&this.datasetObservable.hasObservers()&&i.push(r.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new ya(Ra),this.datasets.ids.length=0,this.datasets.startingIndices=new ya(Ra),this._datasetMeta.clear(),this._strategies.forEach(t=>t.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(mU,"").split(`
`).map(u=>u.split(",").filter(d=>d.length>0)).filter(u=>u.length>0),s=0,r=cn.NumberOfPointsOffset;if(i.length<2)return!1;const n={ids:[],data:new ya(Ra),startingIndices:new ya(Ra)},[o,...l]=i;if(o.length<2||o[s]!==zT||o[r]!==WT)return!1;const h=new Map;for(let u=cn.SliceDataOffset;u<o.length;u++){const[d,f]=o[u].split($_);n.ids.push(d),h.set(d,f)}let c=0;for(const u of l){if(u.length<2)return!1;const d=parseFloat(u[s]),f=parseInt(u[r]);if(isNaN(f)||isNaN(d)||(n.data.push(d),n.data.push(f),f+cn.SliceDataOffset!==u.length))return!1;for(let _=cn.SliceDataOffset;_<u.length;_++){const p=parseFloat(u[_]);if(isNaN(p))return!1;n.data.push(p)}n.startingIndices.push(c),c+=u.length}if(this.datasets.ids=n.ids,this.datasets.data=n.data,this.datasets.startingIndices=n.startingIndices,t||this._datasetMeta.clear(),this._strategies.forEach(u=>u.dispose()),this._strategies.clear(),!t)for(const u of this.datasets.ids){const d=h.get(u);this._datasetMeta.set(u,{category:d,color:this._getHexColorFromId(u)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${zT},${WT}`;for(let i=0;i<this.datasets.ids.length;i++)if(e+=`,${this.datasets.ids[i]}`,this._datasetMeta){const s=this._datasetMeta.get(this.datasets.ids[i]);s!=null&&s.category&&(e+=`${$_}${s.category}`)}e+=`
`;for(let i=0;i<this.datasets.startingIndices.itemLength;i++){const s=this.datasets.startingIndices.at(i),r=this.datasets.data.at(s),n=this.datasets.data.at(s+cn.NumberOfPointsOffset);e+=`${r},${n}`;for(let o=0;o<n;o++)e+=`,${this.datasets.data.at(s+cn.SliceDataOffset+o)}`;for(let o=0;o<this.datasets.ids.length-n;o++)e+=",";e+=`
`}const t=`${new Date().toISOString()}-perfdata.csv`;X.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?this._startingTimestamp===void 0&&(this._startingTimestamp=Zi.Now):(this.datasets.data=new ya(Ra),this.datasets.startingIndices=new ya(Ra),this._startingTimestamp=Zi.Now),this._scene.onAfterRenderObservable.add(this._collectDataAtFrame),this._restoreStringEvents(),this._isStarted=!0}stop(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._isStarted=!1}get isStarted(){return this._isStarted}dispose(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._datasetMeta.clear(),this._strategies.forEach(e=>{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}Ee.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new cn(this)),this._perfCollector};function gU(a){const e=new Array,t=new Array,i=new Array,s=a.add(()=>{const n=e.length;for(let o=0;o<n;o++)Zd(e.shift(),t.shift(),i.shift())});return{scheduler:(n,o,l)=>{e.push(n),t.push(o),i.push(l)},dispose:()=>{a.remove(s)}}}G.prototype.runCoroutineAsync=function(a){if(!this._coroutineScheduler){const e=gU(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return LE(a,this._coroutineScheduler)};G.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const xU="equirectangularPanoramaPixelShader",TU=`#ifdef GL_ES
precision highp float;
#endif
#define M_PI 3.1415926535897932384626433832795
varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(
- sin( longitude )*sin( latitude ),
cos( latitude ),
- cos( longitude )*sin( latitude )
);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;W.ShadersStore[xU]=TU;class $a extends _s{constructor(e,t={}){super(e),this.options=t,this._direction=new m(0,0,-1),this._mat=new D,this._onSelectEnabled=!1,this._origin=new m(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new G,this._onHitTestResults=i=>{const s=i.map(r=>{const n=D.FromArray(r.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||n.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&n.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),n),{xrHitResult:r,transformationMatrix:n}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(s)},this._onSelect=i=>{this._onSelectEnabled&&$a.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",X.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then(r=>{const n=s||(o=>!!o.hitMatrix);return r.filter(n)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return super.attach()?(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0):!1}detach(){return super.detach()?(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;D.FromArrayToRef(t.transform.matrix,0,this._mat),m.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),m.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});$a.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}$a.Name=dt.HIT_TEST;$a.Version=1;fi.AddWebXRFeature($a.Name,(a,e)=>()=>new $a(a,e),$a.Version,!1);let EU=0;class iu extends _s{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new G,this.onAnchorRemovedObservable=new G,this.onAnchorUpdatedObservable=new G,this._tmpVector=new m,this._tmpQuaternion=new Q,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new m,i=new Q){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{const r=await e.xrHitResult.createAnchor(s);return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!0,xrTransformation:s,resolve:n,reject:o})})}catch(r){throw new Error(r)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new Q,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:n,reject:o})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch{}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter(r=>!t.has(r.xrAnchor)).map(r=>this._trackedAnchors.indexOf(r));let s=0;i.forEach(r=>{const n=this._trackedAnchors.splice(r-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(n),s++}),t.forEach(r=>{if(this._lastFrameDetected.has(r)){const n=this._findIndexInAnchorArray(r),o=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(r,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new Q,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{X.Warn("Anchor could not be updated")}}else{const n={id:EU++,xrAnchor:r,remove:()=>r.delete()},o=this._updateAnchorWithXRFrame(r,n,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const h=this._futureAnchors.filter(c=>c.nativeAnchor===r)[0];h&&(h.resolve(o),h.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(i=>{!i.resolved&&!i.submitted&&(this._createAnchorAtTransformation(i.xrTransformation,e).then(s=>{i.nativeAnchor=s},s=>{i.resolved=!0,i.reject(s)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return-1}_updateAnchorWithXRFrame(e,t,i){const s=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new D;D.FromArrayToRef(s.transform.matrix,0,r),this._xrSessionManager.scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),t.transformationMatrix=r,this._options.worldParentNode&&r.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),r)}return t}async _createAnchorAtTransformation(e,t){if(t.createAnchor)try{return t.createAnchor(e,this._referenceSpaceForFrameAnchors??this._xrSessionManager.referenceSpace)}catch(i){throw new Error(i)}else throw this.detach(),new Error("Anchors are not enabled in your browser")}}iu.Name=dt.ANCHOR_SYSTEM;iu.Version=1;fi.AddWebXRFeature(iu.Name,(a,e)=>()=>new iu(a,e),iu.Version);let SU=0;class su extends _s{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new G,this.onPlaneRemovedObservable=new G,this.onPlaneUpdatedObservable=new G,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return typeof XRPlane<"u"}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var i;if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||((i=e.worldInformation)==null?void 0:i.detectedPlanes);if(t){for(let s=0;s<this._detectedPlanes.length;s++){const r=this._detectedPlanes[s];t.has(r.xrPlane)||(this._detectedPlanes.splice(s--,1),this.onPlaneRemovedObservable.notifyObservers(r))}t.forEach(s=>{if(this._lastFrameDetected.has(s)){if(s.lastChangedTime===this._xrSessionManager.currentTimestamp){const r=this._findIndexInPlaneArray(s),n=this._detectedPlanes[r];this._updatePlaneWithXRPlane(s,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const r={id:SU++,xrPlane:s,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(s,r,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}}),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(r=>{const n=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new m(r.x,r.y,r.z*n)});const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new D;D.FromArrayToRef(s.transform.matrix,0,r),this._xrSessionManager.scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),t.transformationMatrix=r,this._options.worldParentNode&&r.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),r)}return t}_findIndexInPlaneArray(e){for(let t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return-1}}su.Name=dt.PLANE_DETECTION;su.Version=1;fi.AddWebXRFeature(su.Name,(a,e)=>()=>new su(a,e),su.Version);class ru extends _s{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new G}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(i=>i.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}ru.Name=dt.BACKGROUND_REMOVER;ru.Version=1;fi.AddWebXRFeature(ru.Name,(a,e)=>()=>new ru(a,e),ru.Version,!0);class nu extends _s{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||We.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=pa("impostor-mesh-"+e.uniqueId,{diameterX:typeof i=="number"?i:i.width,diameterY:typeof i=="number"?i:i.height,diameterZ:typeof i=="number"?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new Q;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new We(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||O.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(s=>{s._doNotLoadControllerMesh?this._createPhysicsImpostor(i):s.onModelLoadedObservable.addOnce(()=>{const r=new We(s.rootMesh,We.MeshImpostor,{mass:0,...this._options.physicsProperties}),n=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:r,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(i))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new Q,this._tmpVector=new m,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:We.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=pa("headset-mesh",{diameterX:typeof t=="number"?t:t.width,diameterY:typeof t=="number"?t:t.height,diameterZ:typeof t=="number"?t:t.depth}),this._headsetMesh.rotationQuaternion=new Q,this._headsetMesh.isVisible=!1,this._headsetImpostor=new We(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0):!1}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t=typeof e=="string"?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),(t=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&t.linearVelocity){const s=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if((i=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&i.angularVelocity){const s=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(s=>{var h,c;const r=this._controllers[s],n=r.xrController.grip||r.xrController.pointer,o=r.oldPos||r.impostorMesh.position;if((h=r.xrController._lastXRPose)!=null&&h.linearVelocity){const u=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),r.impostor.setLinearVelocity(this._tmpVector)}else n.position.subtractToRef(o,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);o.copyFrom(n.position),this._debugMode&&O.Log([this._tmpVector,"linear"]);const l=r.oldRotation||r.impostorMesh.rotationQuaternion;if((c=r.xrController._lastXRPose)!=null&&c.angularVelocity){const u=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!l.equalsWithEpsilon(n.rotationQuaternion)){l.conjugateInPlace().multiplyToRef(n.rotationQuaternion,this._tmpQuaternion);const u=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),u<.001)this._tmpVector.scaleInPlace(2);else{const d=2*Math.atan2(u,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(d/(u*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}l.copyFrom(n.rotationQuaternion),this._debugMode&&O.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}nu.Name=dt.PHYSICS_CONTROLLERS;nu.Version=1;fi.AddWebXRFeature(nu.Name,(a,e)=>()=>new nu(a,e),nu.Version,!0);class au extends _s{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new D,this._tmpPos=new m,this._tmpQuat=new Q,this._initHitTestSource=i=>{if(!i)return;const s=new XRRay(this.options.offsetRay||{}),r={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:s};if(this.options.entityTypes&&(r.entityTypes=this.options.entityTypes),!r.space){X.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(r).then(n=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=n})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new G,this.paused=!1,this.xrNativeFeatureName="hit-test",X.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(t=>{this._transientXrHitTestSource=t})}return!0}detach(){return super.detach()?(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0):!1}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!(!this.attached||this.paused)){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach(i=>{this._processWebXRHitTestResult(i.results,i.inputSource)})}}_processWebXRHitTestResult(e,t){const i=[];e.forEach(s=>{const r=s.getPose(this._xrSessionManager.referenceSpace);if(!r)return;const n=r.transform.position,o=r.transform.orientation;this._tmpPos.set(n.x,n.y,n.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(o.x,o.y,o.z,o.w),D.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const l={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:s};i.push(l)}),this.onHitTestResultObservable.notifyObservers(i)}}au.Name=dt.HIT_TEST;au.Version=2;fi.AddWebXRFeature(au.Name,(a,e)=>()=>new au(a,e),au.Version,!1);class ou extends _s{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new G,this.onFeaturePointsUpdatedObservable=new G,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this.featurePointCloud.length=0,!0):!1}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(!(!t||t.length===0)){if(t.length%5!==0)throw new Error("Received malformed feature point cloud of length: "+t.length);const i=t.length/5,s=[],r=[];for(let n=0;n<i;n++){const o=n*5,l=t[o+4];this._featurePointCloud[l]?s.push(l):(this._featurePointCloud[l]={position:new m,confidenceValue:0},r.push(l)),this._featurePointCloud[l].position.x=t[o],this._featurePointCloud[l].position.y=t[o+1],this._featurePointCloud[l].position.z=t[o+2],this._featurePointCloud[l].confidenceValue=t[o+3]}r.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(r),s.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(s)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}ou.Name=dt.FEATURE_POINTS;ou.Version=1;fi.AddWebXRFeature(ou.Name,a=>()=>new ou(a),ou.Version);let CU=0;class lu extends _s{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new G,this.onMeshRemovedObservable=new G,this.onMeshUpdatedObservable=new G,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return super.detach()?(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0):!1}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=e.detectedMeshes||((t=e.worldInformation)==null?void 0:t.detectedMeshes);if(i){const s=new Set;this._detectedMeshes.forEach((r,n)=>{i.has(n)||s.add(n)}),s.forEach(r=>{const n=this._detectedMeshes.get(r);n&&(this.onMeshRemovedObservable.notifyObservers(n),this._detectedMeshes.delete(r))}),i.forEach(r=>{if(this._detectedMeshes.has(r)){if(r.lastChangedTime===this._xrSessionManager.currentTimestamp){const n=this._detectedMeshes.get(r);n&&(this._updateVertexDataWithXRMesh(r,n,e),this.onMeshUpdatedObservable.notifyObservers(n))}}else{const n={id:CU++,xrMesh:r},o=this._updateVertexDataWithXRMesh(r,n,e);this._detectedMeshes.set(r,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){O.Log(i.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){var r;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let o=0;o<s.length;o+=3)t.positions[o]=s[o],t.positions[o+1]=s[o+1],t.positions[o+2]=-1*s[o+2];if(e.normals){t.normals=new Float32Array(e.normals.length);for(let o=0;o<e.normals.length;o+=3)t.normals[o]=e.normals[o],t.normals[o+1]=e.normals[o+1],t.normals[o+2]=-1*e.normals[o+2]}}t.indices=e.indices;const n=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(n){const o=t.transformationMatrix||new D;D.FromArrayToRef(n.transform.matrix,0,o),this._xrSessionManager.scene.useRightHandedSystem||o.toggleModelMatrixHandInPlace(),t.transformationMatrix=o,this._options.worldParentNode&&o.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),o)}if(this._options.generateMeshes){if(t.mesh){const o=t.mesh;o.updateVerticesData(y.PositionKind,t.positions),t.normals?o.updateVerticesData(y.NormalKind,t.normals):o.createNormals(!0),o.updateIndices(t.indices)}else{const o=new z("xr mesh "+t.id,this._xrSessionManager.scene);o.rotationQuaternion=new Q,o.setVerticesData(y.PositionKind,t.positions),t.normals?o.setVerticesData(y.NormalKind,t.normals):o.createNormals(!0),o.setIndices(t.indices,void 0,!0),t.mesh=o}(r=t.transformationMatrix)==null||r.decompose(t.mesh.scaling,t.mesh.rotationQuaternion,t.mesh.position)}}return t}}lu.Name=dt.MESH_DETECTION;lu.Version=1;fi.AddWebXRFeature(lu.Name,(a,e)=>()=>new lu(a,e),lu.Version,!1);var Dn;(function(a){a[a.NotReceived=0]="NotReceived",a[a.Waiting=1]="Waiting",a[a.Received=2]="Received"})(Dn||(Dn={}));class hu extends _s{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new G,this.onTrackableImageFoundObservable=new G,this.onTrackedImageUpdatedObservable=new G,this._trackableScoreStatus=Dn.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map(t=>typeof t.src=="string"?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(t.src):Promise.resolve(t.src));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map((i,s)=>({image:i,widthInMeters:this.options.images[s].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return X.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===Dn.Waiting)return;if(this._trackableScoreStatus===Dn.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let s=!1;const r=i.index,n=this._trackedImages[r];if(!n)continue;n.xrTrackingResult=i,n.realWorldWidth!==i.measuredWidthInMeters&&(n.realWorldWidth=i.measuredWidthInMeters,s=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const c=n.transformationMatrix;D.FromArrayToRef(o.transform.matrix,0,c),this._xrSessionManager.scene.useRightHandedSystem||c.toggleModelMatrixHandInPlace(),s=!0}const h=i.trackingState==="emulated";n.emulated!==h&&(n.emulated=h,s=!0),s&&this.onTrackedImageUpdatedObservable.notifyObservers(n)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==Dn.NotReceived)return;this._trackableScoreStatus=Dn.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=Dn.NotReceived;return}for(let t=0;t<e.length;++t)if(e[t]=="untrackable")this.onUntrackableImageFoundObservable.notifyObservers(t);else{const i=this._originalTrackingRequest[t].image,s={id:t,originalBitmap:i,transformationMatrix:new D,ratio:i.width/i.height};this._trackedImages[t]=s,this.onTrackableImageFoundObservable.notifyObservers(s)}this._trackableScoreStatus=e.length>0?Dn.Received:Dn.NotReceived}}hu.Name=dt.IMAGE_TRACKING;hu.Version=1;fi.AddWebXRFeature(hu.Name,(a,e)=>()=>new hu(a,e),hu.Version,!1);class cu extends _s{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",X.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!super.attach()||!this._xrSessionManager.session.domOverlayState||this._xrSessionManager.session.domOverlayState.type===null?!1:(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,this._element!==null&&this.options.supressXRSelectEvents===!0&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),this._element!==null&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(this.options.element===void 0)return X.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if(typeof this.options.element=="string"){const e=document.querySelector(this.options.element);if(e===null)return X.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}cu.Name=dt.DOM_OVERLAY;cu.Version=1;fi.AddWebXRFeature(cu.Name,(a,e)=>()=>new cu(a,e),cu.Version,!1);class Ka extends _s{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new Q,this._tmpRotationMatrix=D.Identity(),this._tmpTranslationDirection=new m,this._tmpMovementTranslation=new m,this._tempCacheQuaternion=new Q,this._attachController=i=>{if(this._controllers[i.uniqueId])return;this._controllers[i.uniqueId]={xrController:i,registeredComponents:[]};const s=this._controllers[i.uniqueId];if(s.xrController.inputSource.targetRayMode==="tracked-pointer"&&s.xrController.inputSource.gamepad){const r=()=>{if(i.motionController)for(const n of this._currentRegistrationConfigurations){let o=null;if(n.allowedComponentTypes)for(const h of n.allowedComponentTypes){const c=i.motionController.getComponentOfType(h);if(c!==null){o=c;break}}if(n.mainComponentOnly){const h=i.motionController.getMainComponent();if(h===null)continue;o=h}if(typeof n.componentSelectionPredicate=="function"&&(o=n.componentSelectionPredicate(i)),o&&n.forceHandedness&&i.inputSource.handedness!==n.forceHandedness||o===null)continue;const l={registrationConfiguration:n,component:o};s.registeredComponents.push(l),"axisChangedHandler"in n&&(l.onAxisChangedObserver=o.onAxisValueChangedObservable.add(h=>{n.axisChangedHandler(h,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in n&&(l.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{o.changes.pressed&&n.buttonChangedhandler(o.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};i.motionController?r():i.onMotionControllerInitObservable.addOnce(()=>{r()})}},!t||t.xrInput===void 0){X.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Ka.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return super.attach()?(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0):!1}detach(){return super.detach()?(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0):!1}_onXRFrame(e){if(this.attached){if(this._movementState.rotateX!==0&&this._featureContext.rotationEnabled){const i=this._xrSessionManager.scene.getEngine().getDeltaTime()*.001*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=i,Q.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(Q.RotationYawPitchRollToRef(i*3,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(D.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),m.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const i of t.registeredComponents)i.onAxisChangedObserver&&i.component.onAxisValueChangedObservable.remove(i.onAxisChangedObserver),i.onButtonChangedObserver&&i.component.onButtonStateChangedObservable.remove(i.onButtonChangedObserver);delete this._controllers[e]}}}Ka.Name=dt.MOVEMENT;Ka.REGISTRATIONS={default:[{allowedComponentTypes:[Ar.THUMBSTICK_TYPE,Ar.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(a,e,t)=>{e.rotateX=Math.abs(a.x)>t.rotationThreshold?a.x:0,e.rotateY=Math.abs(a.y)>t.rotationThreshold?a.y:0}},{allowedComponentTypes:[Ar.THUMBSTICK_TYPE,Ar.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(a,e,t)=>{e.moveX=Math.abs(a.x)>t.movementThreshold?a.x:0,e.moveY=Math.abs(a.y)>t.movementThreshold?a.y:0}}]};Ka.Version=1;fi.AddWebXRFeature(Ka.Name,(a,e)=>()=>new Ka(a,e),Ka.Version,!0);class uu extends _s{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=m.Up().negateInPlace(),this._lightColor=q.White(),this._intensity=1,this._sphericalHarmonics=new Bo,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new G,this._updateReflectionCubeMap=()=>{var s;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const r=Date.now();if(r-this._cubeMapPollTime<this.options.cubeMapPollInterval)return;this._cubeMapPollTime=r}const i=this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);if(i&&this._reflectionCubeMap){if(this._reflectionCubeMap._texture)(s=this._reflectionCubeMap._texture._hardwareTexture)==null||s.set(i),this._reflectionCubeMap._texture.getEngine().resetTextureCache();else{const r=new Tt(this._xrSessionManager.scene.getEngine(),et.Unknown);r.isCube=!0,r.invertY=!1,r._useSRGBBuffer=this.options.reflectionFormat==="srgba8",r.format=5,r.generateMipMaps=!0,r.type=this.options.reflectionFormat!=="srgba8"?2:0,r.samplingMode=3,r.width=this._reflectionCubeMapTextureSize,r.height=this._reflectionCubeMapTextureSize,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new Ec(i,this._getCanvasContext()),this._reflectionCubeMap._texture=r}this._reflectionCubeMap._texture.isReady=!0,this.options.disablePreFiltering?(this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap)):(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._hdrFilter.prefilter(this._reflectionCubeMap).then(()=>{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)}))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new Hr("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new m(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Nt.FALLOFF_GLTF),this._hdrFilter=new OS(this._xrSessionManager.scene.getEngine()),X.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return this._canvasContext===null&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(this._xrWebGLBinding===null){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then(t=>{this._xrLightProbe=t,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Et(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){const e=super.detach();return this._xrLightProbe!==null&&!this.options.disableCubeMapReflection&&(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),this._reflectionCubeMap!==null&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(this._xrLightProbe!==null){if(this.options.lightEstimationPollInterval){const i=Date.now();if(i-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=i}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);const i=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new m,this._lightColor=new q,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*i),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new ma,(t=this._reflectionCubeMap.sphericalPolynomial)==null||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}}}uu.Name=dt.LIGHT_ESTIMATION;uu.Version=1;fi.AddWebXRFeature(uu.Name,(a,e)=>()=>new uu(a,e),uu.Version,!1);class du extends _s{constructor(e){super(e),this.onEyeTrackingStartedObservable=new G,this.onEyeTrackingEndedObservable=new G,this.onEyeTrackingFrameUpdateObservable=new G,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new tt(m.Zero(),m.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(!(!this.attached||!e)&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const i=t.transform.orientation;U.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?m.RightHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,U.Quaternion[0].z*=-1,U.Quaternion[0].w*=-1,m.LeftHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}du.Name=dt.EYE_TRACKING;du.Version=1;fi.AddWebXRFeature(du.Name,a=>()=>new du(a),du.Version,!1);class vU{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i<e;++i)this._samples.push(t?t():Z.Zero())}get length(){return this._samples.length}push(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)}at(e){if(e>=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class bU{constructor(){this._samples=new vU(20),this._entropy=0,this.onFirstStepDetected=new G}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=Z.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;n<this._samples.length&&!(Z.DistanceSquared(r,this._samples.at(n))<this._samePointSquaredDistanceThreshold);++n);if(n===this._samples.length)return;let o=-1,l=0;for(let C,v=1;v<n;++v)C=Z.DistanceSquared(r,this._samples.at(v)),C>o&&(l=v,o=C);if(o<this._apexSquaredDistanceThreshold)return;const h=this._samples.at(l),c=h.subtract(r);c.normalize();const u=U.Vector2[0];let d,f,_=0;for(let C=1;C<n;++C)f=this._samples.at(C),f.subtractToRef(r,u),d=Z.Dot(c,u),_+=u.lengthSquared()-d*d;if(_>n*this._squaredProjectionDistanceThreshold)return;const p=U.Vector3[0];p.set(i,s,0);const g=U.Vector3[1];g.set(c.x,c.y,0);const x=m.Cross(p,g).z>0,T=r.clone(),S=r.clone();h.subtractToRef(r,c),x?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,T),c.scaleAndAddToRef(this._axisToApexExtendFactor,S)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,T),c.scaleAndAddToRef(this._axisToApexShrinkFactor,S)),this.onFirstStepDetected.notifyObservers({leftApex:T,rightApex:S,currentPosition:r,currentStepDirection:x?"right":"left"})}reset(){for(let e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)}get _samePointCheckStartIdx(){return Math.floor(this._samples.length/3)}get _samePointSquaredDistanceThreshold(){return .03*.03}get _apexSquaredDistanceThreshold(){return .09*.09}get _squaredProjectionDistanceThreshold(){return .03*.03}get _axisToApexShrinkFactor(){return .8}get _axisToApexExtendFactor(){return-1.6}get _entropyDecayFactor(){return .93}get _entropyThreshold(){return .4}}class AU{constructor(e,t,i,s){this._leftApex=new Z,this._rightApex=new Z,this._currentPosition=new Z,this._axis=new Z,this._axisLength=-1,this._forward=new Z,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new Z,this._vitality=0,this.onMovement=new G,this.onFootfall=new G,this._reset(e,t,i,s==="left")}_reset(e,t,i,s){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=s,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1}_updateTAndVitality(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);const i=this._t,s=Z.Dot(this._currentPosition,this._axis);this._t=s/(this._axisLength*this._axisLength);const r=this._currentPosition.lengthSquared()-s/this._axisLength*(s/this._axisLength);this._vitality*=.92-100*Math.max(r-.0016,0)+Math.max(this._t-i,0)}update(e,t){if(this._vitality<this._vitalityThreshold)return!1;const i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold||(this._t>i&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}}class fu{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new bU,this._walker=null,this._movement=new Z,this._millisecondsSinceLastUpdate=fu._MillisecondsPerUpdate,this.movementThisFrame=m.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new AU(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{O.Log("Footfall!")}),this._walker.onMovement.add(i=>{this._walker.forward.scaleAndAddToRef(.024*i.deltaT,this._movement)}))})}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=fu._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=fu._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class K_ extends _s{static get Name(){return dt.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera=this._locomotionTarget.getClassName()==="WebXRCamera"}constructor(e,t){super(e),this._up=new m,this._forward=new m,this._position=new m,this._movement=new m,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&O.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return this._sessionManager.sessionMode===void 0||this._sessionManager.sessionMode==="immersive-vr"}attach(){return!this.isCompatible||!super.attach()?!1:(this._walker=new fu(this._sessionManager.scene.getEngine()),!0)}detach(){return super.detach()?(this._walker=null,!0):!1}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||m.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}fi.AddWebXRFeature(K_.Name,(a,e)=>()=>new K_(a,e),K_.Version,!1);class FC extends Bm{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class wC extends Um{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new G,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s=t=="right"?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||(i==null?void 0:i.textureWidth)!==r||(i==null?void 0:i.textureHeight)!==n){let o;const l=e.depthStencilTextureWidth??r,h=e.depthStencilTextureHeight??n;(r===l||n===h)&&(o=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,o,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e==null?void 0:e.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class yU extends FC{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,s=>new RU(s,i,this)),this.layer=e}}class RU extends wC{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}}const HT={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},IU={};class _u extends _s{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...HT,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return super.detach()?(this._existingLayers.forEach(e=>{e.dispose()}),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0):!1}createXRWebGLLayer(e=IU){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Vm(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&e.textureType!=="texture-array")throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&e.textureType==="texture-array")throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=HT,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new yU(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new FC(()=>n.width,()=>n.height,n,"XRQuadLayer",!1,h=>new wC(h,this._xrWebGLBinding,o));t&&this._compositionLayerTextureMapping.set(n,t);const l=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,l),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,n={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)},o={x:0,y:0,z:0,w:1};s.transform=new XRRigidTransform(n,o);const l=this._layerToRTTProviderMapping.get(s);if(!l)throw new Error("Could not find the RTT provider for the layer");const h=this._xrSessionManager.scene.layers.find(c=>c.texture===e);if(!h)throw new Error("Could not find the babylon layer for the texture");return l.onRenderTargetTextureCreatedObservable.add(c=>{c.eye&&c.eye==="right"||(c.texture.clearColor=new xe(0,0,0,0),h.renderTargetTextures.push(c.texture),h.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add(()=>{c.texture.render()}),h.renderTargetTextures.push(c.texture),h.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce(()=>{h.renderTargetTextures.splice(h.renderTargetTextures.indexOf(c.texture),1),h.renderOnlyInRenderTargetTextures=!1}))}),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;const r={x:0,y:0,z:-10},n={x:0,y:0,z:0,w:1};i.transform=new XRRigidTransform(r,n);const o=this._layerToRTTProviderMapping.get(i);if(!o)throw new Error("Could not find the RTT provider for the layer");return o.onRenderTargetTextureCreatedObservable.add(l=>{l.texture.clearColor=new xe(0,0,0,0),l.texture.customRenderFunction=()=>{e.render()}}),this._xrSessionManager.onXRSessionInit.add(()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)}),this._xrSessionManager.onXRSessionEnded.add(()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)}),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i<t.length;++i){const s=t[i];if(s.layerType!=="XRProjectionLayer"){const r=this._layerToRTTProviderMapping.get(s.layer);if(!r)continue;if(r.layerWrapper.isMultiview){const n=e.getViewerPose(this._xrSessionManager.referenceSpace);if(n){const o=n.views;for(let l=0;l<o.length;++l){const h=o[l];r.getRenderTargetTextureForView(h)}}}else r.getRenderTargetTextureForView()}}}}_u.Name=dt.LAYERS;_u.Version=1;fi.AddWebXRFeature(_u.Name,(a,e)=>()=>new _u(a,e),_u.Version,!1);class pu extends _s{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new Tt(e,et.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format=this.depthDataFormat==="ushort"?2:5,t.generateMipMaps=!1,t.type=this.depthDataFormat==="ushort"?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Ec(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?this.depthDataFormat==="ushort"?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new G,this.xrNativeFeatureName="depth-sensing",X.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!super.attach(e)||this._xrSessionManager.session.depthDataFormat==null||this._xrSessionManager.session.depthUsage==null?!1:(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;(e=this._cachedDepthImageTexture)==null||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(i!=null)for(const s of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,s,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,s,this.depthDataFormat);break;default:X.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{data:r,width:n,height:o,rawValueToMeters:l,getDepthInMeters:h}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=l,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(h.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Fi.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,k.NEAREST_SAMPLINGMODE,H.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map(c=>c*l));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map(c=>c*l));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const l=this._xrSessionManager.scene,c=l.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Fi.CreateRTexture(null,n,o,l,!1,!0,k.NEAREST_SAMPLINGMODE,i==="ushort"?H.TEXTURETYPE_UNSIGNED_BYTE:H.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=c}getXRSessionInitExtension(){const e=this.options.usagePreference!=null&&this.options.usagePreference.length!==0,t=this.options.dataFormatPreference!=null&&this.options.dataFormatPreference.length!==0;return new Promise(i=>{if(e&&t){const s=this.options.usagePreference.map(n=>{switch(n){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),r=this.options.dataFormatPreference.map(n=>{switch(n){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:s,dataFormatPreference:r}})}else i({})})}}pu.Name=dt.DEPTH_SENSING;pu.Version=1;fi.AddWebXRFeature(pu.Name,(a,e)=>()=>new pu(a,e),pu.Version,!1);const PU="velocityPixelShader",MU=`precision highp float;
#define CUSTOM_FRAGMENT_BEGIN
varying vec4 clipPos;varying vec4 previousClipPos;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;
#define CUSTOM_FRAGMENT_MAIN_END
}`;W.ShadersStore[PU]=MU;const DU="velocityVertexShader",OU=`#define CUSTOM_VERTEX_BEGIN
#define VELOCITY
attribute vec3 position;
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform mat4 previousViewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;
#endif
varying vec4 clipPos;varying vec4 previousClipPos;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#include<instancesVertex>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}
#elif
clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}`;W.ShadersStore[DU]=OU;class NU extends oi{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[D.Identity(),D.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Qs("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(r=>{this._previousWorldMatrices[r.uniqueId]=this._previousWorldMatrices[r.uniqueId]||r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[r.uniqueId]),this._previousWorldMatrices[r.uniqueId]=r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(s=>{this._originalPairing.push([s,s.material]),s.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(s=>{s[0].material=s[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class FU{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if(t.layerType!=="XRProjectionLayer")throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new NU(s,r,this._scene,n),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return(!s||(i==null?void 0:i.textureWidth)!==r||(i==null?void 0:i.textureHeight)!=n)&&(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class mu extends _s{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[dt.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new FU(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}mu.Name=dt.SPACE_WARP;mu.Version=1;fi.AddWebXRFeature(mu.Name,a=>()=>new mu(a),mu.Version,!1);class gu extends _s{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new G,this.xrNativeFeatureName="camera-access"}attach(e){return super.attach(e)?(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0):!1}detach(){return super.detach()?(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0):!1}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],l=i.height/2*s[5],h=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:l,gamma:h,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var s,r;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(s=this._glBinding)==null?void 0:s.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(r=this._cachedInternalTextures[t]._hardwareTexture)==null||r.set(i);else{const n=new Tt(this._xrSessionManager.scene.getEngine(),et.Unknown,!0);n.isCube=!0,n.invertY=!1,n.format=5,n.generateMipMaps=!0,n.type=1,n.samplingMode=3,n.width=e.camera.width,n.height=e.camera.height,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new Ec(i,this._glContext),this._cachedInternalTextures[t]=n;const o=new Et(this._xrSessionManager.scene);o.name=`WebXR Raw Camera Access (${t})`,o._texture=this._cachedInternalTextures[t],this.texturesData[t]=o,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach((r,n)=>{s=s&&this._updateInternalTextures(r,n)}),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}gu.Name=dt.RAW_CAMERA_ACCESS;gu.Version=1;fi.AddWebXRFeature(gu.Name,(a,e)=>()=>new gu(a,e),gu.Version,!1);class wU extends Ic{constructor(e,t,i){super(e,LU[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}hs.RegisterController("generic-hand-select-grasp",(a,e)=>new wU(e,a.gamepad,a.handedness));const LU={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class ja extends Ic{constructor(e,t,i){super(e,BU["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=ja.MODEL_LEFT_FILENAME:e=ja.MODEL_RIGHT_FILENAME;const t="default",i=ja.MODEL_BASE_URL+t+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=je.IsPluginForExtensionAvailable(".glb");return e||O.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((t,i)=>{if(!this.disableAnimation&&t&&this.rootMesh){const s=this._mapping.buttons[t],r=s.rootNodeName;if(!r){O.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){O.Warn("Missing button mesh with name: "+r);return}if(s.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.valueNodeName),s.pressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.pressedNodeName),s.unpressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.unpressedNodeName),s.valueMesh&&s.pressedMesh&&s.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else O.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(s=>{if(!this.rootMesh)return;const r=this._mapping.axes[t][s],n=this._getChildByName(this.rootMesh,r.rootNodeName);if(!n){O.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=s==="x-axis"?o.x:o.y;this._lerpTransform(r,l,!0)},void 0,!0):O.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new z(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i<e.length;i++){const s=e[i];s.isPickable=!1,s.parent||(t=s)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Q.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}ja.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/";ja.MODEL_LEFT_FILENAME="left.glb";ja.MODEL_RIGHT_FILENAME="right.glb";hs.RegisterController("windows-mixed-reality",(a,e)=>new ja(e,a.gamepad,a.handedness));const BU={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class En extends Ic{constructor(e,t,i,s=!1,r=!1){super(e,UU[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=En.MODEL_LEFT_FILENAME:e=En.MODEL_RIGHT_FILENAME;const t=this._isQuest()?En.QUEST_MODEL_BASE_URL:En.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i=this.handedness==="right"?-1:1;this.getComponentIds().forEach(s=>{const r=s&&this.getComponent(s);r&&r.onButtonStateChangedObservable.add(n=>{if(!(!this.rootMesh||this.disableAnimation))switch(s){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-n.value*.2,this._modelRootNode.getChildren()[3].position.y=-n.value*.005,this._modelRootNode.getChildren()[3].position.z=-n.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new z(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Q.FromEulerAngles(0,Math.PI,0)),e.forEach(t=>{t.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}En.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";En.MODEL_LEFT_FILENAME="left.babylon";En.MODEL_RIGHT_FILENAME="right.babylon";En.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";hs.RegisterController("oculus-touch",(a,e)=>new En(e,a.gamepad,a.handedness));hs.RegisterController("oculus-touch-legacy",(a,e)=>new En(e,a.gamepad,a.handedness,!0));const UU={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class $l extends Ic{constructor(e,t,i){super(e,VU[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=$l.MODEL_FILENAME,t=$l.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=t&&this.getComponent(t);i&&i.onButtonStateChangedObservable.add(s=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-s.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new z(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Q.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}$l.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";$l.MODEL_FILENAME="wand.babylon";hs.RegisterController("htc-vive",(a,e)=>new $l(e,a.gamepad,a.handedness));const VU={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class kU{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(4+4),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}$I("NativeXRFrame",kU);var yr;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(yr||(yr={}));class Cp{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=en(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=X.Instantiate(e.className),s=new i(e.name,e._connectionType,t);return s.deserialize(e),s}}class Ri{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new Ri(this.value+e.value)}subtract(e){return new Ri(this.value-e.value)}multiply(e){return new Ri(Math.imul(this.value,e.value))}divide(e){return new Ri(this.value/e.value)}getClassName(){return Ri.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Ri(e.value)}}Ri.ClassName="FlowGraphInteger";V("FlowGraphInteger",Ri);class dr{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new dr(e.typeName,e.defaultValue)}}const Te=new dr("any",void 0),GU=new dr("string",""),zt=new dr("number",0),xs=new dr("boolean",!1),vp=new dr("Vector2",Z.Zero()),fa=new dr("Vector3",m.Zero()),zU=new dr("Vector4",we.Zero()),qa=new dr("Matrix",D.Identity()),WU=new dr("Color3",q.Black()),HU=new dr("Color4",new xe(0,0,0,0)),XU=new dr("Quaternion",Q.Identity()),Ii=new dr("FlowGraphInteger",new Ri(0));function YU(a){switch(typeof a){case"string":return GU;case"number":return zt;case"boolean":return xs;case"object":return a instanceof Z?vp:a instanceof m?fa:a instanceof we?zU:a instanceof q?WU:a instanceof xe?HU:a instanceof Q?XU:a instanceof Ri?Ii:Te;default:return Te}}class bp extends Cp{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===yr.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===yr.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=Cp.Parse(e,t);return i.richType=dr.Parse(e.richType),i}}V("FGDataConnection",bp);function LC(a){return a==="Mesh"||a==="AbstractMesh"||a==="GroundMesh"||a==="InstanceMesh"||a==="LinesMesh"||a==="GoldbergMesh"||a==="GreasedLineMesh"||a==="TrailMesh"}function BC(a){return a==="Vector2"||a==="Vector3"||a==="Vector4"||a==="Quaternion"||a==="Color3"||a==="Color4"}function $U(a,e){if(a==="Vector2")return Z.FromArray(e);if(a==="Vector3")return m.FromArray(e);if(a==="Vector4")return we.FromArray(e);if(a==="Quaternion")return Q.FromArray(e);if(a==="Color3")return new q(e[0],e[1],e[2]);if(a==="Color4")return new xe(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${a}`)}function Fg(a,e,t){var s;const i=((s=e==null?void 0:e.getClassName)==null?void 0:s.call(e))??"";LC(i)?t[a]={name:e.name,className:i}:BC(i)?t[a]={value:e.asArray(),className:i}:t[a]=e}function m_(a,e,t){const i=e[a];let s;const r=i==null?void 0:i.className;return LC(r)?s=t.getMeshByName(i.name):BC(r)?s=$U(r,i.value):r==="Matrix"?s=D.FromArray(i.value):r===Ri.ClassName?s=Ri.Parse(i):i&&i.value!==void 0?s=i.value:s=i,s}function KU(a){return a==="FGSetPropertyBlock"||a==="FGGetPropertyBlock"||a==="FGPlayAnimationBlock"||a==="FGMeshPickEventBlock"}class _o{constructor(e){var t;this.config=e,this.uniqueId=en(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new bp(e,yr.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new bp(e,yr.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=Fg){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const i of this.dataInputs){const s={};i.serialize(s),e.dataInputs.push(s)}for(const i of this.dataOutputs){const s={};i.serialize(s),e.dataOutputs.push(s)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=X.Instantiate(e.className),s={},r=t.valueParseFunction??m_;if(e.config)for(const o in e.config)s[o]=r(o,e.config,t.scene);KU(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let o=0;o<e.dataInputs.length;o++){const l=n.getDataInput(e.dataInputs[o].name);if(l)l.deserialize(e.dataInputs[o]);else throw new Error("Could not find data input with name "+e.dataInputs[o].name+" in block "+e.className)}for(let o=0;o<e.dataOutputs.length;o++){const l=n.getDataOutput(e.dataOutputs[o].name);if(l)l.deserialize(e.dataOutputs[o]);else throw new Error("Could not find data output with name "+e.dataOutputs[o].name+" in block "+e.className)}return n.metadata=e.metadata,n.deserialize&&n.deserialize(e),n}}class Ap extends Cp{_isSingularConnection(){return this.connectionType===yr.Output}_activateSignal(e){var t;this.connectionType===yr.Input?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._execute(e,this),e._increaseExecutionId()):(t=this._connectedPoint[0])==null||t._activateSignal(e)}}V("FlowGraphSignalConnection",Ap);class Yn extends _o{constructor(e){super(e),this.signalInputs=[],this.signalOutputs=[],this.in=this._registerSignalInput("in")}_registerSignalInput(e){const t=new Ap(e,yr.Input,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){const t=new Ap(e,yr.Output,this);return this.signalOutputs.push(t),t}getSignalInput(e){return this.signalInputs.find(t=>t.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t<e.signalInputs.length;t++){const i=this.getSignalInput(e.signalInputs[t].name);if(i)i.deserialize(e.signalInputs[t]);else throw new Error("Could not find signal input with name "+e.signalInputs[t].name+" in block "+e.className)}for(let t=0;t<e.signalOutputs.length;t++){const i=this.getSignalOutput(e.signalOutputs[t].name);if(i)i.deserialize(e.signalOutputs[t]);else throw new Error("Could not find signal output with name "+e.signalOutputs[t].name+" in block "+e.className)}}getClassName(){return"FGExecutionBlock"}}class wg extends Yn{constructor(e){super(e),this.out=this._registerSignalOutput("out"),this.done=this._registerSignalOutput("done")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}}class hd extends wg{_execute(e){e._notifyExecuteNode(this),this.out._activateSignal(e)}}class yp{constructor(e){this.uniqueId=en(),this._userVariables={},this._executionVariables={},this._connectionValues={},this._pendingBlocks=[],this._executionId=0,this.onNodeExecutedObservable=new G,this._configuration=e}hasVariable(e){return e in this._userVariables}setVariable(e,t){this._userVariables[e]=t}getVariable(e){return this._userVariables[e]}get userVariables(){return this._userVariables}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables[this._getUniqueIdPrefixedName(e,t)]=i}_getExecutionVariable(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables[this._getUniqueIdPrefixedName(e,t)]:i}_deleteExecutionVariable(e,t){delete this._executionVariables[this._getUniqueIdPrefixedName(e,t)]}_hasExecutionVariable(e,t){return this._getUniqueIdPrefixedName(e,t)in this._executionVariables}_hasConnectionValue(e){return e.uniqueId in this._connectionValues}_setConnectionValue(e,t){this._connectionValues[e.uniqueId]=t}_getConnectionValue(e){return this._connectionValues[e.uniqueId]}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){const t=this._pendingBlocks.indexOf(e);t!==-1&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(const e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_notifyExecuteNode(e){this.onNodeExecutedObservable.notifyObservers(e)}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=Fg){e.uniqueId=this.uniqueId,e._userVariables={};for(const i in this._userVariables)t(i,this._userVariables[i],e._userVariables);e._connectionValues={};for(const i in this._connectionValues)t(i,this._connectionValues[i],e._connectionValues)}getClassName(){return"FGContext"}static Parse(e,t){const i=t.graph.createContext(),s=t.valueParseFunction??m_;i.uniqueId=e.uniqueId;for(const r in e._userVariables){const n=s(r,e._userVariables,i._configuration.scene);i._userVariables[r]=n}for(const r in e._connectionValues){const n=s(r,e._connectionValues,i._configuration.scene);i._connectionValues[r]=n}return i}}E([I()],yp.prototype,"uniqueId",void 0);function Lg(a,e){return!!(a.parent&&(a.parent===e||Lg(a.parent,e)))}class Kl extends hd{constructor(e){super(e),this.config=e}_getReferencedMesh(){const e=this.config.pathConverter.convert(this.config.path),t=e.info.getObject(e.object);if(!t||!(t instanceof ut))throw new Error("Mesh pick event block requires a valid mesh");return t}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){const i=this._getReferencedMesh();e._setExecutionVariable(this,"mesh",i),t=i.getScene().onPointerObservable.add(r=>{var n,o,l;r.type===Re.POINTERPICK&&((n=r.pickInfo)!=null&&n.pickedMesh)&&(((o=r.pickInfo)==null?void 0:o.pickedMesh)===i||Lg((l=r.pickInfo)==null?void 0:l.pickedMesh,i))&&this._execute(e)});const s=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return Kl.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}Kl.ClassName="FGMeshPickEventBlock";V(Kl.ClassName,Kl);var bo;(function(a){a[a.Stopped=0]="Stopped",a[a.Started=1]="Started"})(bo||(bo={}));class jl{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=bo.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){const e=new yp({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==bo.Started){this.state=bo.Started,this._executionContexts.length===0&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===Kl.ClassName){const i=t._getReferencedMesh();let s=0;for(;s<e.length;s++){const n=e[s]._getReferencedMesh();if(i&&n&&Lg(i,n))break}e.splice(s,0,t)}else e.push(t);return e}dispose(){if(this.state!==bo.Stopped){this.state=bo.Stopped;for(const e of this._executionContexts)e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){const t=[],i=new Set;for(const s of this._eventBlocks)t.push(s),i.add(s.uniqueId);for(;t.length>0;){const s=t.pop();e(s);for(const r of s.dataInputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId));if(s instanceof Yn)for(const r of s.signalOutputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const s={};i.serialize(s),e.allBlocks.push(s)}),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const s of i.dataOutputs)if(s.uniqueId===t)return s;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof Yn){for(const s of i.signalInputs)if(s.uniqueId===t)return s}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??m_;for(const n of e.allBlocks){const o=_o.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(o),o instanceof hd&&i.addEventBlock(o)}for(const n of s){for(const o of n.dataInputs)for(const l of o.connectedPointIds){const h=jl.GetDataOutConnectionByUniqueId(s,l);o.connectTo(h)}if(n instanceof Yn)for(const o of n.signalOutputs)for(const l of o.connectedPointIds){const h=jl.GetSignalInConnectionByUniqueId(s,l);o.connectTo(h)}}for(const n of e.executionContexts)yp.Parse(n,{graph:i,valueParseFunction:r});return i}}class Dl{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(Dl.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new jl({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);t!==-1&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){this._flowGraphs.forEach(i=>i.dispose()),this._flowGraphs.length=0;const e=Dl.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);t!==-1&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)})}static Parse(e,t){var r;const i=t.valueParseFunction??m_,s=new Dl({scene:t.scene});return(r=e._flowGraphs)==null||r.forEach(n=>{jl.Parse(n,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})}),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new G,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}Dl.SceneCoordinators=new Map;class $r extends Yn{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class ql extends $r{constructor(e){super(e),this.message=this.registerDataInput("message",Te)}_execute(e){const t=this.message.getValue(e);O.Log(t),this.out._activateSignal(e)}getClassName(){return ql.ClassName}}ql.ClassName="FGConsoleLogBlock";V(ql.ClassName,ql);class Ql extends $r{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Te)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return Ql.ClassName}}Ql.ClassName="FGSetVariableBlock";V(Ql.ClassName,Ql);const XT=new RegExp(/\{(\w+)\}/g);class Tf{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=XT.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,Ii)),i=XT.exec(e)}}getAccessor(e,t){let i=this.path;for(const s of this.templatedInputs){const r=s.getValue(t).value;i=i.replace(`{${s.name}}`,r.toString())}return e.convert(i)}}class cd extends $r{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Te),this.templateComponent=new Tf(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return cd.ClassName}}cd.ClassName="FGSetPropertyBlock";V("FGSetPropertyBlock",cd);class ud extends $r{constructor(e){super(e),this.config=e;for(let t=0;t<this.config.eventData.length;t++){const i=this.config.eventData[t];this.registerDataInput(i,Te)}}_execute(e){const t=this.config.eventId,i=this.dataInputs.map(s=>s.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return ud.ClassName}}ud.ClassName="FGSendCustomEventBlock";V("FGSendCustomEventBlock",ud);class jU extends Yn{constructor(e){super(e),this.condition=this.registerDataInput("condition",xs),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}V("FGBranchBlock",jU);class Zl extends $r{constructor(e={startIndex:new Ri(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Ii),this.value=this.registerDataOutput("value",Ii)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.value<this.n.getValue(e).value&&(this.value.setValue(new Ri(i.value+1),e),this.out._activateSignal(e))}}getClassName(){return Zl.ClassName}}Zl.ClassName="FGDoNBlock";V(Zl.ClassName,Zl);class qU extends $r{constructor(e){super(e),this.startIndex=this.registerDataInput("startIndex",zt),this.endIndex=this.registerDataInput("endIndex",zt),this.step=this.registerDataInput("step",zt),this.index=this.registerDataOutput("index",zt),this.onLoop=this._registerSignalOutput("onLoop")}_executeLoop(e){let t=e._getExecutionVariable(this,"index");const i=e._getExecutionVariable(this,"endIndex");if(t<i){this.index.setValue(t,e),this.onLoop._activateSignal(e);const s=e._getExecutionVariable(this,"step",1);t+=s,e._setExecutionVariable(this,"index",t),this._executeLoop(e)}else this.out._activateSignal(e)}_execute(e){const t=this.startIndex.getValue(e),i=this.endIndex.getValue(e),s=this.step.getValue(e);e._setExecutionVariable(this,"index",t),e._setExecutionVariable(this,"endIndex",i),e._setExecutionVariable(this,"step",s),this._executeLoop(e)}getClassName(){return"FGForLoopBlock"}}V("FGForLoopBlock",qU);class QU extends $r{constructor(e){super(e),this.reset=this._registerSignalInput("reset"),this.duration=this.registerDataInput("duration",zt),this.timeRemaining=this.registerDataOutput("timeRemaining",zt)}_execute(e,t){const i=e._getExecutionVariable(this,"lastExecutedTime"),s=this.duration.getValue(e),r=Date.now();if(t===this.reset||i===void 0||r-i>s)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const n=s-(r-i);this.timeRemaining.setValue(n,e)}}getClassName(){return"FGThrottleBlock"}}V("FGThrottleBlock",QU);class dd extends wg{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",zt)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new KD({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);s!==-1?i.splice(s,1):X.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const i of t)i.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return dd.ClassName}}dd.ClassName="FGTimerBlock";V("FGTimerBlock",dd);class ZU extends Yn{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",zt),this.config.startIndex=this.config.startIndex!==void 0?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows.push(this._registerSignalOutput(`out${t}`))}_getUnusedIndexes(e){const t=this._cachedUnusedIndexes;if(t.length=0,e._hasExecutionVariable(this,"unusedIndexes")){const i=e._getExecutionVariable(this,"unusedIndexes");for(let s=0;s<i.length;s++)t.push(i[s])}else for(let i=0;i<this.config.numberOutputFlows;i++)t.push(i);return t}_getNextOutput(e,t){if(this.config.isRandom){const i=Math.floor(Math.random()*t.length);return t[i]}else return e+1}_execute(e,t){const i=e._getExecutionVariable(this,"currentIndex")??this.config.startIndex-1;let s=this._getUnusedIndexes(e);if(t===this.reset){e._deleteExecutionVariable(this,"currentIndex"),e._deleteExecutionVariable(this,"unusedIndexes");return}let r=this._getNextOutput(i,s);if(r>=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter(n=>n!==r),s.length===0)for(let n=0;n<this.config.numberOutputFlows;n++)s.push(n);e._setExecutionVariable(this,"unusedIndexes",s),e._setExecutionVariable(this,"currentIndex",r),this.currentIndex.setValue(r,e),this.outFlows[r]._activateSignal(e)}getClassName(){return"FGMultiGateBlock"}serialize(e){super.serialize(e),e.config.numberOutputFlows=this.config.numberOutputFlows,e.config.isRandom=this.config.isRandom,e.config.loop=this.config.loop,e.config.startIndex=this.config.startIndex}}V("FGMultiGateBlock",ZU);class JU extends Yn{constructor(e){super(e),this.config=e,this.selection=this.registerDataInput("selection",Te),this.outputFlows=[];for(let t=0;t<=this.config.cases.length;t++)this.outputFlows.push(this._registerSignalOutput(`out${t}`))}_execute(e,t){const i=this.selection.getValue(e);for(let s=0;s<this.config.cases.length;s++)if(i===this.config.cases[s]){this.outputFlows[s]._activateSignal(e);return}this.outputFlows[this.outputFlows.length-1]._activateSignal(e)}getClassName(){return"FGSwitchBlock"}serialize(e){super.serialize(e),e.cases=this.config.cases}}V("FGSwitchBlock",JU);class eV extends $r{constructor(e){super(e),this.config=e,this.inFlows=[],this._cachedActivationState=[],this.reset=this._registerSignalInput("reset");for(let t=1;t<this.config.numberInputFlows;t++)this.inFlows.push(this._registerSignalInput(`in${t}`))}_getCurrentActivationState(e){const t=this._cachedActivationState;if(t.length=0,e._hasExecutionVariable(this,"activationState")){const i=e._getExecutionVariable(this,"activationState");for(let s=0;s<i.length;s++)t.push(i[s])}else for(let i=0;i<this.config.numberInputFlows;i++)t.push(!1);return t}_execute(e,t){const i=this._getCurrentActivationState(e);if(t===this.reset)for(let s=0;s<this.config.numberInputFlows;s++)i[s]=!1;else if(t===this.in)i[0]=!0;else{const s=this.inFlows.indexOf(t);s>=0&&(i[s+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(s=>s)){this.out._activateSignal(e);for(let s=0;s<this.config.numberInputFlows;s++)i[s]=!1}}getClassName(){return"FGWaitAllBlock"}serialize(e){super.serialize(e),e.config.numberInputFlows=this.config.numberInputFlows}}V("FGWaitAllBlock",eV);class tV extends $r{constructor(e){super(e),this.count=this.registerDataOutput("count",zt),this.reset=this._registerSignalInput("reset")}_execute(e,t){if(t===this.reset){e._setExecutionVariable(this,"count",0),this.count.setValue(0,e);return}const i=(e._getExecutionVariable(this,"count")??0)+1;e._setExecutionVariable(this,"count",i),this.count.setValue(i,e),this.out._activateSignal(e)}getClassName(){return"FGCounterBlock"}}V("FGCounterBlock",tV);class Jl extends $r{constructor(e){super(e),this.config=e,this.condition=this.registerDataInput("condition",xs),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){var s;let i=this.condition.getValue(e);for((s=this.config)!=null&&s.isDo&&!i&&this.loopBody._activateSignal(e);i;)this.loopBody._activateSignal(e),i=this.condition.getValue(e);this.out._activateSignal(e)}getClassName(){return Jl.ClassName}serialize(e){var t;super.serialize(e),e.isDo=(t=this.config)==null?void 0:t.isDo}}Jl.ClassName="FGWhileLoopBlock";V(Jl.ClassName,Jl);class iV extends $r{constructor(e){super(e),this.count=this.registerDataInput("count",zt),this.reset=this._registerSignalInput("reset"),this.currentCount=this.registerDataOutput("currentCount",zt)}_execute(e,t){if(t===this.reset){e._setExecutionVariable(this,"debounceCount",0);return}const i=this.count.getValue(e),r=e._getExecutionVariable(this,"debounceCount",0)+1;this.currentCount.setValue(r,e),e._setExecutionVariable(this,"debounceCount",r),r>=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}V("FGDebounceBlock",iV);class sV extends Yn{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",xs)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}V("FGFlipFlopBlock",sV);class eh extends Yn{constructor(e){super(e),this.config=e,this.outFlows=[];for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows.push(this._registerSignalOutput(`${t}`))}_execute(e){for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows[t]._activateSignal(e)}getClassName(){return eh.ClassName}}eh.ClassName="FGSequenceBlock";V(eh.ClassName,eh);class Vu extends wg{constructor(e){super(e),this.config=e,this.templateTargetComponent=new Tf(e.targetPath,this),this.templateAnimationComponent=new Tf(e.animationPath,this),this.speed=this.registerDataInput("speed",zt),this.loop=this.registerDataInput("loop",xs),this.from=this.registerDataInput("from",zt),this.to=this.registerDataInput("to",zt),this.runningAnimatable=this.registerDataOutput("runningAnimatable",Te)}_preparePendingTasks(e){const t=this.templateTargetComponent.getAccessor(this.config.pathConverter,e),i=t.info.getObject(t.object),s=this.templateAnimationComponent.getAccessor(this.config.pathConverter,e),r=s.info.get(s.object);if(!i||!r)throw new Error("Cannot play animation without target or animation");const n=e._getExecutionVariable(this,"runningAnimatables")??[],o=this.runningAnimatable.getValue(e);if(o&&o.paused)o.restart();else{const h=e.configuration.scene.beginDirectAnimation(i,[r],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),()=>this._onAnimationEnd(h,e));this.runningAnimatable.setValue(h,e),n.push(h)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);s!==-1&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const i of t)i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Vu.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Vu.ClassName="FGPlayAnimationBlock";V(Vu.ClassName,Vu);class rV extends $r{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Te)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}V("FGStopAnimationBlock",rV);class nV extends $r{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Te)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}V("FGPauseAnimationBlock",nV);class aV extends _o{constructor(e){super(e),this.condition=this.registerDataInput("condition",xs),this.trueValue=this.registerDataInput("trueValue",Te),this.falseValue=this.registerDataInput("falseValue",Te),this.output=this.registerDataOutput("output",Te)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}V("FGConditionalDataBlock",aV);class th extends _o{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Te)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return th.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}th.ClassName="FGGetVariableBlock";V(th.ClassName,th);class oV extends _o{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Te),this.destinationSystem=this.registerDataInput("destinationSystem",Te),this.inputCoordinates=this.registerDataInput("inputCoordinates",fa),this.outputCoordinates=this.registerDataOutput("outputCoordinates",fa)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=U.Matrix[0].copyFrom(n);o.invert();const l=U.Matrix[1];o.multiplyToRef(r,l);const h=this.outputCoordinates.getValue(e);m.TransformCoordinatesToRef(s,l,h)}getClassName(){return"FGCoordinateTransformBlock"}}V("FGCoordinateTransformBlock",oV);class lV extends _o{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",YU(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Fg){super.serialize(e),t("value",this.config.value,e.config)}}V("FGConstantBlock",lV);class ih extends _o{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Te),this.templateComponent=new Tf(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return ih.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}ih.ClassName="FGGetPropertyBlock";V(ih.ClassName,ih);const YT="cachedOperationValue",$T="cachedExecutionId";class g_ extends _o{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,$T),i=e._getExecutionVariable(this,YT);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const s=this._doOperation(e);e._setExecutionVariable(this,YT,s),e._setExecutionVariable(this,$T,e.executionId),this.value.setValue(s,e)}}}class Vi extends g_{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Mt extends g_{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Uc="FGLogic",UC="AndBlock",VC="OrBlock",kC="NotBlock";class hV extends Vi{constructor(e){super(xs,xs,xs,(t,i)=>t&&i,`${Uc}${UC}`,e)}}V(`${Uc}${UC}`,hV);class cV extends Vi{constructor(e){super(xs,xs,xs,(t,i)=>t||i,`${Uc}${VC}`,e)}}V(`${Uc}${VC}`,cV);class uV extends Mt{constructor(e){super(xs,xs,t=>!t,`${Uc}${kC}`,e)}}V(`${Uc}${kC}`,uV);class fd extends g_{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Bg extends g_{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function vs(a){return a.getClassName?a.getClassName():""}function _d(a,e){return a==="Vector2"&&e==="Vector2"||a==="Vector3"&&e==="Vector3"||a==="Vector4"&&e==="Vector4"}function pd(a,e){return a==="Matrix"&&e==="Matrix"}function md(a,e){return a==="FlowGraphInteger"&&e==="FlowGraphInteger"}class sh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAdd(t,i),sh.ClassName,e)}_polymorphicAdd(e,t){const i=vs(e),s=vs(t);return _d(i,s)||pd(i,s)||md(i,s)?e.add(t):e+t}}sh.ClassName="FGAddBlock";V(sh.ClassName,sh);class rh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAdd(t,i),rh.ClassName,e)}_polymorphicAdd(e,t){const i=vs(e),s=vs(t);return _d(i,s)||md(i,s)?e.subtract(t):pd(i,s)?e.add(t.scale(-1)):e-t}}rh.ClassName="FGSubBlock";V(rh.ClassName,rh);class nh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMultiply(t,i),nh.ClassName,e)}_polymorphicMultiply(e,t){const i=vs(e),s=vs(t);return _d(i,s)||md(i,s)?e.multiply(t):pd(i,s)?D.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}nh.ClassName="FGMultiplyBlock";V(nh.ClassName,nh);class ah extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicDivide(t,i),ah.ClassName,e)}_polymorphicDivide(e,t){const i=vs(e),s=vs(t);return _d(i,s)||md(i,s)?e.divide(t):pd(i,s)?D.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}ah.ClassName="FGDivideBlock";V(ah.ClassName,ah);class oh extends fd{constructor(e){super(zt,()=>Math.random(),oh.ClassName,e)}}oh.ClassName="FGRandomBlock";V(oh.ClassName,oh);class lh extends Vi{constructor(e){super(Te,Te,zt,(t,i)=>this._polymorphicDot(t,i),lh.ClassName,e)}_polymorphicDot(e,t){switch(vs(e)){case"Vector2":return Z.Dot(e,t);case"Vector3":return m.Dot(e,t);case"Vector4":return we.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}lh.ClassName="FGDotBlock";V(lh.ClassName,lh);class hh extends fd{constructor(e){super(zt,()=>Math.E,hh.ClassName,e)}}hh.ClassName="FGEBlock";V(hh.ClassName,hh);class ch extends fd{constructor(e){super(zt,()=>Math.PI,ch.ClassName,e)}}ch.ClassName="FGPIBlock";V(ch.ClassName,ch);class uh extends fd{constructor(e){super(zt,()=>Number.POSITIVE_INFINITY,uh.ClassName,e)}}uh.ClassName="FGInfBlock";V(uh.ClassName,uh);class dh extends fd{constructor(e){super(zt,()=>Number.NaN,dh.ClassName,e)}}dh.ClassName="FGNaNBlock";V(dh.ClassName,dh);function vi(a,e){switch(vs(a)){case"FlowGraphInteger":return new Ri(e(a.value));case"Vector2":return new Z(e(a.x),e(a.y));case"Vector3":return new m(e(a.x),e(a.y),e(a.z));case"Vector4":return new we(e(a.x),e(a.y),e(a.z),e(a.w));case"Matrix":return D.FromValues(e(a.m[0]),e(a.m[4]),e(a.m[8]),e(a.m[12]),e(a.m[1]),e(a.m[5]),e(a.m[9]),e(a.m[13]),e(a.m[2]),e(a.m[6]),e(a.m[10]),e(a.m[14]),e(a.m[3]),e(a.m[7]),e(a.m[11]),e(a.m[15]));default:return e(a)}}class fh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicAbs(t),fh.ClassName,e)}_polymorphicAbs(e){return vi(e,Math.abs)}}fh.ClassName="FGAbsBlock";V(fh.ClassName,fh);class _h extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicSign(t),_h.ClassName,e)}_polymorphicSign(e){return vi(e,Math.sign)}}_h.ClassName="FGSignBlock";V(_h.ClassName,_h);class ph extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicTrunc(t),ph.ClassName,e)}_polymorphicTrunc(e){return vi(e,Math.trunc)}}ph.ClassName="FGTruncBlock";V(ph.ClassName,ph);class mh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicFloor(t),mh.ClassName,e)}_polymorphicFloor(e){return vi(e,Math.floor)}}mh.ClassName="FGFloorBlock";V(mh.ClassName,mh);class gh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicCeiling(t),gh.ClassName,e)}_polymorphicCeiling(e){return vi(e,Math.ceil)}}gh.ClassName="FGCeilBlock";V(gh.ClassName,gh);class xh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicFract(t),xh.ClassName,e)}_polymorphicFract(e){return vi(e,t=>t-Math.floor(t))}}xh.ClassName="FGFractBlock";V(xh.ClassName,xh);class Th extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicNeg(t),Th.ClassName,e)}_polymorphicNeg(e){return vi(e,t=>-t)}}Th.ClassName="FGNegBlock";V(Th.ClassName,Th);function gd(a,e,t){switch(vs(a)){case"FlowGraphInteger":return new Ri(t(a.value,e.value));case"Vector2":return new Z(t(a.x,e.x),t(a.y,e.y));case"Vector3":return new m(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z));case"Vector4":return new we(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z),t(a.w,e.w));case"Matrix":return D.FromValues(t(a.m[0],e.m[0]),t(a.m[4],e.m[4]),t(a.m[8],e.m[8]),t(a.m[12],e.m[12]),t(a.m[1],e.m[1]),t(a.m[5],e.m[5]),t(a.m[9],e.m[9]),t(a.m[13],e.m[13]),t(a.m[2],e.m[2]),t(a.m[6],e.m[6]),t(a.m[10],e.m[10]),t(a.m[14],e.m[14]),t(a.m[3],e.m[3]),t(a.m[7],e.m[7]),t(a.m[11],e.m[11]),t(a.m[15],e.m[15]));default:return t(a,e)}}class Eh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicRemainder(t,i),Eh.ClassName,e)}_polymorphicRemainder(e,t){return gd(e,t,(i,s)=>i%s)}}Eh.ClassName="FGRemainderBlock";V(Eh.ClassName,Eh);class Sh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMin(t,i),Sh.ClassName,e)}_polymorphicMin(e,t){return gd(e,t,Math.min)}}Sh.ClassName="FGMinBlock";V(Sh.ClassName,Sh);class Ch extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMax(t,i),Ch.ClassName,e)}_polymorphicMax(e,t){return gd(e,t,Math.max)}}Ch.ClassName="FGMaxBlock";V(Ch.ClassName,Ch);function dV(a,e,t){return Math.min(Math.max(a,Math.min(e,t)),Math.max(e,t))}function GC(a,e,t,i){switch(vs(a)){case"FlowGraphInteger":return new Ri(i(a.value,e.value,t.value));case"Vector2":return new Z(i(a.x,e.x,t.x),i(a.y,e.y,t.y));case"Vector3":return new m(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z));case"Vector4":return new we(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z),i(a.w,e.w,t.w));case"Matrix":return D.FromValues(i(a.m[0],e.m[0],t.m[0]),i(a.m[4],e.m[4],t.m[4]),i(a.m[8],e.m[8],t.m[8]),i(a.m[12],e.m[12],t.m[12]),i(a.m[1],e.m[1],t.m[1]),i(a.m[5],e.m[5],t.m[5]),i(a.m[9],e.m[9],t.m[9]),i(a.m[13],e.m[13],t.m[13]),i(a.m[2],e.m[2],t.m[2]),i(a.m[6],e.m[6],t.m[6]),i(a.m[10],e.m[10],t.m[10]),i(a.m[14],e.m[14],t.m[14]),i(a.m[3],e.m[3],t.m[3]),i(a.m[7],e.m[7],t.m[7]),i(a.m[11],e.m[11],t.m[11]),i(a.m[15],e.m[15],t.m[15]));default:return i(a,e,t)}}class vh extends Bg{constructor(e){super(Te,Te,Te,Te,(t,i,s)=>this._polymorphicClamp(t,i,s),vh.ClassName,e)}_polymorphicClamp(e,t,i){return GC(e,t,i,dV)}}vh.ClassName="FGClampBlock";V(vh.ClassName,vh);function fV(a){return Math.min(Math.max(a,0),1)}class bh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicSaturate(t),bh.ClassName,e)}_polymorphicSaturate(e){return vi(e,fV)}}bh.ClassName="FGSaturateBlock";V(bh.ClassName,bh);class Ah extends Bg{constructor(e){super(Te,Te,Te,Te,(t,i,s)=>this._polymorphicInterpolate(t,i,s),Ah.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return GC(e,t,i,this._interpolate)}}Ah.ClassName="FGInterpolateBlock";V(Ah.ClassName,Ah);class yh extends Vi{constructor(e){super(Te,Te,xs,(t,i)=>this._polymorphicEq(t,i),yh.ClassName,e)}_polymorphicEq(e,t){const i=vs(e),s=vs(t);return _d(i,s)||pd(i,s)||md(i,s)?e.equals(t):e===t}}yh.ClassName="FGEqBlock";V(yh.ClassName,yh);function x_(a,e,t){const i=vs(a),s=vs(e);if(i===s){if(i==="")return t(a,e);if(i==="FlowGraphInteger")return t(a.value,e.value);throw new Error(`Cannot compare ${a} and ${e}`)}throw new Error(`${a} and ${e} are of different types.`)}class Rh extends Vi{constructor(e){super(Te,Te,xs,(t,i)=>this._polymorphicLessThan(t,i),Rh.ClassName,e)}_polymorphicLessThan(e,t){return x_(e,t,(i,s)=>i<s)}}Rh.ClassName="FGLessThanBlock";V(Rh.ClassName,Rh);class T_ extends Vi{constructor(e){super(Te,Te,xs,(t,i)=>this._polymorphicLessThanOrEqual(t,i),T_.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return x_(e,t,(i,s)=>i<=s)}}T_.ClassName="FGLessThanOrEqualBlock";class Ih extends Vi{constructor(e){super(Te,Te,xs,(t,i)=>this._polymorphicGreaterThan(t,i),Ih.ClassName,e)}_polymorphicGreaterThan(e,t){return x_(e,t,(i,s)=>i>s)}}Ih.ClassName="FGGreaterThanBlock";V(Ih.ClassName,Ih);class Ph extends Vi{constructor(e){super(Te,Te,xs,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),Ph.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return x_(e,t,(i,s)=>i>=s)}}Ph.ClassName="FGGreaterThanOrEqualBlock";V(Ph.ClassName,Ph);class Mh extends Mt{constructor(e){super(Te,xs,t=>this._polymorphicIsNan(t),Mh.ClassName,e)}_polymorphicIsNan(e){const t=vs(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Mh.ClassName="FGIsNanBlock";V(Mh.ClassName,Mh);class E_ extends Mt{constructor(e){super(Te,xs,t=>this._polymorphicIsInf(t),E_.ClassName,e)}_polymorphicIsInf(e){const t=vs(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}E_.ClassName="FGIsInfBlock";class Dh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicDegToRad(t),Dh.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return vi(e,this._degToRad)}}Dh.ClassName="FGDegToRadBlock";V(Dh.ClassName,Dh);class Oh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicRadToDeg(t),Oh.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return vi(e,this._radToDeg)}}Oh.ClassName="FGRadToDegBlock";V(Oh.ClassName,Oh);class Nh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicSin(t),Nh.ClassName,e)}_polymorphicSin(e){return vi(e,Math.sin)}}Nh.ClassName="FGSinBlock";V(Nh.ClassName,Nh);class Fh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicCos(t),Fh.ClassName,e)}_polymorphicCos(e){return vi(e,Math.cos)}}Fh.ClassName="FGCosBlock";V(Fh.ClassName,Fh);class wh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicTan(t),wh.ClassName,e)}_polymorphicTan(e){return vi(e,Math.tan)}}wh.ClassName="FGTanBlock";V(wh.ClassName,wh);class Lh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicAsin(t),Lh.ClassName,e)}_polymorphicAsin(e){return vi(e,Math.asin)}}Lh.ClassName="FGAsinBlock";V(Lh.ClassName,Lh);class Bh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicAcos(t),Bh.ClassName,e)}_polymorphicAcos(e){return vi(e,Math.acos)}}Bh.ClassName="FGAcosBlock";V(Bh.ClassName,Bh);class Uh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicAtan(t),Uh.ClassName,e)}_polymorphicAtan(e){return vi(e,Math.atan)}}Uh.ClassName="FGAtanBlock";V(Uh.ClassName,Uh);class Vh extends Vi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAtan2(t,i),Vh.ClassName,e)}_polymorphicAtan2(e,t){return gd(e,t,Math.atan2)}}Vh.ClassName="FGAtan2Block";V(Vh.ClassName,Vh);class kh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicSinh(t),kh.ClassName,e)}_polymorphicSinh(e){return vi(e,Math.sinh)}}kh.ClassName="FGSinhBlock";V(kh.ClassName,kh);class Gh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicCosh(t),Gh.ClassName,e)}_polymorphicCosh(e){return vi(e,Math.cosh)}}Gh.ClassName="FGCoshBlock";V(Gh.ClassName,Gh);class zh extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicTanh(t),zh.ClassName,e)}_polymorphicTanh(e){return vi(e,Math.tanh)}}zh.ClassName="FGTanhBlock";V(zh.ClassName,zh);class Wh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicAsinh(t),Wh.ClassName,e)}_polymorphicAsinh(e){return vi(e,Math.asinh)}}Wh.ClassName="FGAsinhBlock";V(Wh.ClassName,Wh);class Hh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicAcosh(t),Hh.ClassName,e)}_polymorphicAcosh(e){return vi(e,Math.acosh)}}Hh.ClassName="FGAcoshBlock";V(Hh.ClassName,Hh);class Xh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicAtanh(t),Xh.ClassName,e)}_polymorphicAtanh(e){return vi(e,Math.atanh)}}Xh.ClassName="FGAtanhBlock";V(Xh.ClassName,Xh);class Yh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicExp(t),Yh.ClassName,e)}_polymorphicExp(e){return vi(e,Math.exp)}}Yh.ClassName="FGExpBlock";V(Yh.ClassName,Yh);class $h extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicLog(t),$h.ClassName,e)}_polymorphicLog(e){return vi(e,Math.log)}}$h.ClassName="FGLogBlock";V($h.ClassName,$h);class Kh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicLog2(t),Kh.ClassName,e)}_polymorphicLog2(e){return vi(e,Math.log2)}}Kh.ClassName="FGLog2Block";V(Kh.ClassName,Kh);class jh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicLog10(t),jh.ClassName,e)}_polymorphicLog10(e){return vi(e,Math.log10)}}jh.ClassName="FGLog10Block";V(jh.ClassName,jh);class qh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicSqrt(t),qh.ClassName,e)}_polymorphicSqrt(e){return vi(e,Math.sqrt)}}qh.ClassName="FGSqrtBlock";V(qh.ClassName,qh);class Qh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicCubeRoot(t),Qh.ClassName,e)}_polymorphicCubeRoot(e){return vi(e,Math.cbrt)}}Qh.ClassName="FGCubeRootBlock";V(Qh.ClassName,Qh);class Zh extends Vi{constructor(e){super(Te,zt,zt,(t,i)=>this._polymorphicPow(t,i),Zh.ClassName,e)}_polymorphicPow(e,t){return gd(e,t,Math.pow)}}Zh.ClassName="FGPowBlock";V(Zh.ClassName,Zh);class Jh extends Mt{constructor(e){super(Te,zt,t=>this._polymorphicLength(t),Jh.ClassName,e)}_polymorphicLength(e){switch(vs(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Jh.ClassName="FGLengthBlock";V(Jh.ClassName,Jh);class ec extends Mt{constructor(e){super(Te,Te,t=>this._polymorphicNormalize(t),ec.ClassName,e)}_polymorphicNormalize(e){switch(vs(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}ec.ClassName="FGNormalizeBlock";V(ec.ClassName,ec);class tc extends Vi{constructor(e){super(fa,fa,fa,(t,i)=>m.Cross(t,i),tc.ClassName,e)}}tc.ClassName="FGCrossBlock";V(tc.ClassName,tc);class ic extends Vi{constructor(e){super(vp,zt,vp,(t,i)=>Z.Transform(t,D.RotationZ(i)),ic.ClassName,e)}}ic.ClassName="FGRotate2DBlock";V(ic.ClassName,ic);class sc extends Bg{constructor(e){super(fa,fa,zt,fa,(t,i,s)=>m.TransformCoordinates(t,D.RotationAxis(i,s)),sc.ClassName,e)}}sc.ClassName="FGRotate3DBlock";V(sc.ClassName,sc);class rc extends Mt{constructor(e){super(qa,qa,t=>D.Transpose(t),rc.ClassName,e)}}rc.ClassName="FGTransposeBlock";V(rc.ClassName,rc);class nc extends Mt{constructor(e){super(qa,zt,t=>t.determinant(),nc.ClassName,e)}}nc.ClassName="FGDeterminantBlock";V(nc.ClassName,nc);class ac extends Mt{constructor(e){super(qa,qa,t=>D.Invert(t),ac.ClassName,e)}}ac.ClassName="FGInvertMatrixBlock";V(ac.ClassName,ac);class oc extends Vi{constructor(e){super(qa,qa,qa,(t,i)=>i.multiply(t),oc.ClassName,e)}}oc.ClassName="FGMatMulBlock";V(oc.ClassName,oc);class lc extends Mt{constructor(e){super(Ii,Ii,t=>new Ri(~t.value),lc.ClassName,e)}}lc.ClassName="FGBitwiseNotBlock";V(lc.ClassName,lc);class hc extends Vi{constructor(e){super(Ii,Ii,Ii,(t,i)=>new Ri(t.value&i.value),hc.ClassName,e)}}hc.ClassName="FGBitwiseAndBlock";V(hc.ClassName,hc);class cc extends Vi{constructor(e){super(Ii,Ii,Ii,(t,i)=>new Ri(t.value|i.value),cc.ClassName,e)}}cc.ClassName="FGBitwiseOrBlock";V(cc.ClassName,cc);class uc extends Vi{constructor(e){super(Ii,Ii,Ii,(t,i)=>new Ri(t.value^i.value),uc.ClassName,e)}}uc.ClassName="FGBitwiseXorBlock";V(uc.ClassName,uc);class dc extends Vi{constructor(e){super(Ii,Ii,Ii,(t,i)=>new Ri(t.value<<i.value),dc.ClassName,e)}}dc.ClassName="FGBitwiseLeftShiftBlock";V(dc.ClassName,dc);class fc extends Vi{constructor(e){super(Ii,Ii,Ii,(t,i)=>new Ri(t.value>>i.value),fc.ClassName,e)}}fc.ClassName="FGBitwiseRightShiftBlock";V(fc.ClassName,fc);class _c extends Mt{constructor(e){super(Ii,Ii,t=>new Ri(Math.clz32(t.value)),_c.ClassName,e)}}_c.ClassName="FGCountLeadingZerosBlock";V(_c.ClassName,_c);class pc extends Mt{constructor(e){super(Ii,Ii,t=>new Ri(t.value?31-Math.clz32(t.value&-t.value):32),pc.ClassName,e)}}pc.ClassName="FGCountTrailingZerosBlock";V(pc.ClassName,pc);function _V(a){let e=0;for(;a;)e+=a&1,a>>=1;return e}class mc extends Mt{constructor(e){super(Ii,Ii,t=>new Ri(_V(t.value)),mc.ClassName,e)}}mc.ClassName="FGCountOneBitsBlock";V(mc.ClassName,mc);class xd extends hd{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return xd.ClassName}}xd.ClassName="FGSceneReadyEventBlock";V("FGSceneReadyEventBlock",xd);class gc extends hd{constructor(e){super(e),this.config=e;for(let t=0;t<this.config.eventData.length;t++){const i=this.config.eventData[t];this.registerDataOutput(i,Te)}}_preparePendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add(i=>{for(let s=0;s<i.length;s++)this.dataOutputs[s].setValue(i[s],e);this._execute(e)})}_cancelPendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):X.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return gc.ClassName}serialize(e){super.serialize(e),e.eventId=this.config.eventId,e.eventData=this.config.eventData}}gc.ClassName="FGReceiveCustomEventBlock";V(gc.ClassName,gc);class xc extends hd{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){const i=e.configuration.scene.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return xc.ClassName}}xc.ClassName="FGSceneTickEventBlock";V(xc.ClassName,xc);function Rp(a,e,t,i){const s={externalResourceFunction:i};return t&&(s.uri=e==="file:"?t:e+t),ArrayBuffer.isView(a)?GLTFValidator.validateBytes(a,s):GLTFValidator.validateString(a,s)}function pV(){const a=[];onmessage=e=>{const t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{Rp(t.data,t.rootUrl,t.fileName,i=>new Promise((s,r)=>{const n=a.length;a.push({resolve:s,reject:r}),postMessage({id:"getExternalResource",index:n,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{a[t.index].resolve(t.value);break}case"getExternalResource.reject":{a[t.index].reject(t.reason);break}}}}class zC{static ValidateAsync(e,t,i,s){return typeof Worker=="function"?new Promise((r,n)=>{const o=`${Rp}(${pV})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),h=new Worker(l),c=d=>{h.removeEventListener("error",c),h.removeEventListener("message",u),n(d)},u=d=>{const f=d.data;switch(f.id){case"getExternalResource":{s(f.uri).then(_=>{h.postMessage({id:"getExternalResource.resolve",index:f.index,value:_},[_])},_=>{h.postMessage({id:"getExternalResource.reject",index:f.index,reason:_})});break}case"validate.resolve":{h.removeEventListener("error",c),h.removeEventListener("message",u),r(f.value),h.terminate();break}case"validate.reject":h.removeEventListener("error",c),h.removeEventListener("message",u),n(f.reason),h.terminate()}};if(h.addEventListener("error",c),h.addEventListener("message",u),h.postMessage({id:"init",url:X.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const d=e.slice();h.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else h.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=X.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>Rp(e,t,i,s)))}}zC.Configuration={url:`${X._DefaultCdnUrl}/gltf_validator.js`};function KT(a,e,t){try{return Promise.resolve(new Uint8Array(a,e,t))}catch(i){return Promise.reject(i)}}function mV(a,e,t){try{if(e<0||e>=a.byteLength)throw new RangeError("Offset is out of range.");if(e+t>a.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(a.buffer,a.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var ku;(function(a){a[a.AUTO=0]="AUTO",a[a.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(ku||(ku={}));var Ol;(function(a){a[a.NONE=0]="NONE",a[a.FIRST=1]="FIRST",a[a.ALL=2]="ALL"})(Ol||(Ol={}));var gr;(function(a){a[a.LOADING=0]="LOADING",a[a.READY=1]="READY",a[a.COMPLETE=2]="COMPLETE"})(gr||(gr={}));class Ti{constructor(){this.onParsedObservable=new G,this.coordinateSystemMode=ku.AUTO,this.animationStartMode=Ol.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new G,this.onSkinLoadedObservable=new G,this.onTextureLoadedObservable=new G,this.onMaterialLoadedObservable=new G,this.onCameraLoadedObservable=new G,this.onCompleteObservable=new G,this.onErrorObservable=new G,this.onDisposeObservable=new G,this.onExtensionLoadedObservable=new G,this.validate=!1,this.onValidatedObservable=new G,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new G,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,l),null;this._progressCallback=r;const h=t.name||X.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&O.Warn("glTF validation is not supported when range requests are enabled");const c={abort:()=>{},onCompleteObservable:new G},u={readAsync:(d,f)=>new Promise((_,p)=>{this._loadFile(e,t,g=>{_(new Uint8Array(g))},!0,g=>{p(g)},g=>{g.setRequestHeader("Range",`bytes=${d}-${d+f-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new Bd(u)).then(d=>{c.onCompleteObservable.notifyObservers(c),s(d)},o?d=>o(void 0,d):void 0),c}return this._loadFile(e,t,c=>{this._validate(e,new Uint8Array(c,0,c.byteLength),i,h),this._unpackBinaryAsync(new Bd({readAsync:(u,d)=>KT(c,u,d),byteLength:c.byteLength})).then(u=>{s(u)},o?u=>o(void 0,u):void 0)},!0,o)}else return this._loadFile(e,t,c=>{this._validate(e,c,i,h),s({json:this._parseJson(c)})},!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new Bd({readAsync:(o,l)=>mV(t,o,l),byteLength:t.byteLength})).then(o=>{s(o)},r?o=>r(void 0,o):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n)))}loadAsync(e,t,i,s,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r)))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new Df(e),o=[];this.onMaterialLoadedObservable.add(u=>{o.push(u)});const l=[];this.onTextureLoadedObservable.add(u=>{l.push(u)});const h=[];this.onCameraLoadedObservable.add(u=>{h.push(u)});const c=[];return this.onMeshLoadedObservable.add(u=>{u.morphTargetManager&&c.push(u.morphTargetManager)}),this._loader.importMeshAsync(null,e,n,t,i,s,r).then(u=>(Array.prototype.push.apply(n.geometries,u.geometries),Array.prototype.push.apply(n.meshes,u.meshes),Array.prototype.push.apply(n.particleSystems,u.particleSystems),Array.prototype.push.apply(n.skeletons,u.skeletons),Array.prototype.push.apply(n.animationGroups,u.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,l),Array.prototype.push.apply(n.lights,u.lights),Array.prototype.push.apply(n.transformNodes,u.transformNodes),Array.prototype.push.apply(n.cameras,h),Array.prototype.push.apply(n.morphTargetManagers,c),n))})}canDirectLoad(e){return e.indexOf("asset")!==-1&&e.indexOf("version")!==-1||e.startsWith("data:base64,"+Ti._MagicBase64Encoded)||e.startsWith("data:;base64,"+Ti._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+Ti._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+Ti._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+Ti._MagicBase64Encoded)||t.startsWith(";base64,"+Ti._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+Ti._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+Ti._MagicBase64Encoded)){const i=Xu(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new Bd({readAsync:(s,r)=>KT(i,s,r),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new Ti}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(gr[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,s,r,n);return o.onCompleteObservable.add(l=>{this._requests.splice(this._requests.indexOf(l),1)}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const n of this._requests){if(n._lengthComputable===void 0||n._loaded===void 0||n._total===void 0)return;i=i&&n._lengthComputable,s+=n._loaded,r+=n._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),zC.ValidateAsync(t,i,s,r=>this.preprocessUrlAsync(i+r).then(n=>e._loadFileAsync(n,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(r=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(r),this.onValidatedObservable.clear()},r=>{this._endPerformanceCounter("Validate JSON"),X.Warn(`Failed to validate: ${r.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=Ti._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){const n=Ti._parseVersion(t.minVersion);if(!n)throw new Error("Invalid minimum version: "+t.minVersion);if(Ti._compareVersion(n,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const r={1:Ti._CreateGLTF1Loader,2:Ti._CreateGLTF2Loader}[i.major];if(!r)throw new Error("Unsupported version: "+t.version);return r(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new Sn("Unexpected magic: "+i,ca.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const r=e.readUint32();!this.useRangeRequests&&r!==e.buffer.byteLength&&O.Warn(`Length in header does not match actual data length: ${r} != ${e.buffer.byteLength}`);let n;switch(s){case 1:{n=this._unpackBinaryV1Async(e,r);break}case 2:{n=this._unpackBinaryV2Async(e,r);break}default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),n})}_unpackBinaryV1Async(e,t){const i={JSON:0},s=e.readUint32(),r=e.readUint32();if(r!==i.JSON)throw new Error(`Unexpected content format: ${r}`);const n=t-e.byteOffset,o={json:this._parseJson(e.readString(s)),bin:null};if(n!==0){const l=e.byteOffset;o.bin={readAsync:(h,c)=>e.buffer.readAsync(l+h,c),byteLength:n}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){const i={JSON:1313821514,BIN:5130562},s=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then(()=>({json:this._parseJson(e.readString(s)),bin:null})):e.loadAsync(s+8).then(()=>{const n={json:this._parseJson(e.readString(s)),bin:null},o=()=>{const l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{const c=e.byteOffset;n.bin={readAsync:(u,d)=>e.buffer.readAsync(c+u,d),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(n)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const t=Ti._logSpaces.substr(0,this._logIndentLevel*2);O.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){X.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){X.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}Ti.IncrementalLoading=!0;Ti.HomogeneousCoordinates=!1;Ti._MagicBase64Encoded="Z2xURg";Ti._logSpaces="                                ";je&&je.RegisterPlugin(new Ti);var ka;(function(a){a[a.BYTE=5120]="BYTE",a[a.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",a[a.SHORT=5122]="SHORT",a[a.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",a[a.FLOAT=5126]="FLOAT"})(ka||(ka={}));var Ip;(function(a){a[a.FRAGMENT=35632]="FRAGMENT",a[a.VERTEX=35633]="VERTEX"})(Ip||(Ip={}));var nr;(function(a){a[a.BYTE=5120]="BYTE",a[a.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",a[a.SHORT=5122]="SHORT",a[a.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",a[a.INT=5124]="INT",a[a.UNSIGNED_INT=5125]="UNSIGNED_INT",a[a.FLOAT=5126]="FLOAT",a[a.FLOAT_VEC2=35664]="FLOAT_VEC2",a[a.FLOAT_VEC3=35665]="FLOAT_VEC3",a[a.FLOAT_VEC4=35666]="FLOAT_VEC4",a[a.INT_VEC2=35667]="INT_VEC2",a[a.INT_VEC3=35668]="INT_VEC3",a[a.INT_VEC4=35669]="INT_VEC4",a[a.BOOL=35670]="BOOL",a[a.BOOL_VEC2=35671]="BOOL_VEC2",a[a.BOOL_VEC3=35672]="BOOL_VEC3",a[a.BOOL_VEC4=35673]="BOOL_VEC4",a[a.FLOAT_MAT2=35674]="FLOAT_MAT2",a[a.FLOAT_MAT3=35675]="FLOAT_MAT3",a[a.FLOAT_MAT4=35676]="FLOAT_MAT4",a[a.SAMPLER_2D=35678]="SAMPLER_2D"})(nr||(nr={}));var xu;(function(a){a[a.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",a[a.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",a[a.REPEAT=10497]="REPEAT"})(xu||(xu={}));var xn;(function(a){a[a.NEAREST=9728]="NEAREST",a[a.LINEAR=9728]="LINEAR",a[a.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",a[a.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",a[a.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",a[a.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(xn||(xn={}));var jT;(function(a){a[a.ALPHA=6406]="ALPHA",a[a.RGB=6407]="RGB",a[a.RGBA=6408]="RGBA",a[a.LUMINANCE=6409]="LUMINANCE",a[a.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"})(jT||(jT={}));var Pp;(function(a){a[a.FRONT=1028]="FRONT",a[a.BACK=1029]="BACK",a[a.FRONT_AND_BACK=1032]="FRONT_AND_BACK"})(Pp||(Pp={}));var Di;(function(a){a[a.ZERO=0]="ZERO",a[a.ONE=1]="ONE",a[a.SRC_COLOR=768]="SRC_COLOR",a[a.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",a[a.DST_COLOR=774]="DST_COLOR",a[a.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",a[a.SRC_ALPHA=770]="SRC_ALPHA",a[a.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",a[a.DST_ALPHA=772]="DST_ALPHA",a[a.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",a[a.CONSTANT_COLOR=32769]="CONSTANT_COLOR",a[a.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",a[a.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",a[a.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",a[a.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"})(Di||(Di={}));class cs{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=D.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=D.Transpose(t.getWorldMatrix().invert())),n)switch(i.type){case nr.FLOAT_MAT2:r.setMatrix2x2(s,D.GetAsMatrix2x2(n));break;case nr.FLOAT_MAT3:r.setMatrix3x3(s,D.GetAsMatrix3x3(n));break;case nr.FLOAT_MAT4:r.setMatrix(s,n);break}}static SetUniform(e,t,i,s){switch(s){case nr.FLOAT:return e.setFloat(t,i),!0;case nr.FLOAT_VEC2:return e.setVector2(t,Z.FromArray(i)),!0;case nr.FLOAT_VEC3:return e.setVector3(t,m.FromArray(i)),!0;case nr.FLOAT_VEC4:return e.setVector4(t,we.FromArray(i)),!0;default:return!1}}static GetWrapMode(e){switch(e){case xu.CLAMP_TO_EDGE:return k.CLAMP_ADDRESSMODE;case xu.MIRRORED_REPEAT:return k.MIRROR_ADDRESSMODE;case xu.REPEAT:return k.WRAP_ADDRESSMODE;default:return k.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 xn.LINEAR:case xn.LINEAR_MIPMAP_NEAREST:case xn.LINEAR_MIPMAP_LINEAR:return k.TRILINEAR_SAMPLINGMODE;case xn.NEAREST:case xn.NEAREST_MIPMAP_NEAREST:return k.NEAREST_SAMPLINGMODE;default:return k.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 o=n.buffer;switch(i+=n.byteOffset,r){case ka.BYTE:return new Int8Array(o,i,s);case ka.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case ka.SHORT:return new Int16Array(o,i,s);case ka.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*cs.GetByteStrideFromType(t);return cs.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(!cs._DefaultMaterial){xt.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(`
`),xt.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{","    gl_FragColor = u_emission;","}"].join(`
`);const t={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},i={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};cs._DefaultMaterial=new Qs("GLTFDefaultMaterial",e,t,i),cs._DefaultMaterial.setColor4("u_emission",new xe(.5,.5,.5,1))}return cs._DefaultMaterial}}cs._DefaultMaterial=null;var Ga;(function(a){a[a.IDENTIFIER=1]="IDENTIFIER",a[a.UNKNOWN=2]="UNKNOWN",a[a.END_OF_INPUT=3]="END_OF_INPUT"})(Ga||(Ga={}));class qT{constructor(e){this._pos=0,this.currentToken=Ga.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Ga.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Ga.UNKNOWN,this.currentString==="_"||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Ga.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 WC=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],HC=["world","view","projection","worldView","worldViewProjection","mBones"],gV=["translation","rotation","scale"],xV=["position","rotationQuaternion","scaling"],TV=(a,e)=>{for(const t in a){const i=a[t];e.buffers[t]=i,e.buffersCount++}},EV=(a,e)=>{for(const t in a){const i=a[t];e.shaders[t]=i,e.shaderscount++}},Ws=(a,e,t)=>{for(const i in a){const s=a[i];t[e][i]=s}},SV=a=>{if(a)for(let e=0;e<a.length/2;e++)a[e*2+1]=1-a[e*2+1]},QT=a=>{if(a.semantic==="NORMAL")return"normal";if(a.semantic==="POSITION")return"position";if(a.semantic==="JOINT")return"matricesIndices";if(a.semantic==="WEIGHT")return"matricesWeights";if(a.semantic==="COLOR")return"color";if(a.semantic&&a.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(a.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},CV=a=>{for(const e in a.animations){const t=a.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 o=null,l=null;t.parameters?(o=t.parameters[n.input],l=t.parameters[n.output]):(o=n.input,l=n.output);const h=cs.GetBufferFromAccessor(a,a.accessors[o]),c=cs.GetBufferFromAccessor(a,a.accessors[l]),u=r.target.id;let d=a.scene.getNodeById(u);if(d===null&&(d=a.scene.getNodeByName(u)),d===null){X.Warn("Creating animation named "+e+". But cannot find node named "+u+" to attach to");continue}const f=d instanceof Ut;let _=r.target.path;const p=gV.indexOf(_);p!==-1&&(_=xV[p]);let g=K.ANIMATIONTYPE_MATRIX;f||(_==="rotationQuaternion"?(g=K.ANIMATIONTYPE_QUATERNION,d.rotationQuaternion=new Q):g=K.ANIMATIONTYPE_VECTOR3);let x=null;const T=[];let S=0,C=!1;f&&i&&i.getKeys().length===h.length&&(x=i,C=!0),C||(a.scene._blockEntityCollection=!!a.assetContainer,x=new K(e,f?"_matrix":_,1,g,K.ANIMATIONLOOPMODE_CYCLE),a.scene._blockEntityCollection=!1);for(let v=0;v<h.length;v++){let b=null;if(_==="rotationQuaternion"?(b=Q.FromArray([c[S],c[S+1],c[S+2],c[S+3]]),S+=4):(b=m.FromArray([c[S],c[S+1],c[S+2]]),S+=3),f){const A=d;let P=m.Zero(),L=new Q,w=m.Zero(),$=A.getBaseMatrix();C&&i&&($=i.getKeys()[v].value),$.decompose(w,L,P),_==="position"?P=b:_==="rotationQuaternion"?L=b:w=b,b=D.Compose(w,L,P)}C?i&&(i.getKeys()[v].value=b):T.push({frame:h[v],value:b})}!C&&x&&(x.setKeys(T),d.animations.push(x)),i=x,a.scene.stopAnimation(d),a.scene.beginAnimation(d,0,h[h.length-1],!0,1)}}},Ug=a=>{let e=null;if(a.translation||a.rotation||a.scale){const t=m.FromArray(a.scale||[1,1,1]),i=Q.FromArray(a.rotation||[0,0,0,1]),s=m.FromArray(a.translation||[0,0,0]);e=D.Compose(t,i,s)}else e=D.FromArray(a.matrix);return e},XC=(a,e,t,i)=>{for(let r=0;r<i.bones.length;r++)if(i.bones[r].name===t)return i.bones[r];const s=a.nodes;for(const r in s){const n=s[r];if(!n.jointName)continue;const o=n.children;for(let l=0;l<o.length;l++){const h=a.nodes[o[l]];if(h.jointName&&h.jointName===t){const c=Ug(n),u=new Ut(n.name||"",i,XC(a,e,n.jointName,i),c);return u.id=r,u}}}return null},vV=(a,e)=>{for(let t=0;t<a.length;t++){const i=a[t];for(let s=0;s<i.node.children.length;s++)if(i.node.children[s]===e)return i.bone}return null},j_=(a,e)=>{const t=a.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},bV=(a,e)=>{for(let t=0;t<a.jointNames.length;t++)if(a.jointNames[t]===e)return!0;return!1},AV=(a,e,t,i)=>{for(const s in a.nodes){const r=a.nodes[s],n=s;if(!r.jointName||bV(t,r.jointName))continue;const o=Ug(r),l=new Ut(r.name||"",e,null,o);l.id=n,i.push({bone:l,node:r,id:n})}for(let s=0;s<i.length;s++){const r=i[s],n=r.node.children;for(let o=0;o<n.length;o++){let l=null;for(let h=0;h<i.length;h++)if(i[h].id===n[o]){l=i[h];break}l&&(l.bone._parent=r.bone,r.bone.children.push(l.bone))}}},yV=(a,e,t,i)=>{if(i||(i=new eo(e.name||"","",a.scene)),!e.babylonSkeleton)return i;const s=[],r=[];AV(a,i,e,s),i.bones=[];for(let o=0;o<e.jointNames.length;o++){const l=j_(a,e.jointNames[o]);if(!l)continue;const h=l.node;if(!h){X.Warn("Joint named "+e.jointNames[o]+" does not exist");continue}const c=l.id,u=a.scene.getBoneById(c);if(u){i.bones.push(u);continue}let d=!1,f=null;for(let g=0;g<o;g++){const x=j_(a,e.jointNames[g]);if(!x)continue;const T=x.node;if(!T){X.Warn("Joint named "+e.jointNames[g]+" does not exist when looking for parent");continue}const S=T.children;if(S){d=!1;for(let C=0;C<S.length;C++)if(S[C]===c){f=XC(a,e,e.jointNames[g],i),d=!0;break}if(d)break}}const _=Ug(h);!f&&s.length>0&&(f=vV(s,c),f&&r.indexOf(f)===-1&&r.push(f));const p=new Ut(h.jointName||"",i,f,_);p.id=c}const n=i.bones;i.bones=[];for(let o=0;o<e.jointNames.length;o++){const l=j_(a,e.jointNames[o]);if(l){for(let h=0;h<n.length;h++)if(n[h].id===l.id){i.bones.push(n[h]);break}}}i.prepare();for(let o=0;o<r.length;o++)i.bones.push(r[o]);return i},ZT=(a,e,t,i,s)=>{if(s||(a.scene._blockEntityCollection=!!a.assetContainer,s=new z(e.name||"",a.scene),s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const o=[],l=[],h=[],c=[];for(let f=0;f<t.length;f++){const _=t[f],p=a.meshes[_];if(p)for(let g=0;g<p.primitives.length;g++){const x=new le,T=p.primitives[g];T.mode;const S=T.attributes;let C=null,v=null;for(const A in S)if(C=a.accessors[S[A]],v=cs.GetBufferFromAccessor(a,C),A==="NORMAL")x.normals=new Float32Array(v.length),x.normals.set(v);else if(A==="POSITION"){if(Ti.HomogeneousCoordinates){x.positions=new Float32Array(v.length-v.length/4);for(let P=0;P<v.length;P+=4)x.positions[P]=v[P],x.positions[P+1]=v[P+1],x.positions[P+2]=v[P+2]}else x.positions=new Float32Array(v.length),x.positions.set(v);l.push(x.positions.length)}else if(A.indexOf("TEXCOORD_")!==-1){const P=Number(A.split("_")[1]),L=y.UVKind+(P===0?"":P+1),w=new Float32Array(v.length);w.set(v),SV(w),x.set(w,L)}else A==="JOINT"?(x.matricesIndices=new Float32Array(v.length),x.matricesIndices.set(v)):A==="WEIGHT"?(x.matricesWeights=new Float32Array(v.length),x.matricesWeights.set(v)):A==="COLOR"&&(x.colors=new Float32Array(v.length),x.colors.set(v));if(C=a.accessors[T.indices],C)v=cs.GetBufferFromAccessor(a,C),x.indices=new Int32Array(v.length),x.indices.set(v),c.push(x.indices.length);else{const A=[];for(let P=0;P<x.positions.length/3;P++)A.push(P);x.indices=new Int32Array(A),c.push(x.indices.length)}n?n.merge(x):n=x;const b=a.scene.getMaterialById(T.material);r.push(b===null?cs.GetDefaultMaterial(a.scene):b),o.push(o.length===0?0:o[o.length-1]+l[l.length-2]),h.push(h.length===0?0:h[h.length-1]+c[c.length-2])}}let u;a.scene._blockEntityCollection=!!a.assetContainer,r.length>1?(u=new _a("multimat"+i,a.scene),u.subMaterials=r):u=new de("multimat"+i,a.scene),r.length===1&&(u=r[0]),u._parentContainer=a.assetContainer,s.material||(s.material=u),new zi(i,a.scene,n,!1,s),s.computeWorldMatrix(!0),a.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let f=0;f<t.length;f++){const _=t[f],p=a.meshes[_];if(p)for(let g=0;g<p.primitives.length;g++)p.primitives[g].mode,Ss.AddToMesh(d,o[d],l[d],h[d],c[d],s,s,!0),d++}return s},Mp=(a,e,t,i)=>{a.position&&(a.position=e),(a.rotationQuaternion||a.rotation)&&(a.rotationQuaternion=t),a.scaling&&(a.scaling=i)},RV=(a,e)=>{if(e.matrix){const t=new m(0,0,0),i=new Q,s=new m(0,0,0);D.FromArray(e.matrix).decompose(s,i,t),Mp(a,t,i,s)}else e.translation&&e.rotation&&e.scale&&Mp(a,m.FromArray(e.translation),Q.FromArray(e.rotation),m.FromArray(e.scale));a.computeWorldMatrix(!0)},IV=(a,e,t)=>{let i=null;if(a.importOnlyMeshes&&(e.skin||e.meshes)&&a.importMeshesNames&&a.importMeshesNames.length>0&&a.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=a.skins[e.skin],r=ZT(a,e,e.meshes,t,e.babylonNode);r.skeleton=a.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=yV(a,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=ZT(a,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Ho(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=q.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new Hr(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=q.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new Pc(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=q.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new hr(e.light,m.Zero(),m.Zero(),0,0,a.scene);n.name=e.name||"",r.color&&(n.diffuse=q.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.cameras[e.camera];if(s){if(a.scene._blockEntityCollection=!!a.assetContainer,s.type==="orthographic"){const r=new qs(e.camera,m.Zero(),a.scene,!1);r.name=e.name||"",r.mode=ve.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=a.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new qs(e.camera,m.Zero(),a.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=a.scene.getEngine().getRenderWidth()/a.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=a.assetContainer}a.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){a.scene._blockEntityCollection=!!a.assetContainer;const s=new z(e.name||"",a.scene);s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof z)RV(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];Mp(i,m.FromArray(s),Q.FromArray(r),m.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},Gu=(a,e,t,i=!1)=>{const s=a.nodes[e];let r=null;if(a.importOnlyMeshes&&!i&&a.importMeshesNames?a.importMeshesNames.indexOf(s.name||"")!==-1||a.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=IV(a,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n<s.children.length;n++)Gu(a,s.children[n],r,i)},JT=a=>{let e=a.currentScene;if(e)for(let t=0;t<e.nodes.length;t++)Gu(a,e.nodes[t],null);else for(const t in a.scenes){e=a.scenes[t];for(let i=0;i<e.nodes.length;i++)Gu(a,e.nodes[i],null)}CV(a);for(let t=0;t<a.scene.skeletons.length;t++){const i=a.scene.skeletons[t];a.scene.beginAnimation(i,0,Number.MAX_VALUE,!0,1)}},PV=(a,e,t,i,s,r,n)=>{const o=r.values||s.parameters;for(const l in t){const h=t[l],c=h.type;if(c===nr.FLOAT_MAT2||c===nr.FLOAT_MAT3||c===nr.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)cs.SetMatrix(e.scene,a,h,l,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;cs.SetMatrix(e.scene,u,h,l,i.getEffect())}}else{const u=o[s.uniforms[l]];if(!u)continue;if(c===nr.SAMPLER_2D){const d=e.textures[r.values?u:h.value].babylonTexture;if(d==null)continue;i.getEffect().setTexture(l,d)}else cs.SetUniform(i.getEffect(),l,u,c)}}n(i)},MV=(a,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const o in s){const l=s[o],h=l.type;let c=r[n[o]];if(c===void 0&&(c=l.value),!c)continue;const u=d=>f=>{l.value&&d&&(e.setTexture(d,f),delete s[d])};h===nr.SAMPLER_2D?Ps.LoadTextureAsync(a,i.values?c:l.value,u(o),()=>u(null)):l.value&&cs.SetUniform(e,o,i.values?c:l.value,h)&&delete s[o]}},DV=(a,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+a.name+". Error: "+s+". Default material will be applied")},OV=(a,e,t,i,s,r)=>n=>{MV(a,e,t,i,s),e.onBind=o=>{PV(o,a,s,e,t,i,r)}},eE=(a,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(a.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=WC.indexOf(r.semantic);if(n!==-1)return delete t[i],HC[n]}}return a.currentIdentifier},tE=a=>{for(const e in a.materials)Ps.LoadMaterialAsync(a,e,()=>{},()=>{})};class ra{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&&Ws(e.extensions,"extensions",s),e.extensionsUsed&&Ws(e.extensionsUsed,"extensionsUsed",s),e.buffers&&TV(e.buffers,s),e.bufferViews&&Ws(e.bufferViews,"bufferViews",s),e.accessors&&Ws(e.accessors,"accessors",s),e.meshes&&Ws(e.meshes,"meshes",s),e.lights&&Ws(e.lights,"lights",s),e.cameras&&Ws(e.cameras,"cameras",s),e.nodes&&Ws(e.nodes,"nodes",s),e.images&&Ws(e.images,"images",s),e.textures&&Ws(e.textures,"textures",s),e.shaders&&EV(e.shaders,s),e.programs&&Ws(e.programs,"programs",s),e.samplers&&Ws(e.samplers,"samplers",s),e.techniques&&Ws(e.techniques,"techniques",s),e.materials&&Ws(e.materials,"materials",s),e.animations&&Ws(e.animations,"animations",s),e.skins&&Ws(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];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),r,void 0,!0,o=>{o&&s(o.status+" "+o.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];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),void 0,void 0,!0,o=>{o&&s(o.status+" "+o.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],o=n.minFilter===xn.NEAREST_MIPMAP_NEAREST||n.minFilter===xn.NEAREST_MIPMAP_LINEAR||n.minFilter===xn.LINEAR_MIPMAP_NEAREST||n.minFilter===xn.LINEAR_MIPMAP_LINEAR,l=k.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),d=new k(c,e.scene,!o,!0,l,u,u);n.wrapS!==void 0&&(d.wrapU=cs.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(d.wrapV=cs.GetWrapMode(n.wrapT)),d.name=t,r.babylonTexture=d,s(d)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(X.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else X.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 b=new de(t,e.scene);b._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,b.diffuseColor=new q(.5,.5,.5),b.sideOrientation=ee.CounterClockWiseSideOrientation,i(b);return}const o=e.programs[n.program],l=n.states,h=xt.ShadersStore[o.vertexShader+"VertexShader"],c=xt.ShadersStore[o.fragmentShader+"PixelShader"];let u="",d="";const f=new qT(h),_=new qT(c),p={},g=[],x=[],T=[];for(const b in n.uniforms){const A=n.uniforms[b],P=n.parameters[A];if(p[b]=P,P.semantic&&!P.node&&!P.source){const L=WC.indexOf(P.semantic);L!==-1?(g.push(HC[L]),delete p[b]):g.push(b)}else P.type===nr.SAMPLER_2D?T.push(b):g.push(b)}for(const b in n.attributes){const A=n.attributes[b],P=n.parameters[A];if(P.semantic){const L=QT(P);L&&x.push(L)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==Ga.IDENTIFIER){u+=f.currentString;continue}let A=!1;for(const P in n.attributes){const L=n.attributes[P],w=n.parameters[L];if(f.currentIdentifier===P&&w.semantic){u+=QT(w),A=!0;break}}A||(u+=eE(f,n,p))}for(;!_.isEnd()&&_.getNextToken();){if(_.currentToken!==Ga.IDENTIFIER){d+=_.currentString;continue}d+=eE(_,n,p)}const S={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},C={attributes:x,uniforms:g,samplers:T,needAlphaBlending:l&&l.enable&&l.enable.indexOf(3042)!==-1};xt.ShadersStore[o.vertexShader+t+"VertexShader"]=u,xt.ShadersStore[o.fragmentShader+t+"PixelShader"]=d;const v=new Qs(t,e.scene,S,C);if(v.onError=DV(o,v,s),v.onCompiled=OV(e,v,n,r,p,i),v.sideOrientation=ee.CounterClockWiseSideOrientation,l&&l.functions){const b=l.functions;b.cullFace&&b.cullFace[0]!==Pp.BACK&&(v.backFaceCulling=!1);const A=b.blendFuncSeparate;A&&(A[0]===Di.SRC_ALPHA&&A[1]===Di.ONE_MINUS_SRC_ALPHA&&A[2]===Di.ONE&&A[3]===Di.ONE?v.alphaMode=Y.ALPHA_COMBINE:A[0]===Di.ONE&&A[1]===Di.ONE&&A[2]===Di.ZERO&&A[3]===Di.ONE?v.alphaMode=Y.ALPHA_ONEONE:A[0]===Di.SRC_ALPHA&&A[1]===Di.ONE&&A[2]===Di.ZERO&&A[3]===Di.ONE?v.alphaMode=Y.ALPHA_ADD:A[0]===Di.ZERO&&A[1]===Di.ONE_MINUS_SRC_COLOR&&A[2]===Di.ONE&&A[3]===Di.ONE?v.alphaMode=Y.ALPHA_SUBTRACT:A[0]===Di.DST_COLOR&&A[1]===Di.ZERO&&A[2]===Di.ONE&&A[3]===Di.ONE?v.alphaMode=Y.ALPHA_MULTIPLY:A[0]===Di.SRC_ALPHA&&A[1]===Di.ONE_MINUS_SRC_COLOR&&A[2]===Di.ONE&&A[3]===Di.ONE&&(v.alphaMode=Y.ALPHA_MAXIMIZED))}}}let Tc=class Dp{static RegisterExtension(e){if(Dp.Extensions[e.name]){X.Error('Tool with the same name "'+e.name+'" already exists');return}Dp.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,l){return t.useRightHandedSystem=!0,Ps.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=[],X.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=[],u=[];for(const d in h.nodes){const f=h.nodes[d];f.babylonNode instanceof ut&&c.push(f.babylonNode)}for(const d in h.skins){const f=h.skins[d];f.babylonSkeleton instanceof eo&&u.push(f.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{tE(h),JT(h),!Ti.IncrementalLoading&&n&&n(c,u)})}),Ti.IncrementalLoading&&n&&n(c,u)},l),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((o,l)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{o({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},n,h=>{l(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,Ps.LoadRuntimeAsync(e,t,i,o=>{Ps.LoadRuntimeExtensionsAsync(o,()=>{this._createNodes(o),this._loadBuffersAsync(o,()=>{this._loadShadersAsync(o,()=>{tE(o),JT(o),Ti.IncrementalLoading||s()})}),Ti.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,o=>{n(new Error(o))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{Ps.LoadShaderStringAsync(e,r,o=>{o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(xt.ShadersStore[r+(n.type===Ip.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},()=>{X.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)():X.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{Ps.LoadBufferAsync(e,r,o=>{e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[r].byteLength&&X.Error("Buffer named "+r+" is length "+o.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=o),e.loadedBufferCount===e.buffersCount&&t()},()=>{X.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)():X.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;i<t.nodes.length;i++)Gu(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++)Gu(e,t.nodes[s],null)}}};Tc.Extensions={};class Ps{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){Ps._ApplyExtensions(n=>n.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(ra.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){Ps._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){Ps._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{ra.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){Ps._LoadTextureBufferAsync(e,t,r=>{r&&Ps._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){Ps._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{ra.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){Ps._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{ra.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){Ps._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{ra.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){Ps._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{ra.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in Tc.Extensions){const s=Tc.Extensions[i];if(e(s))return}t()}}Ti._CreateGLTF1Loader=()=>new Tc;const NV="binary_glTF";class FV extends Ps{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(ra.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==NV?!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],o=e.bufferViews[n.bufferView],l=cs.GetBufferFromBufferView(e,o,0,o.byteLength,ka.UNSIGNED_BYTE);return i(l),!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],o=cs.GetBufferFromBufferView(e,n,0,n.byteLength,ka.UNSIGNED_BYTE);return setTimeout(()=>{const l=cs.DecodeBufferToText(o);i(l)}),!0}}Tc.RegisterExtension(new FV);class wV extends Ps{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 Ho(r.name,new m(0,1,0),e.scene),o=r.ambient;o&&(n.diffuse=q.FromArray(o.color||[1,1,1]));break}case"point":{const n=new Pc(r.name,new m(10,10,10),e.scene),o=r.point;o&&(n.diffuse=q.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new Hr(r.name,new m(0,-1,0),e.scene),o=r.directional;o&&(n.diffuse=q.FromArray(o.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const o=new hr(r.name,new m(0,10,0),new m(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);o.diffuse=q.FromArray(n.color||[1,1,1])}break}default:X.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 o=new de(t,e.scene);return o.sideOrientation=ee.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(o.disableLighting=!0),o.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,o.alpha=n.values.transparency===void 0?1:n.values.transparency,o.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=q.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=q.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=q.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=q.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){ra.LoadTextureBufferAsync(e,t,n=>{ra.CreateTextureAsync(e,t,n,o=>i[s]=o)},r)}}Tc.RegisterExtension(new wV);function iE(a,e,t,i){return m.FromArray(e,t).scaleInPlace(i)}function LV(a,e,t,i){return Q.FromArray(e,t).scaleInPlace(i)}function BV(a,e,t,i){const s=new Array(a._numMorphTargets);for(let r=0;r<s.length;r++)s[r]=e[t++]*i;return s}class Td{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new K(e,this.name,t,this.type);return s.setKeys(i),s}}class q_ extends Td{buildAnimations(e,t,i,s,r){r(e._babylonTransformNode,this._buildAnimation(t,i,s))}}class UV extends Td{buildAnimations(e,t,i,s,r){if(e._numMorphTargets)for(let n=0;n<e._numMorphTargets;n++){const o=new K(`${t}_${n}`,this.name,i,this.type);if(o.setKeys(s.map(l=>({frame:l.frame,inTangent:l.inTangent?l.inTangent[n]:void 0,value:l.value[n],outTangent:l.outTangent?l.outTangent[n]:void 0,interpolation:l.interpolation}))),e._primitiveBabylonMeshes){for(const l of e._primitiveBabylonMeshes)if(l.morphTargetManager){const h=l.morphTargetManager.getTarget(n),c=o.clone();h.animations.push(c),r(h,c)}}}}}const $c={translation:[new q_(K.ANIMATIONTYPE_VECTOR3,"position",iE,()=>3)],rotation:[new q_(K.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",LV,()=>4)],scale:[new q_(K.ANIMATIONTYPE_VECTOR3,"scaling",iE,()=>3)],weights:[new UV(K.ANIMATIONTYPE_FLOAT,"influence",BV,a=>a._numMorphTargets)]};function YC(...a){const e=t=>t&&typeof t=="object";return a.reduce((t,i)=>(Object.keys(i).forEach(s=>{const r=t[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?t[s]=r.concat(...n):e(r)&&e(n)?t[s]=YC(r,n):t[s]=n}),t),{})}class Je{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}class Me{static RegisterExtension(e,t){Me.UnregisterExtension(e)&&O.Warn(`Extension with the name '${e}' already exists`),Me._RegisteredExtensions[e]={factory:t}}static UnregisterExtension(e){return Me._RegisteredExtensions[e]?(delete Me._RegisteredExtensions[e],!0):!1}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._parent=e}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach(e=>e.dispose&&e.dispose()),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then(()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let l=null;if(e){const h={};if(this._gltf.nodes)for(const u of this._gltf.nodes)u.name&&(h[u.name]=u.index);l=(e instanceof Array?e:[e]).map(u=>{const d=h[u];if(d===void 0)throw new Error(`Failed to find node '${u}'`);return d})}return this._loadAsync(r,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}loadAsync(e,t,i,s,r=""){return Promise.resolve().then(()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,()=>{})))}_loadAsync(e,t,i,s){return Promise.resolve().then(()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${gr[gr.LOADING]} => ${gr[gr.READY]}`,n=`${gr[gr.LOADING]} => ${gr[gr.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(gr.LOADING),this._extensionsOnLoading();const o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){const c=Je.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${c.index}`,c))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let c=0;c<this._gltf.materials.length;++c){const u=this._gltf.materials[c],d="/materials/"+c,f=ee.TriangleFillMode;o.push(this._loadMaterialAsync(d,u,null,f,()=>{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then(()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(gr.READY),this._startAnimations(),s())).then(c=>(this._parent._endPerformanceCounter(r),X.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(n),this._parent._setState(gr.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},u=>{this._parent.onErrorObservable.notifyObservers(u),this._parent.onErrorObservable.clear(),this.dispose()})}),c))}).catch(r=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(r),this._parent.onErrorObservable.clear(),this.dispose()),r})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLength<e.bin.byteLength-3||i.byteLength>e.bin.byteLength)&&O.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else O.Warn("Unexpected BIN chunk")}}_setupData(){if(Je.Assign(this._gltf.accessors),Je.Assign(this._gltf.animations),Je.Assign(this._gltf.buffers),Je.Assign(this._gltf.bufferViews),Je.Assign(this._gltf.cameras),Je.Assign(this._gltf.images),Je.Assign(this._gltf.materials),Je.Assign(this._gltf.meshes),Je.Assign(this._gltf.nodes),Je.Assign(this._gltf.samplers),Je.Assign(this._gltf.scenes),Je.Assign(this._gltf.skins),Je.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const s of i.children)e[s]=i.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=s===void 0?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in Me._RegisteredExtensions){const t=Me._RegisteredExtensions[e].factory(this);t.name!==e&&O.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired){for(const e of this._gltf.extensionsRequired)if(!this._extensions.some(i=>i.name===e&&i.enabled))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new z("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case ku.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],Me._LoadTransform(t,this._rootBabylonMesh));break}case ku.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const r of t.nodes){const n=Je.Get(`${e}/nodes/${r}`,this._gltf.nodes,r);s.push(this.loadNodeAsync(`/nodes/${n.index}`,n,o=>{o.parent=this._rootBabylonMesh}))}for(const r of this._postSceneLoadActions)r();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{const r=s.geometry;r&&e.indexOf(r)===-1&&e.push(r)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof ut&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{e.push(s)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case Ol.NONE:break;case Ol.FIRST:{const e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case Ol.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:{O.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=o=>{if(Me.AddPointerMetadata(o,e),Me._LoadTransform(t,o),t.camera!=null){const l=Je.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${l.index}`,l,h=>{h.parent=o}))}if(t.children)for(const l of t.children){const h=Je.Get(`${e}/children/${l}`,this._gltf.nodes,l);r.push(this.loadNodeAsync(`/nodes/${h.index}`,h,c=>{c.parent=o}))}i(o)};if(t.mesh==null||t.skin!=null){const o=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const l=new Ke(o,this._babylonScene);l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=l:t._babylonTransformNodeForSkin=l,n(l)}if(t.mesh!=null)if(t.skin==null){const o=Je.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,n))}else{const o=Je.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,l=>{const h=t._babylonTransformNodeForSkin;l.metadata=YC(h.metadata,l.metadata||{});const c=Je.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${c.index}`,t,c,u=>{this._forEachPrimitive(t,d=>{d.skeleton=u}),this._postSceneLoadActions.push(()=>{if(c.skeleton!=null){const d=Je.Get(`/skins/${c.index}/skeleton`,this._gltf.nodes,c.skeleton).parent;t.index===d.index?l.parent=h.parent:l.parent=d._babylonTransformNode}else l.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:l})})}))}))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(t,o=>{o.geometry&&o.geometry.useBoundingInfoFromGeometry?o._updateBoundingInfo():o.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);r[0].index==null&&Je.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(r.length===1){const l=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,h=>{t._babylonTransformNode=h,t._primitiveBabylonMeshes=[h]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Ke(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const l of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,h=>{h.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(h)}))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!s.primitives[0].targets;let h,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,h=r._instanceData.babylonSourceMesh.createInstance(t),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const u=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const d=new z(t,this._babylonScene);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,d),u.push(this._loadVertexDataAsync(e,r,d).then(_=>this._loadMorphTargetsAsync(e,r,d,_).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,_.applyToMesh(d),_._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})));const f=Me._GetDrawMode(e,r.mode);if(r.material==null){let _=this._defaultBabylonMaterialData[f];_||(_=this._createDefaultMaterial("__GLTFLoader._default",f),this._parent.onMaterialLoadedObservable.notifyObservers(_),this._defaultBabylonMaterialData[f]=_),d.material=_}else if(!this.parent.skipMaterials){const _=Je.Get(`${e}/material`,this._gltf.materials,r.material);u.push(this._loadMaterialAsync(`/materials/${_.index}`,_,d,f,p=>{d.material=p}))}c=Promise.all(u),l&&(r._instanceData={babylonSourceMesh:d,promise:c}),h=d}return Me.AddPointerMetadata(h,e),this._parent.onMeshLoadedObservable.notifyObservers(h),n(h),this.logClose(),c.then(()=>h)}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new zi(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{const h=Je.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${h.index}`,h).then(c=>{o.setIndices(c)}))}const l=(h,c,u)=>{if(r[h]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(c)===-1&&i._delayInfo.push(c);const d=Je.Get(`${e}/attributes/${h}`,this._gltf.accessors,r[h]);n.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,c).then(f=>{if(f.getKind()===y.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&d.min&&d.max){const _=U.Vector3[0].copyFromFloats(...d.min),p=U.Vector3[1].copyFromFloats(...d.max);if(d.normalized&&d.componentType!==5126){let g=1;switch(d.componentType){case 5120:g=127;break;case 5121:g=255;break;case 5122:g=32767;break;case 5123:g=65535;break}const x=1/g;_.scaleInPlace(x),p.scaleInPlace(x)}o._boundingInfo=new or(_,p),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(f,d.count)})),c==y.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),u&&u(d)};return l("POSITION",y.PositionKind),l("NORMAL",y.NormalKind),l("TANGENT",y.TangentKind),l("TEXCOORD_0",y.UVKind),l("TEXCOORD_1",y.UV2Kind),l("TEXCOORD_2",y.UV3Kind),l("TEXCOORD_3",y.UV4Kind),l("TEXCOORD_4",y.UV5Kind),l("TEXCOORD_5",y.UV6Kind),l("JOINTS_0",y.MatricesIndicesKind),l("WEIGHTS_0",y.MatricesWeightsKind),l("JOINTS_1",y.MatricesIndicesExtraKind),l("WEIGHTS_1",y.MatricesWeightsExtraKind),l("COLOR_0",y.ColorKind,h=>{h.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(n).then(()=>o)}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(t._numMorphTargets==null)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new zn(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o<s.targets.length;o++){const l=t.weights?t.weights[o]:i.weights?i.weights[o]:0,h=n?n[o]:`morphTarget${o}`;r.morphTargetManager.addTarget(new Fo(h,l,r.getScene()))}}_loadMorphTargetsAsync(e,t,i,s){if(!t.targets)return Promise.resolve();const r=new Array,n=i.morphTargetManager;for(let o=0;o<n.numTargets;o++){const l=n.getTarget(o);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${o}`,s,t.targets[o],l))}return Promise.all(r).then(()=>{n.areUpdatesFrozen=!1})}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(o,l,h)=>{if(i[o]==null)return;const c=t.getVertexBuffer(l);if(!c)return;const u=Je.Get(`${e}/${o}`,this._gltf.accessors,i[o]);r.push(this._loadFloatAccessorAsync(`/accessors/${u.index}`,u).then(d=>{h(c,d)}))};return n("POSITION",y.PositionKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(l.length,(c,u)=>{h[u]=l[u]+c}),s.setPositions(h)}),n("NORMAL",y.NormalKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(h.length,(c,u)=>{h[u]=l[u]+c}),s.setNormals(h)}),n("TANGENT",y.TangentKind,(o,l)=>{const h=new Float32Array(l.length/3*4);let c=0;o.forEach(l.length/3*4,(u,d)=>{(d+1)%4!==0&&(h[c]=l[c]+u,c++)}),s.setTangents(h)}),Promise.all(r).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=m.Zero(),s=Q.Identity(),r=m.One();e.matrix?D.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=m.FromArray(e.translation)),e.rotation&&(s=Q.FromArray(e.rotation)),e.scale&&(r=m.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new eo(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(h=>{this._updateBoneMatrices(o,h)});return i._data={babylonSkeleton:o,promise:l},s(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){const r=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(r)if(t.skeleton===void 0)t.skeleton=r.index;else{const n=(l,h)=>{for(;h.parent;h=h.parent)if(h.parent===l)return!0;return!1},o=Je.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==r&&!n(o,r)&&(O.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=r.index)}else O.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=Je.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;const i={};for(const r of t){const n=[];let o=Je.Get(`${e}/${r}`,this._gltf.nodes,r);for(;o.index!==-1;)n.unshift(o),o=o.parent;i[r]=n}let s=null;for(let r=0;;++r){let n=i[t[0]];if(r>=n.length)return s;const o=n[r];for(let l=1;l<t.length;++l)if(n=i[t[l]],r>=n.length||o!==n[r])return s;s=o}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?n=this._loadBone(e.parent,t,i,s):t.skeleton!==void 0&&O.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new Ut(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);const i=Je.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const s=D.Identity(),r=i._index;t&&r!==-1&&(D.FromArrayToRef(t,r*16,s),s.invertToRef(s));const n=i.getParent();n&&s.multiplyToRef(n.getAbsoluteInverseBindMatrix(),s),i.updateMatrix(s,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?D.FromArray(e.matrix):D.Compose(e.scale?m.FromArray(e.scale):m.One(),e.rotation?Q.FromArray(e.rotation):Q.Identity(),e.translation?m.FromArray(e.translation):m.Zero())}loadCameraAsync(e,t,i=()=>{}){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new qs(t.name||`camera${t.index}`,m.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=o.yfov,n.minZ=o.znear,n.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=ve.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return Me.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then(()=>n)}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i<e.length;i++){const s=e[i];t.push(this.loadAnimationAsync(`/animations/${s.index}`,s).then(r=>{r.targetedAnimations.length===0&&r.dispose()}))}return Promise.all(t).then(()=>{})}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new Nn(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;Je.Assign(t.channels),Je.Assign(t.samplers);for(const n of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(o,l)=>{o.animations=o.animations||[],o.animations.push(l),s.addTargetedAnimation(l,o)}));return Promise.all(r).then(()=>(s.normalize(0),s))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(s.target.node==null)return Promise.resolve();const o=Je.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if(s.target.path==="weights"&&!o._numMorphTargets||s.target.path!=="weights"&&!o._babylonTransformNode)return Promise.resolve();let l;switch(s.target.path){case"translation":{l=$c.translation;break}case"rotation":{l=$c.rotation;break}case"scale":{l=$c.scale;break}case"weights":{l=$c.weights;break}default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const h={object:o,info:l};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,h,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,l=1/o,h=Je.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,h).then(c=>{let u=0;const d=r.object,f=r.info;for(const _ of f){const p=_.getStride(d),g=c.input,x=c.output,T=new Array(g.length);let S=0;switch(c.interpolation){case"STEP":{for(let C=0;C<g.length;C++){const v=_.getValue(d,x,S,1);S+=p,T[C]={frame:g[C]*o,value:v,interpolation:Kd.STEP}}break}case"CUBICSPLINE":{for(let C=0;C<g.length;C++){const v=_.getValue(d,x,S,l);S+=p;const b=_.getValue(d,x,S,1);S+=p;const A=_.getValue(d,x,S,l);S+=p,T[C]={frame:g[C]*o,inTangent:v,value:b,outTangent:A}}break}case"LINEAR":{for(let C=0;C<g.length;C++){const v=_.getValue(d,x,S,1);S+=p,T[C]={frame:g[C]*o,value:v}}break}}if(S>0){const C=`${i.name||`animation${i.index}`}_channel${s.index}_${u}`;_.buildAnimations(d,C,o,T,(v,b)=>{++u,n(v,b)})}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=Je.Get(`${e}/input`,this._gltf.accessors,t.input),r=Je.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then(([n,o])=>({input:n,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(n=>{try{return new Uint8Array(n.buffer,n.byteOffset+i,s)}catch(o){throw new Error(`${e}: ${o.message}`)}})}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=Je.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=Me._GetNumComponents(e,t.type),r=s*y.GetTypeByteLength(t.componentType),n=s*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(n));else{const o=Je.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===r))return Me._GetTypedArray(e,t.componentType,l,t.byteOffset,n);{const h=new i(n);return y.ForEach(l,t.byteOffset||0,o.byteStride||r,s,t.componentType,h.length,t.normalized||!1,(c,u)=>{h[u]=c}),h}})}if(t.sparse){const o=t.sparse;t._data=t._data.then(l=>{const h=l,c=Je.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=Je.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${c.index}`,c),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([d,f])=>{const _=Me._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),p=s*o.count;let g;if(t.componentType===5126&&!t.normalized)g=Me._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,p);else{const T=Me._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,p);g=new i(p),y.ForEach(T,0,r,s,t.componentType,g.length,t.normalized||!1,(S,C)=>{g[C]=S})}let x=0;for(let T=0;T<_.length;T++){let S=_[T]*s;for(let C=0;C<s;C++)h[S++]=g[x++]}return h})})}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if(t.type!=="SCALAR")throw new Error(`${e}/type: Invalid value ${t.type}`);if(t.componentType!==5121&&t.componentType!==5123&&t.componentType!==5125)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const i=Me._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,i)}else{const i=Je.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i).then(s=>Me._GetTypedArray(e,t.componentType,s,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new Ji(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var r;if((r=t._babylonVertexBuffer)!=null&&r[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(n=>new y(s,n,i,!1));else{const n=Je.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then(o=>{const l=Me._GetNumComponents(e,t.type);return new y(s,o,i,!1,void 0,n.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=q.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=q.White(),i.metallic=t.metallicFactor==null?1:t.metallicFactor,i.roughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,r=>{r.name=`${i.name} (Base Color)`,i.albedoTexture=r})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,r=>{r.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=r})),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,i,s,r=()=>{}){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const l=this.createMaterial(e,t,s);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[s]=o,Me.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{const l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),r(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new ye(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=ye.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?q.FromArray(t.emissiveFactor):new q(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,r=>{r.name=`${i.name} (Normal)`,i.bumpTexture=r})),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,t.normalTexture.scale!=null&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,r=>{r.name=`${i.name} (Occlusion)`,i.ambientTexture=r})),i.useAmbientInGrayScale=!0,t.occlusionTexture.strength!=null&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,r=>{r.name=`${i.name} (Emissive)`,i.emissiveTexture=r})),Promise.all(s).then(()=>{})}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=ye.PBRMATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=ye.PBRMATERIAL_ALPHATEST,i.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=ye.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=Je.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,o=>{o.coordinatesIndex=t.texCoord||0,Me.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),n}_loadTextureAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=t.sampler==null?Me.DefaultSampler:Je.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=Je.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=()=>{},r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,h=new Yc;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(d,f)=>{this._disposed||h.reject(new Error(`${e}: ${f&&f.message?f.message:d||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},u=new k(null,this._babylonScene,c);return u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(h.promise),l.push(this.loadImageAsync(`/images/${i.index}`,i).then(d=>{const f=i.uri||`${this._fileName}#image${i.index}`,_=`data:${this._uniqueRootUrl}${f}`;u.updateURL(_,d)})),u.wrapU=o.wrapU,u.wrapV=o.wrapV,s(u),Promise.all(l).then(()=>u)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:Me._GetTextureSamplingMode(e,t),wrapU:Me._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Me._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=Je.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!Me._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Sf(i)){const r=new Uint8Array(Xu(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${r.length} bytes)`),Promise.resolve(r)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(r=>new Promise((n,o)=>{this._parent._loadFile(this._babylonScene,r,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),n(new Uint8Array(l)))},!0,l=>{o(new Su(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t??10497,t){case 33071:return k.CLAMP_ADDRESSMODE;case 33648:return k.MIRROR_ADDRESSMODE;case 10497:return k.WRAP_ADDRESSMODE;default:return O.Warn(`${e}: Invalid value (${t})`),k.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=t.magFilter==null?9729:t.magFilter,s=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(s){case 9728:return k.LINEAR_NEAREST;case 9729:return k.LINEAR_LINEAR;case 9984:return k.LINEAR_NEAREST_MIPNEAREST;case 9985:return k.LINEAR_LINEAR_MIPNEAREST;case 9986:return k.LINEAR_NEAREST_MIPLINEAR;case 9987:return k.LINEAR_LINEAR_MIPLINEAR;default:return O.Warn(`${e}/minFilter: Invalid value (${s})`),k.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&O.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return k.NEAREST_NEAREST;case 9729:return k.NEAREST_LINEAR;case 9984:return k.NEAREST_NEAREST_MIPNEAREST;case 9985:return k.NEAREST_LINEAR_MIPNEAREST;case 9986:return k.NEAREST_NEAREST_MIPLINEAR;case 9987:return k.NEAREST_LINEAR_MIPLINEAR;default:return O.Warn(`${e}/minFilter: Invalid value (${s})`),k.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=Me._GetTypedArrayConstructor(`${e}/componentType`,t),l=y.GetTypeByteLength(t);return s%l!==0?(O.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new o(n.slice(s,s+r*l),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return X.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return ee.PointListDrawMode;case 1:return ee.LineListDrawMode;case 2:return ee.LineLoopDrawMode;case 3:return ee.LineStripDrawMode;case 4:return ee.TriangleFillMode;case 5:return ee.TriangleStripDrawMode;case 6:return ee.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials){for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const r of s.babylonMeshes){r.computeWorldMatrix(!0);const n=s.babylonMaterial;e.push(n.forceCompilationAsync(r)),e.push(n.forceCompilationAsync(r,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(r,{clipPlane:!0})),e.push(n.forceCompilationAsync(r,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const s=i.getShadowGenerator();s&&e.push(s.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const l=i(s);if(l)return l}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const n=t.extensions[i];return n?s(`${e}/extensions/${i}`,n):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const n=t.extras[i];return n?s(`${e}/extras/${i}`,n):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}Me._RegisteredExtensions={};Me.DefaultSampler={index:-1};Ti._CreateGLTF2Loader=a=>new Me(a);const Op="EXT_lights_image_based";class VV{constructor(e){this.name=Op,this._loader=e,this.enabled=this._loader.isExtensionUsed(Op)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Me.LoadExtensionAsync(e,t,this.name,(i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=Je.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then(o=>{this._loader.babylonScene.environmentTexture=o})),this._loader.logClose(),Promise.all(r).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r<t.specularImages.length;r++){const n=t.specularImages[r];s[r]=new Array(n.length);for(let o=0;o<n.length;o++){const l=`${e}/specularImages/${r}/${o}`;this._loader.logOpen(`${l}`);const h=n[o],c=Je.Get(l,this._loader.gltf.images,h);i.push(this._loader.loadImageAsync(`/images/${h}`,c).then(u=>{s[r][o]=u})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then(()=>{const r=new gg(this._loader.babylonScene,null,t.specularImageSize);if(r.name=t.name||"environment",t._babylonTexture=r,t.intensity!=null&&(r.level=t.intensity),t.rotation){let h=Q.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(h=Q.Inverse(h)),D.FromQuaternionToRef(h,r.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const n=Bo.FromArray(t.irradianceCoefficients);n.scaleInPlace(t.intensity),n.convertIrradianceToLambertianRadiance();const o=ma.FromHarmonics(n),l=(s.length-1)/ge.Log2(t.specularImageSize);return r.updateRGBDAsync(s,o,l)})}return t._loaded.then(()=>t._babylonTexture)}}Me.RegisterExtension(Op,a=>new VV(a));const Np="EXT_mesh_gpu_instancing";class kV{constructor(e){this.name=Np,this._loader=e,this.enabled=this._loader.isExtensionUsed(Np)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{this._loader._disableInstancedMesh++;const n=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return n;const o=new Array;let l=0;const h=c=>{if(r.attributes[c]==null){o.push(Promise.resolve(null));return}const u=Je.Get(`${s}/attributes/${c}`,this._loader.gltf.accessors,r.attributes[c]);if(o.push(this._loader._loadFloatAccessorAsync(`/accessors/${u.bufferView}`,u)),l===0)l=u.count;else if(l!==u.count)throw new Error(`${s}/attributes: Instance buffer accessors do not have the same count.`)};return h("TRANSLATION"),h("ROTATION"),h("SCALE"),n.then(c=>Promise.all(o).then(([u,d,f])=>{const _=new Float32Array(l*16);U.Vector3[0].copyFromFloats(0,0,0),U.Quaternion[0].copyFromFloats(0,0,0,1),U.Vector3[1].copyFromFloats(1,1,1);for(let p=0;p<l;++p)u&&m.FromArrayToRef(u,p*3,U.Vector3[0]),d&&Q.FromArrayToRef(d,p*4,U.Quaternion[0]),f&&m.FromArrayToRef(f,p*3,U.Vector3[1]),D.ComposeToRef(U.Vector3[1],U.Quaternion[0],U.Vector3[0],U.Matrix[0]),U.Matrix[0].copyToArray(_,p*16);for(const p of t._primitiveBabylonMeshes)p.thinInstanceSetBuffer("matrix",_,16,!0);return c}))})}}Me.RegisterExtension(Np,a=>new kV(a));const Fp="EXT_meshopt_compression";class GV{constructor(e){this.name=Fp,this.enabled=e.isExtensionUsed(Fp),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return Me.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=Je.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then(o=>na.Default.decodeGltfBufferAsync(o,s.count,s.byteStride,s.mode,s.filter)),r._meshOptData})}}Me.RegisterExtension(Fp,a=>new GV(a));const wp="EXT_texture_webp";class zV{constructor(e){this.name=wp,this._loader=e,this.enabled=e.isExtensionUsed(wp)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Me.DefaultSampler:Je.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Je.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}Me.RegisterExtension(wp,a=>new zV(a));const Lp="KHR_draco_mesh_compression";class WV{constructor(e){this.name=Lp,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=Cr.DecoderAvailable&&this._loader.isExtensionUsed(Lp)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},l=(c,u)=>{const d=r.attributes[c];if(d!=null&&(i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(u)===-1&&i._delayInfo.push(u),n[u]=d,this.useNormalizedFlagFromAccessor)){const f=Je.TryGet(this._loader.gltf.accessors,t.attributes[c]);f&&(o[u]=f.normalized||!1)}};l("POSITION",y.PositionKind),l("NORMAL",y.NormalKind),l("TANGENT",y.TangentKind),l("TEXCOORD_0",y.UVKind),l("TEXCOORD_1",y.UV2Kind),l("TEXCOORD_2",y.UV3Kind),l("TEXCOORD_3",y.UV4Kind),l("TEXCOORD_4",y.UV5Kind),l("TEXCOORD_5",y.UV6Kind),l("JOINTS_0",y.MatricesIndicesKind),l("WEIGHTS_0",y.MatricesWeightsKind),l("COLOR_0",y.ColorKind);const h=Je.Get(s,this._loader.gltf.bufferViews,r.bufferView);return h._dracoBabylonGeometry||(h._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${h.index}`,h).then(c=>(this.dracoCompression||Cr.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,c,n,o).catch(d=>{throw new Error(`${e}: ${d.message}`)}))),h._dracoBabylonGeometry})}}Me.RegisterExtension(Lp,a=>new WV(a));const Bp="KHR_lights_punctual";class HV{constructor(e){this.name=Bp,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bp)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Je.Assign(this._lights)}}loadNodeAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,n=>{let o;const l=Je.Get(s,this._lights,r.light),h=l.name||n.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,l.type){case"directional":{const c=new Hr(h,m.Backward(),this._loader.babylonScene);c.position.setAll(0),o=c;break}case"point":{o=new Pc(h,m.Zero(),this._loader.babylonScene);break}case"spot":{const c=new hr(h,m.Zero(),m.Backward(),0,1,this._loader.babylonScene);c.angle=(l.spot&&l.spot.outerConeAngle||Math.PI/4)*2,c.innerAngle=(l.spot&&l.spot.innerConeAngle||0)*2,o=c;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${l.type})`)}o._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,l._babylonLight=o,o.falloffType=st.FALLOFF_GLTF,o.diffuse=l.color?q.FromArray(l.color):q.White(),o.intensity=l.intensity==null?1:l.intensity,o.range=l.range==null?Number.MAX_VALUE:l.range,o.parent=n,this._loader._babylonLights.push(o),Me.AddPointerMetadata(o,s),i(n)})))}}Me.RegisterExtension(Bp,a=>new HV(a));const Up="KHR_materials_pbrSpecularGlossiness";class XV{constructor(e){this.name=Up,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Up)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=q.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=q.White(),i.reflectivityColor=t.specularFactor?q.FromArray(t.specularFactor):q.White(),i.microSurface=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,r=>{r.name=`${i.name} (Diffuse)`,i.albedoTexture=r})),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,r=>{r.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=r,i.reflectivityTexture.hasAlpha=!0})),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then(()=>{})}}Me.RegisterExtension(Up,a=>new XV(a));const Vp="KHR_materials_unlit";class YV{constructor(e){this.name=Vp,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,()=>this._loadUnlitPropertiesAsync(e,t,i))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=q.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=q.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,n=>{n.name=`${i.name} (Base Color)`,i.albedoTexture=n}))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}}Me.RegisterExtension(Vp,a=>new YV(a));const kp="KHR_materials_clearcoat";class $V{constructor(e){this.name=kp,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(kp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,t.clearcoatFactor!=null?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,r=>{r.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=r})),t.clearcoatRoughnessFactor!=null?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,r=>{r.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=r}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,r=>{r.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=r})),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,t.clearcoatNormalTexture.scale!=null&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then(()=>{})}}Me.RegisterExtension(kp,a=>new $V(a));const Gp="KHR_materials_iridescence";class KV{constructor(e){this.name=Gp,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,r=>{r.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=r})),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,r=>{r.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=r})),Promise.all(s).then(()=>{})}}Me.RegisterExtension(Gp,a=>new KV(a));const zp="KHR_materials_anisotropy";class jV{constructor(e){this.name=zp,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(zp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,r=>{r.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=r})),Promise.all(s).then(()=>{})}}Me.RegisterExtension(zp,a=>new jV(a));const Wp="KHR_materials_emissive_strength";class qV{constructor(e){this.name=Wp,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then(()=>{this._loadEmissiveProperties(s,r,i)}))}_loadEmissiveProperties(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);t.emissiveStrength!==void 0&&(i.emissiveIntensity=t.emissiveStrength)}}Me.RegisterExtension(Wp,a=>new qV(a));const Hp="KHR_materials_sheen";class QV{constructor(e){this.name=Hp,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Hp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,t.sheenColorFactor!=null?i.sheen.color=q.FromArray(t.sheenColorFactor):i.sheen.color=q.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,r=>{r.name=`${i.name} (Sheen Color)`,i.sheen.texture=r})),t.sheenRoughnessFactor!==void 0?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,r=>{r.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=r}))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then(()=>{})}}Me.RegisterExtension(Hp,a=>new QV(a));const Xp="KHR_materials_specular";class ZV{constructor(e){this.name=Xp,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const s=new Array;return t.specularFactor!==void 0&&(i.metallicF0Factor=t.specularFactor),t.specularColorFactor!==void 0&&(i.metallicReflectanceColor=q.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,r=>{r.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=r,i.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,r=>{r.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=r})),Promise.all(s).then(()=>{})}}Me.RegisterExtension(Xp,a=>new ZV(a));const Yp="KHR_materials_ior";class S_{constructor(e){this.name=Yp,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);return t.ior!==void 0?i.indexOfRefraction=t.ior:i.indexOfRefraction=S_._DEFAULT_IOR,Promise.resolve()}}S_._DEFAULT_IOR=1.5;Me.RegisterExtension(Yp,a=>new S_(a));const sr="KHR_materials_variants";class Fa{constructor(e){this.name=sr,this._loader=e,this.enabled=this._loader.isExtensionUsed(sr)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Fa.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${sr} extension`);const s=r=>{const n=i.variants[r];if(n)for(const o of n)o.mesh.material=o.material};if(t instanceof Array)for(const r of t)s(r);else s(t);i.lastSelected=t}selectVariant(e,t){Fa.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${sr} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){Fa.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${sr} extension`);return t.lastSelected}getLastSelectedVariant(e){return Fa.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return((i=(t=e==null?void 0:e._internalMetadata)==null?void 0:t.gltf)==null?void 0:i[sr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return Me.LoadExtensionAsync(e,r,this.name,(o,l)=>{const h=new Array;return h.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,c=>{if(n(c),c instanceof z){const u=Me._GetDrawMode(e,r.mode),d=this._loader.rootBabylonMesh,f=d?d._internalMetadata=d._internalMetadata||{}:{},_=f.gltf=f.gltf||{},p=_[sr]=_[sr]||{lastSelected:null,original:[],variants:{}};p.original.push({mesh:c,material:c.material});for(let g=0;g<l.mappings.length;++g){const x=l.mappings[g],T=Je.Get(`${o}/mappings/${g}/material`,this._loader.gltf.materials,x.material);h.push(this._loader._loadMaterialAsync(`#/materials/${x.material}`,T,c,u,S=>{for(let C=0;C<x.variants.length;++C){const v=x.variants[C],b=Je.Get(`/extensions/${sr}/variants/${v}`,this._variants,v);p.variants[b.name]=p.variants[b.name]||[],p.variants[b.name].push({mesh:c,material:S}),c.onClonedObservable.add(A=>{const P=A;let L=null,w=P;do{if(w=w.parent,!w)return;L=Fa._GetExtensionMetadata(w)}while(L===null);if(d&&L===Fa._GetExtensionMetadata(d)){w._internalMetadata={};for(const $ in d._internalMetadata)w._internalMetadata[$]=d._internalMetadata[$];w._internalMetadata.gltf=[];for(const $ in d._internalMetadata.gltf)w._internalMetadata.gltf[$]=d._internalMetadata.gltf[$];w._internalMetadata.gltf[sr]={lastSelected:null,original:[],variants:{}};for(const $ of L.original)w._internalMetadata.gltf[sr].original.push({mesh:$.mesh,material:$.material});for(const $ in L.variants)if(Object.prototype.hasOwnProperty.call(L.variants,$)){w._internalMetadata.gltf[sr].variants[$]=[];for(const J of L.variants[$])w._internalMetadata.gltf[sr].variants[$].push({mesh:J.mesh,material:J.material})}L=w._internalMetadata.gltf[sr]}for(const $ of L.original)$.mesh===c&&($.mesh=P);for(const $ of L.variants[b.name])$.mesh===c&&($.mesh=P)})}}))}}})),Promise.all(h).then(([c])=>c)})}}Me.RegisterExtension(sr,a=>new Fa(a));class Vg{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Y.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Vg._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new G,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter(r=>this._options[r]!==e[r]).length)return;const i={...this._options,...e},s=this._options;this._options=i,i.renderSize!==s.renderSize||i.renderTargetTextureType!==s.renderTargetTextureType||i.generateMipmaps!==s.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=i.samples,this._opaqueRenderTarget.lodGenerationScale=i.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=i.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return e?!!(e instanceof ye&&e.subSurface.isRefractionEnabled):!1}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),X.SetImmediate(()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e)):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e)})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof ye&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),i!==-1?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):t===-1&&this._transparentMeshesCache.push(e)):t!==-1?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):i===-1&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return((e=this._opaqueRenderTarget)==null?void 0:e.getInternalTexture())!==null}_setupRenderTargets(){var i;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new oi("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=((i=this._options.clearColor)==null?void 0:i.clone())??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0;let e,t;this._opaqueRenderTarget.onBeforeBindObservable.add(s=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?s.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(s.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e}),this._transparentMeshesCache.forEach(s=>{this._shouldRenderAsTransmission(s.material)&&(s.material.refractionTexture=this._opaqueRenderTarget)})}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const $p="KHR_materials_transmission";class JV{constructor(e){this.name=$p,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed($p),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,i,s){var n,o;if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,s.transmissionFactor!==void 0){r.subSurface.refractionIntensity=s.transmissionFactor;const l=r.getScene();r.subSurface.refractionIntensity&&!l._transmissionHelper?new Vg({},r.getScene()):r.subSurface.refractionIntensity&&!((n=l._transmissionHelper)!=null&&n._isRenderTargetValid())&&((o=l._transmissionHelper)==null||o._setupRenderTargets())}else return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then(l=>{r.subSurface.refractionIntensityTexture=l,r.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Me.RegisterExtension($p,a=>new JV(a));const Kp="KHR_materials_translucency";class e3{constructor(e){this.name=Kp,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Kp),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!0,s.translucencyFactor!==void 0)r.subSurface.translucencyIntensity=s.translucencyFactor;else return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();return s.translucencyTexture?(s.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,s.translucencyTexture).then(n=>{r.subSurface.translucencyIntensityTexture=n})):Promise.resolve()}}Me.RegisterExtension(Kp,a=>new e3(a));const jp="KHR_materials_volume";class t3{constructor(e){this.name=jp,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(jp),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=s.attenuationDistance!==void 0?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,s.attenuationColor!==void 0&&s.attenuationColor.length==3&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then(n=>{i.subSurface.thicknessTexture=n,i.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Me.RegisterExtension(jp,a=>new t3(a));const qp="KHR_materials_dispersion";class i3{constructor(e){this.name=qp,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(qp)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof ye))throw new Error(`${e}: Material type not supported`);return!i.subSurface.isRefractionEnabled||!s.dispersion||(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion),Promise.resolve()}}Me.RegisterExtension(qp,a=>new i3(a));const Qp="KHR_mesh_quantization";class s3{constructor(e){this.name=Qp,this.enabled=e.isExtensionUsed(Qp)}dispose(){}}Me.RegisterExtension(Qp,a=>new s3(a));const Zp="KHR_texture_basisu";class r3{constructor(e){this.name=Zp,this._loader=e,this.enabled=e.isExtensionUsed(Zp)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Me.DefaultSampler:Je.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Je.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)})}}Me.RegisterExtension(Zp,a=>new r3(a));const Jp="KHR_texture_transform";class n3{constructor(e){this.name=Jp,this._loader=e,this.enabled=this._loader.isExtensionUsed(Jp)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadTextureInfoAsync(e,t,n=>{if(!(n instanceof k))throw new Error(`${s}: Texture type not supported`);r.offset&&(n.uOffset=r.offset[0],n.vOffset=r.offset[1]),n.uRotationCenter=0,n.vRotationCenter=0,r.rotation&&(n.wAng=-r.rotation),r.scale&&(n.uScale=r.scale[0],n.vScale=r.scale[1]),r.texCoord!=null&&(n.coordinatesIndex=r.texCoord),i(n)}))}}Me.RegisterExtension(Jp,a=>new n3(a));const em="KHR_xmp_json_ld";class a3{constructor(e){this.name=em,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(em)}dispose(){this._loader=null}onLoading(){var i,s,r;if(this._loader.rootBabylonMesh===null)return;const e=(i=this._loader.gltf.extensions)==null?void 0:i.KHR_xmp_json_ld,t=(r=(s=this._loader.gltf.asset)==null?void 0:s.extensions)==null?void 0:r.KHR_xmp_json_ld;if(e&&t){const n=+t.packet;e.packets&&n<e.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=e.packets[n])}}}Me.RegisterExtension(em,a=>new a3(a));function dl(a,e,t,i){return q.FromArray(e,t).scale(i)}function o3(a,e,t,i){return e[t+3]*i}function ui(a,e,t,i){return e[t]*i}function tm(a,e,t,i){return-e[t]*i}function Ef(a,e,t,i){return e[t+1]*i}function sE(a,e,t,i){return e[t]*i*2}function ir(a){return{scale:[new ti(K.ANIMATIONTYPE_FLOAT,`${a}.uScale`,ui,()=>2),new ti(K.ANIMATIONTYPE_FLOAT,`${a}.vScale`,Ef,()=>2)],offset:[new ti(K.ANIMATIONTYPE_FLOAT,`${a}.uOffset`,ui,()=>2),new ti(K.ANIMATIONTYPE_FLOAT,`${a}.vOffset`,Ef,()=>2)],rotation:[new ti(K.ANIMATIONTYPE_FLOAT,`${a}.wAng`,tm,()=>1)]}}class ea extends Td{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class ti extends Td{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class Wc extends Td{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const l3={__array__:{__target__:!0,...$c}},h3={__array__:{__target__:!0,orthographic:{xmag:[new ea(K.ANIMATIONTYPE_FLOAT,"orthoLeft",tm,()=>1),new ea(K.ANIMATIONTYPE_FLOAT,"orthoRight",Ef,()=>1)],ymag:[new ea(K.ANIMATIONTYPE_FLOAT,"orthoBottom",tm,()=>1),new ea(K.ANIMATIONTYPE_FLOAT,"orthoTop",Ef,()=>1)],zfar:[new ea(K.ANIMATIONTYPE_FLOAT,"maxZ",ui,()=>1)],znear:[new ea(K.ANIMATIONTYPE_FLOAT,"minZ",ui,()=>1)]},perspective:{yfov:[new ea(K.ANIMATIONTYPE_FLOAT,"fov",ui,()=>1)],zfar:[new ea(K.ANIMATIONTYPE_FLOAT,"maxZ",ui,()=>1)],znear:[new ea(K.ANIMATIONTYPE_FLOAT,"minZ",ui,()=>1)]}}},c3={__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new ti(K.ANIMATIONTYPE_COLOR3,"albedoColor",dl,()=>4),new ti(K.ANIMATIONTYPE_FLOAT,"alpha",o3,()=>4)],metallicFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"metallic",ui,()=>1)],roughnessFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"roughness",ui,()=>1)],baseColorTexture:{extensions:{KHR_texture_transform:ir("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:ir("metallicRoughnessTexture")}}},emissiveFactor:[new ti(K.ANIMATIONTYPE_COLOR3,"emissiveColor",dl,()=>3)],normalTexture:{scale:[new ti(K.ANIMATIONTYPE_FLOAT,"bumpTexture.level",ui,()=>1)],extensions:{KHR_texture_transform:ir("bumpTexture")}},occlusionTexture:{strength:[new ti(K.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",ui,()=>1)],extensions:{KHR_texture_transform:ir("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:ir("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new ti(K.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",ui,()=>1)],anisotropyRotation:[new ti(K.ANIMATIONTYPE_FLOAT,"anisotropy.angle",ui,()=>1)],anisotropyTexture:{extensions:{KHR_texture_transform:ir("emissiveTexture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",ui,()=>1)],clearcoatRoughnessFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",ui,()=>1)],clearcoatTexture:{extensions:{KHR_texture_transform:ir("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new ti(K.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",ui,()=>1)],extensions:{KHR_texture_transform:ir("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:ir("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new ti(K.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",ui,()=>1)]},KHR_materials_emissive_strength:{emissiveStrength:[new ti(K.ANIMATIONTYPE_FLOAT,"emissiveIntensity",ui,()=>1)]},KHR_materials_ior:{ior:[new ti(K.ANIMATIONTYPE_FLOAT,"indexOfRefraction",ui,()=>1)]},KHR_materials_iridescence:{iridescenceFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"iridescence.intensity",ui,()=>1)],iridescenceIor:[new ti(K.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",ui,()=>1)],iridescenceThicknessMinimum:[new ti(K.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",ui,()=>1)],iridescenceThicknessMaximum:[new ti(K.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",ui,()=>1)]},KHR_materials_sheen:{sheenColorFactor:[new ti(K.ANIMATIONTYPE_COLOR3,"sheen.color",dl,()=>3)],sheenRoughnessFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"sheen.roughness",ui,()=>1)],sheenColorTexture:{extensions:{KHR_texture_transform:ir("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:ir("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"metallicF0Factor",ui,()=>1)],specularColorFactor:[new ti(K.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",dl,()=>3)],specularTexture:{extensions:{KHR_texture_transform:ir("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:ir("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",ui,()=>1)],transmissionTexture:{extensions:{KHR_texture_transform:ir("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new ti(K.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",dl,()=>3)],attenuationDistance:[new ti(K.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",ui,()=>1)],thicknessFactor:[new ti(K.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",ui,()=>1)],thicknessTexture:{extensions:{KHR_texture_transform:ir("subSurface.thicknessTexture")}}}}}},u3={KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new Wc(K.ANIMATIONTYPE_COLOR3,"diffuse",dl,()=>3)],intensity:[new Wc(K.ANIMATIONTYPE_FLOAT,"intensity",ui,()=>1)],range:[new Wc(K.ANIMATIONTYPE_FLOAT,"range",ui,()=>1)],spot:{innerConeAngle:[new Wc(K.ANIMATIONTYPE_FLOAT,"innerAngle",sE,()=>1)],outerConeAngle:[new Wc(K.ANIMATIONTYPE_FLOAT,"angle",sE,()=>1)]}}}}},d3={nodes:l3,materials:c3,cameras:h3,extensions:u3};class $C{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,i=this._infoTree,s;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(i.__array__)i=i.__array__;else if(i=i[n],!i)throw new Error(`Path ${e} is invalid`);if(t===void 0)throw new Error(`Path ${e} is invalid`);t=t[n],i.__target__&&(s=t)}return{object:s,info:i}}}const im="KHR_animation_pointer";class f3 extends $C{constructor(e){super(e,d3)}}class _3{constructor(e){this.name=im,this._loader=e,this._pathToObjectConverter=new f3(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(im)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){var h;const n=(h=s.target.extensions)==null?void 0:h.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;s.target.path!=="pointer"&&O.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),s.target.node!=null&&O.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,l=n.pointer;if(!l)throw new Error(`${o}: Pointer is missing`);try{const c=this._pathToObjectConverter.convert(l);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,c,r)}catch{return O.Warn(`${o}/pointer: Invalid pointer (${l}) skipped`),null}}}Me.RegisterExtension(im,a=>new _3(a));const sm="MSFT_audio_emitter";class p3{constructor(e){this.name=sm,this._loader=e,this.enabled=this._loader.isExtensionUsed(sm)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,Je.Assign(this._clips),Je.Assign(this._emitters)}}loadSceneAsync(e,t){return Me.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const n of s.emitters){const o=Je.Get(`${i}/emitters`,this._emitters,n);if(o.refDistance!=null||o.maxDistance!=null||o.rolloffFactor!=null||o.distanceModel!=null||o.innerAngle!=null||o.outerAngle!=null)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${o.index}`,o))}return Promise.all(r).then(()=>{})})}loadNodeAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return this._loader.loadNodeAsync(s,t,o=>{for(const l of r.emitters){const h=Je.Get(`${s}/emitters`,this._emitters,l);n.push(this._loadEmitterAsync(`${s}/emitters/${h.index}`,h).then(()=>{for(const c of h._babylonSounds)c.attachToMesh(o),(h.innerAngle!=null||h.outerAngle!=null)&&(c.setLocalDirectionToMesh(m.Forward()),c.setDirectionalCone(2*X.ToDegrees(h.innerAngle==null?Math.PI:h.innerAngle),2*X.ToDegrees(h.outerAngle==null?Math.PI:h.outerAngle),0))}))}i(o)}).then(o=>Promise.all(n).then(()=>o))})}loadAnimationAsync(e,t){return Me.LoadExtensionAsync(e,t,this.name,(i,s)=>this._loader.loadAnimationAsync(e,t).then(r=>{const n=new Array;Je.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then(()=>r)}))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=Je.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then(s=>URL.createObjectURL(new Blob([s],{type:t.mimeType}))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const i=new Array,s=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let o=0;o<t.clips.length;o++){const l=`/extensions/${this.name}/clips`,h=Je.Get(l,this._clips,t.clips[o].clip);i.push(this._loadClipAsync(`${l}/${t.clips[o].clip}`,h).then(c=>{const u=t._babylonSounds[o]=new Tn(s,c,this._loader.babylonScene,null,r);u.refDistance=t.refDistance||1,u.maxDistance=t.maxDistance||256,u.rolloffFactor=t.rolloffFactor||1,u.distanceModel=t.distanceModel||"exponential"}))}const n=Promise.all(i).then(()=>{const o=t.clips.map(h=>h.weight||1),l=new Sb(t.loop||!1,t._babylonSounds,o);t.innerAngle&&(l.directionalConeInnerAngle=2*X.ToDegrees(t.innerAngle)),t.outerAngle&&(l.directionalConeOuterAngle=2*X.ToDegrees(t.outerAngle)),t.volume&&(l.volume=t.volume),t._babylonData.sound=l});t._babylonData={loaded:n}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return n=>{const o=(r||0)+(n-s);t.play(o)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(r.targetedAnimations.length==0)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,l=Je.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,l).then(()=>{const h=l._babylonData.sound;if(h){const c=new mm(s.time,this._getEventAction(e,h,s.action,s.time,s.startOffset));n.animation.addEvent(c),r.onAnimationGroupEndObservable.add(()=>{h.stop()}),r.onAnimationGroupPauseObservable.add(()=>{h.pause()})}})}}Me.RegisterExtension(sm,a=>new p3(a));const rm="MSFT_lod";class m3{constructor(e){this.name=rm,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new G,this.onMaterialLODsLoadedObservable=new G,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(rm)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then(()=>{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then(()=>{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return Me.LoadExtensionAsync(e,t,this.name,(s,r)=>{let n;const o=this._getLODs(s,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${s}`);for(let l=0;l<o.length;l++){const h=o[l];l!==0&&(this._nodeIndexLOD=l,this._nodeSignalLODs[l]=this._nodeSignalLODs[l]||new Yc);const c=d=>{i(d),d.setEnabled(!1)},u=this._loader.loadNodeAsync(`/nodes/${h.index}`,h,c).then(d=>{if(l!==0){const f=o[l-1];f._babylonTransformNode&&(this._disposeTransformNode(f._babylonTransformNode),delete f._babylonTransformNode)}return d.setEnabled(!0),d});this._nodePromiseLODs[l]=this._nodePromiseLODs[l]||[],l===0?n=u:(this._nodeIndexLOD=null,this._nodePromiseLODs[l].push(u))}return this._loader.logClose(),n})}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:Me.LoadExtensionAsync(e,t,this.name,(n,o)=>{let l;const h=this._getLODs(n,t,this._loader.gltf.materials,o.ids);this._loader.logOpen(`${n}`);for(let c=0;c<h.length;c++){const u=h[c];c!==0&&(this._materialIndexLOD=c);const d=this._loader._loadMaterialAsync(`/materials/${u.index}`,u,i,s,f=>{c===0&&r(f)}).then(f=>{if(c!==0){r(f);const _=h[c-1]._data;_[s]&&(this._disposeMaterials([_[s].babylonMaterial]),delete _[s])}return f});this._materialPromiseLODs[c]=this._materialPromiseLODs[c]||[],c===0?l=d:(this._materialIndexLOD=null,this._materialPromiseLODs[c].push(d))}return this._loader.logClose(),l})}_loadUriAsync(e,t,i){if(this._nodeIndexLOD!==null){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new Yc,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>this._loader.loadUriAsync(e,t,i))}else if(this._materialIndexLOD!==null){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new Yc,this._materialSignalLODs[s].promise.then(()=>this._loader.loadUriAsync(e,t,i))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const r=(n,o)=>{const l=i,h=l+s-1;let c=n[o];return c?(c.start=Math.min(c.start,l),c.end=Math.max(c.end,h)):(c={start:l,end:h,loaded:new Yc},n[o]=c),c.loaded.promise.then(u=>new Uint8Array(u.buffer,u.byteOffset+i-c.start,s))};return this._loader.log("deferred"),this._nodeIndexLOD!==null?r(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?r(this._materialBufferLODs,this._materialIndexLOD):r(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then(s=>{i.loaded.resolve(s)},s=>{i.loaded.reject(s)}))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let n=s.length-1;n>=0;n--)if(r.push(Je.Get(`${e}/ids/${s[n]}`,i,s[n])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const r of e.getChildMeshes())r.material&&t.push(r.material);e.dispose();const s=t.filter(r=>this._loader.babylonScene.meshes.every(n=>n.material!=r));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const s of i.getActiveTextures())t[s.uniqueId]=s;i.dispose()}for(const i in t)for(const s of this._loader.babylonScene.materials)s.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}Me.RegisterExtension(rm,a=>new m3(a));const nm="MSFT_minecraftMesh";class g3{constructor(e){this.name=nm,this._loader=e,this.enabled=this._loader.isExtensionUsed(nm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof ye))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,n}return null})}}Me.RegisterExtension(nm,a=>new g3(a));const am="MSFT_sRGBFactors";class x3{constructor(e){this.name=am,this._loader=e,this.enabled=this._loader.isExtensionUsed(am)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Me.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof ye))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i),o=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,o),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,o),n}return null})}}Me.RegisterExtension(am,a=>new x3(a));const T3={"lifecycle/onStart":xd.ClassName,"lifecycle/onTick":xc.ClassName,log:ql.ClassName,"flow/delay":dd.ClassName,"customEvent/send":ud.ClassName,"customEvent/receive":gc.ClassName,"flow/sequence":eh.ClassName,"world/get":ih.ClassName,"world/set":cd.ClassName,"flow/doN":Zl.ClassName,"variable/get":th.ClassName,"variable/set":Ql.ClassName,"flow/whileLoop":Jl.ClassName,"math/random":oh.ClassName,"math/e":hh.ClassName,"math/pi":ch.ClassName,"math/inf":uh.ClassName,"math/nan":dh.ClassName,"math/abs":fh.ClassName,"math/sign":_h.ClassName,"math/trunc":ph.ClassName,"math/floor":mh.ClassName,"math/ceil":gh.ClassName,"math/fract":xh.ClassName,"math/neg":Th.ClassName,"math/add":sh.ClassName,"math/sub":rh.ClassName,"math/mul":nh.ClassName,"math/div":ah.ClassName,"math/rem":Eh.ClassName,"math/min":Sh.ClassName,"math/max":Ch.ClassName,"math/clamp":vh.ClassName,"math/saturate":bh.ClassName,"math/mix":Ah.ClassName,"math/eq":yh.ClassName,"math/lt":Rh.ClassName,"math/le":T_.ClassName,"math/gt":Ih.ClassName,"math/ge":Ph.ClassName,"math/isnan":Mh.ClassName,"math/isinf":E_.ClassName,"math/rad":Dh.ClassName,"math/deg":Oh.ClassName,"math/sin":Nh.ClassName,"math/cos":Fh.ClassName,"math/tan":wh.ClassName,"math/asin":Lh.ClassName,"math/acos":Bh.ClassName,"math/atan":Uh.ClassName,"math/atan2":Vh.ClassName,"math/sinh":kh.ClassName,"math/cosh":Gh.ClassName,"math/tanh":zh.ClassName,"math/asinh":Wh.ClassName,"math/acosh":Hh.ClassName,"math/atanh":Xh.ClassName,"math/exp":Yh.ClassName,"math/log":$h.ClassName,"math/log2":Kh.ClassName,"math/log10":jh.ClassName,"math/sqrt":qh.ClassName,"math/cbrt":Qh.ClassName,"math/pow":Zh.ClassName,"math/length":Jh.ClassName,"math/normalize":ec.ClassName,"math/dot":lh.ClassName,"math/cross":tc.ClassName,"math/rotate2d":ic.ClassName,"math/rotate3d":sc.ClassName,"math/transpose":rc.ClassName,"math/determinant":nc.ClassName,"math/inverse":ac.ClassName,"math/matmul":oc.ClassName,"math/not":lc.ClassName,"math/and":hc.ClassName,"math/or":cc.ClassName,"math/xor":uc.ClassName,"math/asr":fc.ClassName,"math/lsl":dc.ClassName,"math/clz":_c.ClassName,"math/ctz":pc.ClassName,"math/popcnt":mc.ClassName},E3={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function om(a,e,t){if(a.type!==void 0){const i=e.types&&e.types[a.type];if(!i)throw new Error(`${t}: Unknown type: ${a.type}`);const s=i.signature;if(!s)throw new Error(`${t}: Type ${a.type} has no signature`);const r=E3[s];return{value:a.value,className:r}}else return a.value}function S3(a,e,t){const i={},s=a.configuration??[];for(const r of s)if(r.id==="customEvent"){const n=e.customEvents&&e.customEvents[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown custom event: ${r.value}`);i.eventId=n.id,i.eventData=n.values.map(o=>o.id)}else if(r.id==="variable"){const n=e.variables&&e.variables[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown variable: ${r.value}`);i.variableName=n.id}else if(r.id==="path"){const n=r.value;i.path=n}else i[r.id]=om(r,e,`/extensions/KHR_interactivity/nodes/${t}`);return i}function C3(a,e,t){const i=T3[e.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${a}: Unknown block type: ${e.type}`);const s=a.toString(),r=S3(e,t,s),n=e.metadata;return{className:i,config:r,uniqueId:s,metadata:n,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}function v3(a){const e={uniqueId:en(),_userVariables:{},_connectionValues:{}},t=[e],i=[];for(let r=0;r<a.nodes.length;r++){const n=a.nodes[r],o=C3(r,n,a);i.push(o)}for(let r=0;r<a.nodes.length;r++){const n=a.nodes[r],o=i[r],l=n.flows??[];for(const c of l){const u=c.id,d={uniqueId:en(),name:u,_connectionType:yr.Output,connectedPointIds:[]};o.signalOutputs.push(d);const f=c.node,_=c.socket,p=i[f];if(!p)throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Could not find node with id ${f} that connects its input with with node ${r}'s output ${u}`);let g=p.signalInputs.find(x=>x.name===_);g||(g={uniqueId:en(),name:_,_connectionType:yr.Input,connectedPointIds:[]},p.signalInputs.push(g)),g.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(g.uniqueId)}const h=n.values??[];for(const c of h){const u=c.id,d={uniqueId:en(),name:u,_connectionType:yr.Input,connectedPointIds:[]};if(o.dataInputs.push(d),c.value!==void 0){const f=om(c,a,`/extensions/KHR_interactivity/nodes/${r}`);e._connectionValues[d.uniqueId]=f}else if(c.node!==void 0&&c.socket!==void 0){const f=c.node,_=c.socket,p=i[f];if(!p)throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Could not find node with id ${f} that connects its output with node${r}'s input ${u}`);let g=p.dataOutputs.find(x=>x.name===_);g||(g={uniqueId:en(),name:_,_connectionType:yr.Output,connectedPointIds:[]},p.dataOutputs.push(g)),d.connectedPointIds.push(g.uniqueId),g.connectedPointIds.push(d.uniqueId)}else throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Invalid socket ${u} in node ${r}`)}}const s=a.variables??[];for(let r=0;r<s.length;r++){const n=s[r],o=n.id;e._userVariables[o]=om(n,a,`/extensions/KHR_interactivity/variables/${r}`)}return{allBlocks:i,executionContexts:t}}class b3 extends $C{constructor(e){super(e,y3)}}const A3={__array__:{__target__:!0,translation:{type:"Vector3",get:a=>a._babylonTransformNode.position,set:(a,e)=>{const t=e._babylonTransformNode;t.position=a},getObject(a){return a._babylonTransformNode}}}},y3={nodes:A3},lm="KHR_interactivity";class R3{constructor(e){this._loader=e,this.name=lm,this.enabled=this._loader.isExtensionUsed(lm),this._pathConverter=new b3(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){var r;if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=(r=this._loader.gltf.extensions)==null?void 0:r.KHR_interactivity,i=v3(t),s=new Dl({scene:e});jl.Parse(i,{coordinator:s,pathConverter:this._pathConverter}),s.start()}}Me.RegisterExtension(lm,a=>new R3(a));const KC="ExtrasAsMetadata";class I3{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{},s=i.gltf=i.gltf||{};s.extras=t.extras}}constructor(e){this.name=KC,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}Me.RegisterExtension(KC,a=>new I3(a));class pn{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split(`
`),n=/\s+/;let o,l=null;for(let h=0;h<r.length;h++){const c=r[h].trim();if(c.length===0||c.charAt(0)==="#")continue;const u=c.indexOf(" ");let d=u>=0?c.substring(0,u):c;d=d.toLowerCase();const f=u>=0?c.substring(u+1).trim():"";if(d==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new de(f,e),l._parentContainer=s,e._blockEntityCollection=!1;else if(d==="kd"&&l)o=f.split(n,3).map(parseFloat),l.diffuseColor=q.FromArray(o);else if(d==="ka"&&l)o=f.split(n,3).map(parseFloat),l.ambientColor=q.FromArray(o);else if(d==="ks"&&l)o=f.split(n,3).map(parseFloat),l.specularColor=q.FromArray(o);else if(d==="ke"&&l)o=f.split(n,3).map(parseFloat),l.emissiveColor=q.FromArray(o);else if(d==="ns"&&l)l.specularPower=parseFloat(f);else if(d==="d"&&l)l.alpha=parseFloat(f);else if(d==="map_ka"&&l)l.ambientTexture=pn._GetTexture(i,f,e);else if(d==="map_kd"&&l)l.diffuseTexture=pn._GetTexture(i,f,e);else if(d==="map_ks"&&l)l.specularTexture=pn._GetTexture(i,f,e);else if(d!=="map_ns")if(d==="map_bump"&&l){const _=f.split(n),p=_.indexOf("-bm");let g=null;p>=0&&(g=_[p+1],_.splice(p,2)),l.bumpTexture=pn._GetTexture(i,_.join(" "),e),l.bumpTexture&&g!==null&&(l.bumpTexture.level=parseFloat(g))}else d==="map_d"&&l&&(l.opacityTexture=pn._GetTexture(i,f,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if(e==="file:"){let r=t.lastIndexOf("\\");r===-1&&(r=t.lastIndexOf("/")),r>-1?s+=t.substr(r+1):s+=t}else s+=t;return new k(s,i,!1,pn.INVERT_TEXTURE_Y)}}pn.INVERT_TEXTURE_Y=!0;class Xt{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new xe(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let l;this._loadingOptions.optimizeWithUV?l=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):l=this._isInArray(this._tuplePosNorm,[e,i]),l===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),o!==void 0&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(l)}_unwrapData(){for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x*this._handednessSign,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x*this._handednessSign,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._loadingOptions.importVertexColors&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}_getTriangles(e,t){for(let i=t;i<e.length-1;i++)this._pushTriangle(e,i)}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){const s=parseInt(this._triangles[i])-1;this._setData(s,0,0,this._positions[s],Z.Zero(),m.Up(),this._loadingOptions.importVertexColors?this._colors[s]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){const s=this._triangles[i].split("/"),r=parseInt(s[0])-1,n=parseInt(s[1])-1;this._setData(r,n,0,this._positions[r],this._uvs[n],m.Up(),this._loadingOptions.importVertexColors?this._colors[r]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){const s=this._triangles[i].split("/"),r=parseInt(s[0])-1,n=parseInt(s[1])-1,o=parseInt(s[2])-1;this._setData(r,n,o,this._positions[r],this._uvs[n],this._normals[o])}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){const s=this._triangles[i].split("//"),r=parseInt(s[0])-1,n=parseInt(s[1])-1;this._setData(r,1,n,this._positions[r],Z.Zero(),this._normals[n],this._loadingOptions.importVertexColors?this._colors[r]:void 0)}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let i=0;i<this._triangles.length;i++){const s=this._triangles[i].split("/"),r=this._positions.length+parseInt(s[0]),n=this._uvs.length+parseInt(s[1]),o=this._normals.length+parseInt(s[2]);this._setData(r,n,o,this._positions[r],this._uvs[n],this._normals[o],this._loadingOptions.importVertexColors?this._colors[r]:void 0)}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(y.PositionKind),i=e.getVerticesData(y.NormalKind),s={};if(!t||!i)return;for(let n=0;n<t.length/3;n++){const o=t[n*3+0],l=t[n*3+1],h=t[n*3+2],c=o+"_"+l+"_"+h;let u=s[c];u||(u=[],s[c]=u),u.push(n)}const r=new m;for(const n in s){const o=s[n];if(o.length<2)continue;const l=o[0];for(let h=1;h<o.length;++h){const c=o[h];i[l*3+0]+=i[c*3+0],i[l*3+1]+=i[c*3+1],i[l*3+2]+=i[c*3+2]}r.copyFromFloats(i[l*3+0],i[l*3+1],i[l*3+2]),r.normalize();for(let h=0;h<o.length;++h){const c=o[h];i[c*3+0]=r.x,i[c*3+1]=r.y,i[c*3+2]=r.z}}e.setVerticesData(y.NormalKind,i)}parse(e,t,i,s,r){var o;this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(l,h)=>this._triangles.push(l[0],l[h],l[h+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(l,h)=>this._triangles.push(l[0],l[h+1],l[h]),this._handednessSign=1):(this._pushTriangle=(l,h)=>this._triangles.push(l[0],l[h],l[h+1]),this._handednessSign=-1);const n=t.split(`
`);for(let l=0;l<n.length;l++){const h=n[l].trim().replace(/\s\s/g," ");let c;if(!(h.length===0||h.charAt(0)==="#"))if(Xt.VertexPattern.test(h)){if(c=h.match(/[^ ]+/g),this._positions.push(new m(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3]))),this._loadingOptions.importVertexColors)if(c.length>=7){const u=parseFloat(c[4]),d=parseFloat(c[5]),f=parseFloat(c[6]);this._colors.push(new xe(u>1?u/255:u,d>1?d/255:d,f>1?f/255:f,c.length===7||c[7]===void 0?1:parseFloat(c[7])))}else this._colors.push(this._grayColor)}else if((c=Xt.NormalPattern.exec(h))!==null)this._normals.push(new m(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])));else if((c=Xt.UVPattern.exec(h))!==null)this._uvs.push(new Z(parseFloat(c[1])*this._loadingOptions.UVScaling.x,parseFloat(c[2])*this._loadingOptions.UVScaling.y));else if((c=Xt.FacePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "),1);else if((c=Xt.FacePattern4.exec(h))!==null)this._setDataForCurrentFaceWithPattern4(c[1].trim().split(" "),1);else if((c=Xt.FacePattern5.exec(h))!==null)this._setDataForCurrentFaceWithPattern5(c[1].trim().split(" "),1);else if((c=Xt.FacePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "),1);else if((c=Xt.FacePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "),1);else if((c=Xt.LinePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "),0);else if((c=Xt.LinePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "),0);else if((c=Xt.LinePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "),0);else if(Xt.GroupDescriptor.test(h)||Xt.ObjectDescriptor.test(h)){const u={name:h.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Xt.ObjectDescriptor.test(h)};this._addPreviousObjMesh(),this._meshesFromObj.push(u),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Xt.UseMtlDescriptor.test(h)){if(this._materialNameFromObj=h.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const u={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(u),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Xt.MtlLibGroupDescriptor.test(h)?r(h.substring(7).trim()):Xt.SmoothDescriptor.test(h)||O.Log("Unhandled expression at line : "+h)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let l=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const h of this._positions)this._unwrappedPositionsForBabylon.push(h.x,h.y,h.z);if(this._normals.length)for(const h of this._normals)this._unwrappedNormalsForBabylon.push(h.x,h.y,h.z);if(this._uvs.length)for(const h of this._uvs)this._unwrappedUVForBabylon.push(h.x,h.y);if(this._colors.length)for(const h of this._colors)this._unwrappedColorsForBabylon.push(h.r,h.g,h.b,h.a);this._materialNameFromObj||(l=new de(zi.RandomId(),i),l.pointsCloud=!0,this._materialNameFromObj=l.name,this._normals.length||(l.disableLighting=!0,l.emissiveColor=q.White()))}this._meshesFromObj.push({name:zi.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:l,isObject:!0})}for(let l=0;l<this._meshesFromObj.length;l++){if(e&&this._meshesFromObj[l].name){if(e instanceof Array){if(e.indexOf(this._meshesFromObj[l].name)===-1)continue}else if(this._meshesFromObj[l].name!==e)continue}this._handledMesh=this._meshesFromObj[l],i._blockEntityCollection=!!s;const h=new z(this._meshesFromObj[l].name,i);if(h._parentContainer=s,i._blockEntityCollection=!1,this._handledMesh._babylonMesh=h,!this._handledMesh.isObject){for(let u=l-1;u>=0;--u)if(this._meshesFromObj[u].isObject&&this._meshesFromObj[u]._babylonMesh){h.parent=this._meshesFromObj[u]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[l].materialName),((o=this._handledMesh.positions)==null?void 0:o.length)===0){this._babylonMeshesArray.push(h);continue}const c=new le;if(c.uvs=this._handledMesh.uvs,c.indices=this._handledMesh.indices,c.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const u=new Array;le.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,u),c.normals=u}else c.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(c.colors=this._handledMesh.colors),c.applyToMesh(h),this._loadingOptions.invertY&&(h.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(h),this._babylonMeshesArray.push(h),this._handledMesh.directMaterial&&(h.material=this._handledMesh.directMaterial)}}}Xt.ObjectDescriptor=/^o/;Xt.GroupDescriptor=/^g/;Xt.MtlLibGroupDescriptor=/^mtllib /;Xt.UseMtlDescriptor=/^usemtl /;Xt.SmoothDescriptor=/^s /;Xt.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Xt.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Xt.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Xt.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Xt.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Xt.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Xt.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Xt.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Xt.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Xt.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Xt.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class Gi{static get INVERT_TEXTURE_Y(){return pn.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){pn.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||Gi._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:Gi.COMPUTE_NORMALS,optimizeNormals:Gi.OPTIMIZE_NORMALS,importVertexColors:Gi.IMPORT_VERTEX_COLORS,invertY:Gi.INVERT_Y,invertTextureY:Gi.INVERT_TEXTURE_Y,UVScaling:Gi.UV_SCALING,materialLoadingFailsSilently:Gi.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Gi.OPTIMIZE_WITH_UV,skipMaterials:Gi.SKIP_MATERIALS,useLegacyBehavior:Gi.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;X.LoadFile(r,i,void 0,void 0,!1,(n,o)=>{s(r,o)})}createPlugin(){return new Gi(Gi._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then(r=>({meshes:r,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const s=new Df(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then(r=>(r.meshes.forEach(n=>s.meshes.push(n)),r.meshes.forEach(n=>{const o=n.material;o&&s.materials.indexOf(o)==-1&&(s.materials.push(o),o.getActiveTextures().forEach(h=>{s.textures.indexOf(h)==-1&&s.textures.push(h)}))}),this._assetContainer=null,s)).catch(r=>{throw this._assetContainer=null,r})}_parseSolid(e,t,i,s){let r="";const n=new pn,o=[],l=[];new Xt(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{r=u});const c=[];return r!==""&&!this._loadingOptions.skipMaterials&&c.push(new Promise((u,d)=>{this._loadMTL(r,s,f=>{try{n.parseMTL(t,f,s,this._assetContainer);for(let _=0;_<n.materials.length;_++){let p=0;const g=[];let x;for(;(x=o.indexOf(n.materials[_].name,p))>-1;)g.push(x),p=x+1;if(x===-1&&g.length===0)n.materials[_].dispose();else for(let T=0;T<g.length;T++){const S=l[g[T]],C=n.materials[_];S.material=C,S.getTotalIndices()||(C.pointsCloud=!0)}}u()}catch(_){X.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?u():d(_)}},(f,_)=>{X.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?u():d(_)})})),Promise.all(c).then(()=>l)}}Gi.OPTIMIZE_WITH_UV=!0;Gi.INVERT_Y=!1;Gi.IMPORT_VERTEX_COLORS=!1;Gi.COMPUTE_NORMALS=!1;Gi.OPTIMIZE_NORMALS=!1;Gi.UV_SCALING=new Z(1,1);Gi.SKIP_MATERIALS=!1;Gi.MATERIAL_LOADING_FAILS_SILENTLY=!0;Gi.USE_LEGACY_BEHAVIOR=!1;je&&je.RegisterPlugin(new Gi);class Po{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if(typeof i!="string"){if(this._isBinary(i)){const o=new z("stlmesh",t);return this._parseBinary(o,i),r&&r.push(o),!0}i=new TextDecoder().decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let o=n[1];const l=n[3];if(l&&o!=l)return X.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o){if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue}o=o||"stlmesh";const h=new z(o,t);this._parseASCII(h,n[2]),r&&r.push(h)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new Df(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;const i=32/8*3+32/8*3*3+16/8,s=t.getUint32(80,!0);if(80+32/8+s*i===t.byteLength)return!0;const r=[115,111,108,105,100];for(let n=0;n<5;n++)if(t.getUint8(n)!==r[n])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0),r=84,n=12*4+2;let o=0;const l=new Float32Array(s*3*3),h=new Float32Array(s*3*3),c=new Uint32Array(s*3);let u=0;for(let d=0;d<s;d++){const f=r+d*n,_=i.getFloat32(f,!0),p=i.getFloat32(f+4,!0),g=i.getFloat32(f+8,!0);for(let x=1;x<=3;x++){const T=f+x*12;l[o]=i.getFloat32(T,!0),h[o]=_,Po.DO_NOT_ALTER_FILE_COORDINATES?(l[o+1]=i.getFloat32(T+4,!0),l[o+2]=i.getFloat32(T+8,!0),h[o+1]=p,h[o+2]=g):(l[o+2]=i.getFloat32(T+4,!0),l[o+1]=i.getFloat32(T+8,!0),h[o+2]=p,h[o+1]=g),o+=3}Po.DO_NOT_ALTER_FILE_COORDINATES?(c[u]=u,c[u+1]=u+2,c[u+2]=u+1,u+=3):(c[u]=u++,c[u]=u++,c[u]=u++)}e.setVerticesData(y.PositionKind,l),e.setVerticesData(y.NormalKind,h),e.setIndices(c),e.computeWorldMatrix(!0)}_parseASCII(e,t){const i=[],s=[],r=[];let n=0,o;for(;o=this.facetsPattern.exec(t);){const l=o[1],h=this.normalPattern.exec(l);if(this.normalPattern.lastIndex=0,!h)continue;const c=[Number(h[1]),Number(h[5]),Number(h[3])];let u;for(;u=this.vertexPattern.exec(l);)Po.DO_NOT_ALTER_FILE_COORDINATES?(i.push(Number(u[1]),Number(u[3]),Number(u[5])),s.push(c[0],c[2],c[1])):(i.push(Number(u[1]),Number(u[5]),Number(u[3])),s.push(c[0],c[1],c[2]));Po.DO_NOT_ALTER_FILE_COORDINATES?(r.push(n,n+2,n+1),n+=3):r.push(n++,n++,n++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(y.PositionKind,i),e.setVerticesData(y.NormalKind,s),e.setIndices(r),e.computeWorldMatrix(!0)}}Po.DO_NOT_ALTER_FILE_COORDINATES=!1;je&&je.RegisterPlugin(new Po);class kg{constructor(){this.name="splat",this.extensions={".splat":{isBinary:!0},".ply":{isBinary:!0}}}createPlugin(){return new kg}canDirectLoad(){return!1}async importMeshAsync(e,t,i,s,r,n){const o=new wo("GaussianSplatting",null,t);return await o.loadFileAsync(s+(n??"")),{meshes:[o],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}}loadAsync(e,t,i){return new wo("GaussianSplatting",null,e).loadDataAsync(wo.ConvertPLYToSplat(t))}loadAssetContainerAsync(e,t,i){throw new Error("loadAssetContainerAsync not implemented for Gaussian Splatting loading")}}je&&je.RegisterPlugin(new kg);let $d=null,rE=null,Q_=!1,jC=6,nE=500;async function P3(){const e=await(await fetch("/api/config")).json();return{maxPoints:e.max_points||1e4,pointSize:e.point_size||6,refreshInterval:e.refresh_interval||500,disableTransforms:e.disable_transforms||!1}}async function M3(){return await(await fetch("/api/list_tensors")).json()}async function D3(a,e="",t=1e4){const i=`/api/get_tensor?tensor_key=${encodeURIComponent(a)}&code=${encodeURIComponent(e)}`,r=await(await fetch(i)).json();return r.data=w3(r.data,r.dims,t),r}function O3(a){const e=Math.max(0,Math.min(1,a)),t=e,i=(1-e)*.8,s=e*.9+(1-e)*1;return new q(t,i,s)}function N3(){$d&&($d.dispose(),$d=null)}xt.ShadersStore.customVertexShader=`
  precision highp float;
  attribute vec3 position;
  attribute vec4 color;
  uniform mat4 worldViewProjection;
  uniform float pointSize;
  varying vec4 vColor;

  void main() {
    gl_Position = worldViewProjection * vec4(position, 1.0);
    gl_PointSize = pointSize;
    vColor = color;
  }
`;xt.ShadersStore.customFragmentShader=`
  precision highp float;
  varying vec4 vColor;

  void main() {
    gl_FragColor = vColor;
  }
`;function F3(a,e,t){const i=a.dims,s=a.data,r=.7,n=[];if(i===1)s.forEach((h,c)=>{n.push({pos:new m(t.x+c*r,t.y,t.z),val:h})});else if(i===2)s.forEach((h,c)=>{h.forEach((u,d)=>{n.push({pos:new m(t.x+d*r,t.y,t.z+c*r),val:u})})});else if(i===3)s.forEach((h,c)=>{h.forEach((u,d)=>{u.forEach((f,_)=>{n.push({pos:new m(t.x+_*r,t.y+d*r,t.z+c*r),val:f})})})});else{console.log(`Unsupported tensor dimension: ${i}`);return}console.log("Rendering",n.length,"points");const o=n.reduce((h,c)=>h.add(c.pos),new m(0,0,0)).scale(1/n.length);e.activeCamera.setTarget(o);const l=new tL("pcs",1,e);l.addPoints(n.length,(h,c)=>{h.position=n[c].pos;const u=O3(n[c].val);h.color=new q(u.r,u.g,u.b)}),l.buildMeshAsync().then(h=>{$d=h;const c=new Qs("pointShader",e,{vertex:"custom",fragment:"custom"},{attributes:["position","color"],uniforms:["worldViewProjection","pointSize"]});c.setFloat("pointSize",jC),c.backFaceCulling=!1,c.pointsCloud=!0,c.disableLighting=!0,c.emissiveColor=new q(1,1,1),h.material=c,h.alwaysSelectAsActiveMesh=!0})}function Z_(){const a=document.getElementById("downsampleMessage");a.style.display="block",setTimeout(()=>{a.style.display="none"},5e3)}function w3(a,e,t){let i=a;return e===1?a.length>t&&(i=L3(a,t),Z_()):e===2?a.reduce((r,n)=>r+n.length,0)>t&&(i=B3(a,t),Z_()):e===3?a.reduce((r,n)=>r+n.reduce((o,l)=>o+l.length,0),0)>t&&(i=U3(a,t),Z_()):console.warn("Unsupported dims for downsampling:",e),i}function L3(a,e){const t=Math.ceil(a.length/e);return a.filter((i,s)=>s%t===0)}function B3(a,e){const t=[];a.forEach(o=>t.push(...o));const i=Math.ceil(t.length/e),s=t.filter((o,l)=>l%i===0),r=Math.ceil(Math.sqrt(s.length)),n=[];for(let o=0;o<s.length;o+=r)n.push(s.slice(o,o+r));return n}function U3(a,e){const t=[];a.forEach(o=>o.forEach(l=>t.push(...l)));const i=Math.ceil(t.length/e),s=t.filter((o,l)=>l%i===0),r=Math.ceil(Math.cbrt(s.length)),n=[];for(let o=0;o<r;o++){const l=[];for(let h=0;h<r;h++){const c=[];for(let u=0;u<r;u++){const d=o*r*r+h*r+u;d<s.length&&c.push(s[d])}c.length>0&&l.push(c)}l.length>0&&n.push(l)}return n}document.addEventListener("DOMContentLoaded",async()=>{const{maxPoints:a,pointSize:e,refreshInterval:t,disableTransforms:i}=await P3();console.log("disableTransforms",i),jC=e,nE=t,i&&(document.getElementById("pythonCodeInput").hidden=!0);const s=document.getElementById("renderCanvas"),r=new H(s,!0),n=new Ee(r);n.clearColor=new q(0,0,0);const o=new $t("camera",Math.PI/4,Math.PI/4,100,m.Zero(),n);o.minZ=.01,o.maxZ=1e4,o.attachControl(s,!0),o.wheelDeltaPercentage=.01;const l=document.getElementById("tensorSelector"),h=document.getElementById("pythonCodeInput"),c=document.getElementById("tensorInfo"),u=await M3(),d={};l.innerHTML='<option value="">Select a tensor</option>',u.available_tensors.forEach(f=>{const _=document.createElement("option");_.value=f.key,_.textContent=f.name||f.key,l.appendChild(_),d[f.key]={name:f.name||f.key,shape:f.shape||"Unknown"}}),l.addEventListener("change",async f=>{const _=f.target.value;if(!_)return;rE=_;const p=d[_];c.textContent=`Tensor: ${p.name} | Shape: ${p.shape}`,t&&clearInterval(t);const g=async()=>{if(Q_)return;Q_=!0;const x=h.value;try{const T=await D3(rE,x,a);N3(),F3(T,n,new m(0,0,0))}catch(T){console.error("Failed to fetch tensor:",T)}Q_=!1};await g(),t=setInterval(g,nE)}),r.runRenderLoop(()=>n.render()),window.addEventListener("resize",()=>r.resize())});
