diff --git a/docs/assets/index-BqF0neoc.js b/docs/assets/index-v7LhaIZJ.js similarity index 93% rename from docs/assets/index-BqF0neoc.js rename to docs/assets/index-v7LhaIZJ.js index cfca9f1..94fc4be 100644 --- a/docs/assets/index-BqF0neoc.js +++ b/docs/assets/index-v7LhaIZJ.js @@ -1,34 +1,34 @@ -var MN=Object.defineProperty;var DN=(o,e,t)=>e in o?MN(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Ut=(o,e,t)=>(DN(o,typeof e!="symbol"?e+"":e,t),t);(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)}})();var Yu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ON(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}function i_(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var XC={exports:{}};(function(o,e){(function(t){o.exports=t()})(function(){return function t(i,s,r){function n(h,c){if(!s[h]){if(!i[h]){var u=typeof i_=="function"&&i_;if(!c&&u)return u(h,!0);if(a)return a(h,!0);throw new Error("Cannot find module '"+h+"'")}var d=s[h]={exports:{}};i[h][0].call(d.exports,function(f){var p=i[h][1][f];return n(p||f)},d,d.exports,t,i,s,r)}return s[h].exports}for(var a=typeof i_=="function"&&i_,l=0;l (http://steffe.se)",keywords:["cannon.js","cannon","physics","engine","3d"],main:"./build/cannon.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/cannon.js.git"},bugs:{url:"https://github.com/schteppe/cannon.js/issues"},licenses:[{type:"MIT"}],devDependencies:{jshint:"latest","uglify-js":"latest",nodeunit:"^0.9.0",grunt:"~0.4.0","grunt-contrib-jshint":"~0.1.1","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-concat":"~0.1.3","grunt-contrib-uglify":"^0.5.1","grunt-browserify":"^2.1.4","grunt-contrib-yuidoc":"^0.5.2",browserify:"*"},dependencies:{}}},{}],2:[function(t,i,s){i.exports={version:t("../package.json").version,AABB:t("./collision/AABB"),ArrayCollisionMatrix:t("./collision/ArrayCollisionMatrix"),Body:t("./objects/Body"),Box:t("./shapes/Box"),Broadphase:t("./collision/Broadphase"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),Narrowphase:t("./world/Narrowphase"),ConeTwistConstraint:t("./constraints/ConeTwistConstraint"),ContactMaterial:t("./material/ContactMaterial"),ConvexPolyhedron:t("./shapes/ConvexPolyhedron"),Cylinder:t("./shapes/Cylinder"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventTarget:t("./utils/EventTarget"),FrictionEquation:t("./equations/FrictionEquation"),GSSolver:t("./solver/GSSolver"),GridBroadphase:t("./collision/GridBroadphase"),Heightfield:t("./shapes/Heightfield"),HingeConstraint:t("./constraints/HingeConstraint"),LockConstraint:t("./constraints/LockConstraint"),Mat3:t("./math/Mat3"),Material:t("./material/Material"),NaiveBroadphase:t("./collision/NaiveBroadphase"),ObjectCollisionMatrix:t("./collision/ObjectCollisionMatrix"),Pool:t("./utils/Pool"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),PointToPointConstraint:t("./constraints/PointToPointConstraint"),Quaternion:t("./math/Quaternion"),Ray:t("./collision/Ray"),RaycastVehicle:t("./objects/RaycastVehicle"),RaycastResult:t("./collision/RaycastResult"),RigidVehicle:t("./objects/RigidVehicle"),RotationalEquation:t("./equations/RotationalEquation"),RotationalMotorEquation:t("./equations/RotationalMotorEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),SPHSystem:t("./objects/SPHSystem"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Sphere:t("./shapes/Sphere"),SplitSolver:t("./solver/SplitSolver"),Spring:t("./objects/Spring"),Trimesh:t("./shapes/Trimesh"),Vec3:t("./math/Vec3"),Vec3Pool:t("./utils/Vec3Pool"),World:t("./world/World")}},{"../package.json":1,"./collision/AABB":3,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/ConeTwistConstraint":12,"./constraints/Constraint":13,"./constraints/DistanceConstraint":14,"./constraints/HingeConstraint":15,"./constraints/LockConstraint":16,"./constraints/PointToPointConstraint":17,"./equations/ContactEquation":19,"./equations/Equation":20,"./equations/FrictionEquation":21,"./equations/RotationalEquation":22,"./equations/RotationalMotorEquation":23,"./material/ContactMaterial":24,"./material/Material":25,"./math/Mat3":27,"./math/Quaternion":28,"./math/Vec3":30,"./objects/Body":31,"./objects/RaycastVehicle":32,"./objects/RigidVehicle":33,"./objects/SPHSystem":34,"./objects/Spring":35,"./shapes/Box":37,"./shapes/ConvexPolyhedron":38,"./shapes/Cylinder":39,"./shapes/Heightfield":40,"./shapes/Particle":41,"./shapes/Plane":42,"./shapes/Shape":43,"./shapes/Sphere":44,"./shapes/Trimesh":45,"./solver/GSSolver":46,"./solver/Solver":47,"./solver/SplitSolver":48,"./utils/EventTarget":49,"./utils/Pool":51,"./utils/Vec3Pool":54,"./world/Narrowphase":55,"./world/World":56}],3:[function(t,i,s){var r=t("../math/Vec3");t("../utils/Utils"),i.exports=n;function n(h){h=h||{},this.lowerBound=new r,h.lowerBound&&this.lowerBound.copy(h.lowerBound),this.upperBound=new r,h.upperBound&&this.upperBound.copy(h.upperBound)}var a=new r;n.prototype.setFromPoints=function(h,c,u,d){var f=this.lowerBound,p=this.upperBound,_=u;f.copy(h[0]),_&&_.vmult(f,f),p.copy(f);for(var g=1;gp.x&&(p.x=v.x),v.xp.y&&(p.y=v.y),v.yp.z&&(p.z=v.z),v.zc&&(this.lowerBound.x=c);var u=h.upperBound.x;this.upperBound.xc&&(this.lowerBound.y=c);var u=h.upperBound.y;this.upperBound.yc&&(this.lowerBound.z=c);var u=h.upperBound.z;this.upperBound.z=f.x&&c.y<=d.y&&u.y>=f.y&&c.z<=d.z&&u.z>=f.z},n.prototype.getCorners=function(h,c,u,d,f,p,_,g){var v=this.lowerBound,E=this.upperBound;h.copy(v),c.set(E.x,v.y,v.z),u.set(E.x,E.y,v.z),d.set(v.x,E.y,E.z),f.set(E.x,v.y,v.z),p.set(v.x,E.y,v.z),_.set(v.x,v.y,E.z),g.copy(E)};var l=[new r,new r,new r,new r,new r,new r,new r,new r];n.prototype.toLocalFrame=function(h,c){var u=l,d=u[0],f=u[1],p=u[2],_=u[3],g=u[4],v=u[5],E=u[6],C=u[7];this.getCorners(d,f,p,_,g,v,E,C);for(var S=0;S!==8;S++){var b=u[S];h.pointToLocal(b,b)}return c.setFromPoints(u)},n.prototype.toWorldFrame=function(h,c){var u=l,d=u[0],f=u[1],p=u[2],_=u[3],g=u[4],v=u[5],E=u[6],C=u[7];this.getCorners(d,f,p,_,g,v,E,C);for(var S=0;S!==8;S++){var b=u[S];h.pointToWorld(b,b)}return c.setFromPoints(u)}},{"../math/Vec3":30,"../utils/Utils":53}],4:[function(t,i,s){i.exports=r;function r(){this.matrix=[]}r.prototype.get=function(n,a){if(n=n.index,a=a.index,a>n){var l=a;a=n,n=l}return this.matrix[(n*(n+1)>>1)+a-1]},r.prototype.set=function(n,a,l){if(n=n.index,a=a.index,a>n){var h=a;a=n,n=h}this.matrix[(n*(n+1)>>1)+a-1]=l?1:0},r.prototype.reset=function(){for(var n=0,a=this.matrix.length;n!==a;n++)this.matrix[n]=0},r.prototype.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1}},{}],5:[function(t,i,s){var r=t("../objects/Body"),n=t("../math/Vec3"),a=t("../math/Quaternion");t("../shapes/Shape"),t("../shapes/Plane"),i.exports=l;function l(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}l.prototype.collisionPairs=function(_,g,v){throw new Error("collisionPairs not implemented for this BroadPhase class!")};var h=r.STATIC|r.KINEMATIC;l.prototype.needBroadphaseCollision=function(_,g){return!(!(_.collisionFilterGroup&g.collisionFilterMask)||!(g.collisionFilterGroup&_.collisionFilterMask)||(_.type&h||_.sleepState===r.SLEEPING)&&(g.type&h||g.sleepState===r.SLEEPING))},l.prototype.intersectionTest=function(_,g,v,E){this.useBoundingBoxes?this.doBoundingBoxBroadphase(_,g,v,E):this.doBoundingSphereBroadphase(_,g,v,E)};var c=new n;new n,new a,new n,l.prototype.doBoundingSphereBroadphase=function(_,g,v,E){var C=c;g.position.vsub(_.position,C);var S=Math.pow(_.boundingRadius+g.boundingRadius,2),b=C.norm2();bv.norm2()},l.prototype.aabbQuery=function(_,g,v){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(t,i,s){i.exports=l;var r=t("./Broadphase"),n=t("../math/Vec3"),a=t("../shapes/Shape");function l(c,u,d,f,p){r.apply(this),this.nx=d||10,this.ny=f||10,this.nz=p||10,this.aabbMin=c||new n(100,100,100),this.aabbMax=u||new n(-100,-100,-100);var _=this.nx*this.ny*this.nz;if(_<=0)throw"GridBroadphase: Each dimension's n must be >0";this.bins=[],this.binLengths=[],this.bins.length=_,this.binLengths.length=_;for(var g=0;g<_;g++)this.bins[g]=[],this.binLengths[g]=0}l.prototype=new r,l.prototype.constructor=l;var h=new n;new n,l.prototype.collisionPairs=function(c,u,d){var f=c.numObjects(),p=c.bodies,q=this.aabbMax,_e=this.aabbMin,_=this.nx,g=this.ny,v=this.nz,E=g*v,C=v,S=1,b=q.x,R=q.y,I=q.z,N=_e.x,O=_e.y,L=_e.z,B=_/(b-N),V=g/(R-O),Z=v/(I-L),ue=(b-N)/_,oe=(R-O)/g,me=(I-L)/v,le=Math.sqrt(ue*ue+oe*oe+me*me)*.5,ae=a.types,ce=ae.SPHERE,ie=ae.PLANE;ae.BOX,ae.COMPOUND,ae.CONVEXPOLYHEDRON;for(var w=this.bins,H=this.binLengths,X=this.bins.length,te=0;te!==X;te++)H[te]=0;var Q=Math.ceil,_e=Math.min,q=Math.max;function de(gn,Yn,Dn,jr,Wr,$n,On){var vn=(gn-N)*B|0,Nn=(Yn-O)*V|0,hn=(Dn-L)*Z|0,xn=Q((jr-N)*B),Qr=Q((Wr-O)*V),ur=Q(($n-L)*Z);vn<0?vn=0:vn>=_&&(vn=_-1),Nn<0?Nn=0:Nn>=g&&(Nn=g-1),hn<0?hn=0:hn>=v&&(hn=v-1),xn<0?xn=0:xn>=_&&(xn=_-1),Qr<0?Qr=0:Qr>=g&&(Qr=g-1),ur<0?ur=0:ur>=v&&(ur=v-1),vn*=E,Nn*=C,hn*=S,xn*=E,Qr*=C,ur*=S;for(var da=vn;da<=xn;da+=E)for(var wn=Nn;wn<=Qr;wn+=C)for(var fa=hn;fa<=ur;fa+=S){var ao=da+wn+fa;w[ao][H[ao]++]=On}}for(var te=0;te!==f;te++){var ge=p[te],ve=ge.shape;switch(ve.type){case ce:var be=ge.position.x,Le=ge.position.y,Ye=ge.position.z,He=ve.radius;de(be-He,Le-He,Ye-He,be+He,Le+He,Ye+He,ge);break;case ie:ve.worldNormalNeedsUpdate&&ve.computeWorldNormal(ge.quaternion);var Be=ve.worldNormal,Ge=N+ue*.5-ge.position.x,Lt=O+oe*.5-ge.position.y,Mt=L+me*.5-ge.position.z,Vi=h;Vi.set(Ge,Lt,Mt);for(var at=0,ei=0;at!==_;at++,ei+=E,Vi.y=Lt,Vi.x+=ue)for(var di=0,ci=0;di!==g;di++,ci+=C,Vi.z=Mt,Vi.y+=oe)for(var Yi=0,Zt=0;Yi!==v;Yi++,Zt+=S,Vi.z+=me)if(Vi.dot(Be)1)for(var gs=w[te],at=0;at!==ti;at++)for(var ge=gs[at],di=0;di!==at;di++){var br=gs[di];this.needBroadphaseCollision(ge,br)&&this.intersectionTest(ge,br,u,d)}}this.makePairsUnique(u,d)}},{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(t,i,s){i.exports=a;var r=t("./Broadphase"),n=t("./AABB");function a(){r.apply(this)}a.prototype=new r,a.prototype.constructor=a,a.prototype.collisionPairs=function(l,h,c){var u=l.bodies,d=u.length,f,p,_,g;for(f=0;f!==d;f++)for(p=0;p!==f;p++)_=u[f],g=u[p],this.needBroadphaseCollision(_,g)&&this.intersectionTest(_,g,h,c)},new n,a.prototype.aabbQuery=function(l,h,c){c=c||[];for(var u=0;un){var l=a;a=n,n=l}return n+"-"+a in this.matrix},r.prototype.set=function(n,a,l){if(n=n.id,a=a.id,a>n){var h=a;a=n,n=h}l?this.matrix[n+"-"+a]=!0:delete this.matrix[n+"-"+a]},r.prototype.reset=function(){this.matrix={}},r.prototype.setNumObjects=function(n){}},{}],9:[function(t,i,s){i.exports=u;var r=t("../math/Vec3"),n=t("../math/Quaternion"),a=t("../math/Transform");t("../shapes/ConvexPolyhedron"),t("../shapes/Box");var l=t("../collision/RaycastResult"),h=t("../shapes/Shape"),c=t("../collision/AABB");function u(X,te){this.from=X?X.clone():new r,this.to=te?te.clone():new r,this._direction=new r,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=u.ANY,this.result=new l,this.hasHit=!1,this.callback=function(Q){}}u.prototype.constructor=u,u.CLOSEST=1,u.ANY=2,u.ALL=4;var d=new c,f=[];u.prototype.intersectWorld=function(X,te){return this.mode=te.mode||u.ANY,this.result=te.result||new l,this.skipBackfaces=!!te.skipBackfaces,this.collisionFilterMask=typeof te.collisionFilterMask<"u"?te.collisionFilterMask:-1,this.collisionFilterGroup=typeof te.collisionFilterGroup<"u"?te.collisionFilterGroup:-1,te.from&&this.from.copy(te.from),te.to&&this.to.copy(te.to),this.callback=te.callback||function(){},this.hasHit=!1,this.result.reset(),this._updateDirection(),this.getAABB(d),f.length=0,X.broadphase.aabbQuery(X,d,f),this.intersectBodies(f),this.hasHit};var p=new r,_=new r;u.pointInTriangle=g;function g(X,te,Q,_e){_e.vsub(te,ie),Q.vsub(te,p),X.vsub(te,_);var q=ie.dot(ie),de=ie.dot(p),ge=ie.dot(_),ve=p.dot(p),be=p.dot(_),Le,Ye;return(Le=ve*ge-de*be)>=0&&(Ye=q*be-de*ge)>=0&&Le+YeX.boundingSphereRadius)){var ge=this[X.type];ge&&ge.call(this,X,te,Q,_e)}},new r,new r;var C=new r,S=new r,b=new r,R=new r;new r,new l,u.prototype.intersectBox=function(X,te,Q,_e){return this.intersectConvex(X.convexPolyhedronRepresentation,te,Q,_e)},u.prototype[h.types.BOX]=u.prototype.intersectBox,u.prototype.intersectPlane=function(X,te,Q,_e){var q=this.from,de=this.to,ge=this._direction,ve=new r(0,0,1);te.vmult(ve,ve);var be=new r;q.vsub(Q,be);var Le=be.dot(ve);de.vsub(Q,be);var Ye=be.dot(ve);if(!(Le*Ye>0)&&!(q.distanceTo(de)Le)&&(Le=ge[0]),(be===null||ge[1]Ye)&&(Ye=ge[1])),ve!==null){var Be=[];X.getRectMinMax(ve,be,Le,Ye,Be),Be[0],Be[1];for(var Ge=ve;Ge<=Le;Ge++)for(var Lt=be;Lt<=Ye;Lt++){if(this.result._shouldStop||(X.getConvexTrianglePillar(Ge,Lt,!1),a.pointToWorldFrame(Q,te,X.pillarOffset,q),this.intersectConvex(X.pillarConvex,te,q,_e,I),this.result._shouldStop))return;X.getConvexTrianglePillar(Ge,Lt,!0),a.pointToWorldFrame(Q,te,X.pillarOffset,q),this.intersectConvex(X.pillarConvex,te,q,_e,I)}}},u.prototype[h.types.HEIGHTFIELD]=u.prototype.intersectHeightfield;var N=new r,O=new r;u.prototype.intersectSphere=function(X,te,Q,_e){var q=this.from,de=this.to,ge=X.radius,ve=Math.pow(de.x-q.x,2)+Math.pow(de.y-q.y,2)+Math.pow(de.z-q.z,2),be=2*((de.x-q.x)*(q.x-Q.x)+(de.y-q.y)*(q.y-Q.y)+(de.z-q.z)*(q.z-Q.z)),Le=Math.pow(q.x-Q.x,2)+Math.pow(q.y-Q.y,2)+Math.pow(q.z-Q.z,2)-Math.pow(ge,2),Ye=Math.pow(be,2)-4*ve*Le,He=N,Be=O;if(!(Ye<0))if(Ye===0)q.lerp(de,Ye,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1);else{var Ge=(-be-Math.sqrt(Ye))/(2*ve),Lt=(-be+Math.sqrt(Ye))/(2*ve);if(Ge>=0&&Ge<=1&&(q.lerp(de,Ge,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1)),this.result._shouldStop)return;Lt>=0&&Lt<=1&&(q.lerp(de,Lt,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1))}},u.prototype[h.types.SPHERE]=u.prototype.intersectSphere;var L=new r;new r,new r;var B=new r;u.prototype.intersectConvex=function(te,Q,_e,q,de){for(var ge=L,ve=B,be=de&&de.faceList||null,Le=te.faces,Ye=te.vertices,He=te.faceNormals,Be=this._direction,Ge=this.from,Lt=this.to,Mt=Ge.distanceTo(Lt),Vi=be?be.length:Le.length,at=this.result,ei=0;!at._shouldStop&&eiMt||this.reportIntersection(ge,C,te,q,di)}}}}},u.prototype[h.types.CONVEXPOLYHEDRON]=u.prototype.intersectConvex;var V=new r,Z=new r,ue=new r,oe=new r,me=new r,le=new r;new c;var ae=[],ce=new a;u.prototype.intersectTrimesh=function(te,Q,_e,q,de){var ge=V,ve=ae,be=ce,Le=B,Ye=Z,He=ue,Be=oe,Ge=le,Lt=me;de&&de.faceList;var Mt=te.indices;te.vertices,te.faceNormals;var Vi=this.from,at=this.to,ei=this._direction;be.position.copy(_e),be.quaternion.copy(Q),a.vectorToLocalFrame(_e,Q,ei,Ye),a.pointToLocalFrame(_e,Q,Vi,He),a.pointToLocalFrame(_e,Q,at,Be);var di=He.distanceSquared(Be);te.tree.rayQuery(this,be,ve);for(var ci=0,Yi=ve.length;!this.result._shouldStop&&ci!==Yi;ci++){var Zt=ve[ci];te.getNormal(Zt,ge),te.getVertex(Mt[Zt*3],S),S.vsub(He,Le);var zi=Ye.dot(ge),ti=ge.dot(Le)/zi;if(!(ti<0)){Ye.scale(ti,C),C.vadd(He,C),te.getVertex(Mt[Zt*3+1],b),te.getVertex(Mt[Zt*3+2],R);var gs=C.distanceSquared(He);!(g(C,b,S,R)||g(C,S,b,R))||gs>di||(a.vectorToWorldFrame(Q,ge,Lt),a.pointToWorldFrame(_e,Q,C,Ge),this.reportIntersection(Lt,Ge,te,q,Zt))}}ve.length=0},u.prototype[h.types.TRIMESH]=u.prototype.intersectTrimesh,u.prototype.reportIntersection=function(X,te,Q,_e,q){var de=this.from,ge=this.to,ve=de.distanceTo(te),be=this.result;if(!(this.skipBackfaces&&X.dot(this._direction)>0))switch(be.hitFaceIndex=typeof q<"u"?q:-1,this.mode){case u.ALL:this.hasHit=!0,be.set(de,ge,X,te,Q,_e,ve),be.hasHit=!0,this.callback(be);break;case u.CLOSEST:(ve=0&&!(a[u].aabb.lowerBound.x<=c.aabb.lowerBound.x);u--)a[u+1]=a[u];a[u+1]=c}return a},n.insertionSortY=function(a){for(var l=1,h=a.length;l=0&&!(a[u].aabb.lowerBound.y<=c.aabb.lowerBound.y);u--)a[u+1]=a[u];a[u+1]=c}return a},n.insertionSortZ=function(a){for(var l=1,h=a.length;l=0&&!(a[u].aabb.lowerBound.z<=c.aabb.lowerBound.z);u--)a[u+1]=a[u];a[u+1]=c}return a},n.prototype.collisionPairs=function(a,l,h){var c=this.axisList,u=c.length,d=this.axisIndex,f,p;for(this.dirty&&(this.sortList(),this.dirty=!1),f=0;f!==u;f++){var _=c[f];for(p=f+1;pR?b>I?this.axisIndex=0:this.axisIndex=2:R>I?this.axisIndex=1:this.axisIndex=2},n.prototype.aabbQuery=function(a,l,h){h=h||[],this.dirty&&(this.sortList(),this.dirty=!1);var c=this.axisIndex,u="x";c===1&&(u="y"),c===2&&(u="z");var d=this.axisList;l.lowerBound[u],l.upperBound[u];for(var f=0;f"u"&&(c=l.position.distanceTo(h.position)),typeof u>"u"&&(u=1e6),this.distance=c;var d=this.distanceEquation=new n(l,h);this.equations.push(d),d.minForce=-u,d.maxForce=u}a.prototype=new r,a.prototype.update=function(){var l=this.bodyA,h=this.bodyB,c=this.distanceEquation,u=this.distance*.5,d=c.ni;h.position.vsub(l.position,d),d.normalize(),d.mult(u,c.ri),d.mult(-u,c.rj)}},{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(t,i,s){i.exports=h,t("./Constraint");var r=t("./PointToPointConstraint"),n=t("../equations/RotationalEquation"),a=t("../equations/RotationalMotorEquation");t("../equations/ContactEquation");var l=t("../math/Vec3");function h(d,f,p){p=p||{};var _=typeof p.maxForce<"u"?p.maxForce:1e6,g=p.pivotA?p.pivotA.clone():new l,v=p.pivotB?p.pivotB.clone():new l;r.call(this,d,g,f,v,_);var E=this.axisA=p.axisA?p.axisA.clone():new l(1,0,0);E.normalize();var C=this.axisB=p.axisB?p.axisB.clone():new l(1,0,0);C.normalize();var S=this.rotationalEquation1=new n(d,f,p),b=this.rotationalEquation2=new n(d,f,p),R=this.motorEquation=new a(d,f,_);R.enabled=!1,this.equations.push(S,b,R)}h.prototype=new r,h.constructor=h,h.prototype.enableMotor=function(){this.motorEquation.enabled=!0},h.prototype.disableMotor=function(){this.motorEquation.enabled=!1},h.prototype.setMotorSpeed=function(d){this.motorEquation.targetVelocity=d},h.prototype.setMotorMaxForce=function(d){this.motorEquation.maxForce=d,this.motorEquation.minForce=-d};var c=new l,u=new l;h.prototype.update=function(){var d=this.bodyA,f=this.bodyB,p=this.motorEquation,_=this.rotationalEquation1,g=this.rotationalEquation2,v=c,E=u,C=this.axisA,S=this.axisB;r.prototype.update.call(this),d.quaternion.vmult(C,v),f.quaternion.vmult(S,E),v.tangents(_.axisA,g.axisA),_.axisB.copy(E),g.axisB.copy(E),this.motorEquation.enabled&&(d.quaternion.vmult(this.axisA,p.axisA),f.quaternion.vmult(this.axisB,p.axisB))}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(t,i,s){i.exports=l,t("./Constraint");var r=t("./PointToPointConstraint"),n=t("../equations/RotationalEquation");t("../equations/RotationalMotorEquation"),t("../equations/ContactEquation");var a=t("../math/Vec3");function l(h,c,u){u=u||{};var d=typeof u.maxForce<"u"?u.maxForce:1e6,f=new a,p=new a,_=new a;h.position.vadd(c.position,_),_.scale(.5,_),c.pointToLocalFrame(_,p),h.pointToLocalFrame(_,f),r.call(this,h,f,c,p,d);var g=this.rotationalEquation1=new n(h,c,u),v=this.rotationalEquation2=new n(h,c,u),E=this.rotationalEquation3=new n(h,c,u);this.equations.push(g,v,E)}l.prototype=new r,l.constructor=l,new a,new a,l.prototype.update=function(){var h=this.bodyA,c=this.bodyB;this.motorEquation;var u=this.rotationalEquation1,d=this.rotationalEquation2,f=this.rotationalEquation3;r.prototype.update.call(this),h.vectorToWorldFrame(a.UNIT_X,u.axisA),c.vectorToWorldFrame(a.UNIT_Y,u.axisB),h.vectorToWorldFrame(a.UNIT_Y,d.axisA),c.vectorToWorldFrame(a.UNIT_Z,d.axisB),h.vectorToWorldFrame(a.UNIT_Z,f.axisA),c.vectorToWorldFrame(a.UNIT_X,f.axisB)}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(t,i,s){i.exports=l;var r=t("./Constraint"),n=t("../equations/ContactEquation"),a=t("../math/Vec3");function l(h,c,u,d,f){r.call(this,h,u),f=typeof f<"u"?f:1e6,this.pivotA=c?c.clone():new a,this.pivotB=d?d.clone():new a;var p=this.equationX=new n(h,u),_=this.equationY=new n(h,u),g=this.equationZ=new n(h,u);this.equations.push(p,_,g),p.minForce=_.minForce=g.minForce=-f,p.maxForce=_.maxForce=g.maxForce=f,p.ni.set(1,0,0),_.ni.set(0,1,0),g.ni.set(0,0,1)}l.prototype=new r,l.prototype.update=function(){var h=this.bodyA,c=this.bodyB,u=this.equationX,d=this.equationY,f=this.equationZ;h.quaternion.vmult(this.pivotA,u.ri),c.quaternion.vmult(this.pivotB,u.rj),d.ri.copy(u.ri),d.rj.copy(u.rj),f.ri.copy(u.ri),f.rj.copy(u.rj)}},{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(c,u,d){d=d||{};var f=typeof d.maxForce<"u"?d.maxForce:1e6;n.call(this,c,u,-f,f),this.axisA=d.axisA?d.axisA.clone():new r(1,0,0),this.axisB=d.axisB?d.axisB.clone():new r(0,1,0),this.angle=typeof d.angle<"u"?d.angle:0}a.prototype=new n,a.prototype.constructor=a;var l=new r,h=new r;a.prototype.computeB=function(c){var u=this.a,d=this.b,f=this.axisA,p=this.axisB,_=l,g=h,v=this.jacobianElementA,E=this.jacobianElementB;f.cross(p,_),p.cross(f,g),v.rotational.copy(g),E.rotational.copy(_);var C=Math.cos(this.angle)-f.dot(p),S=this.computeGW(),b=this.computeGiMf(),R=-C*u-S*d-c*b;return R}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(t,i,s){i.exports=a;var r=t("./Equation"),n=t("../math/Vec3");t("../math/Mat3");function a(g,v,E){E=typeof E<"u"?E:1e6,r.call(this,g,v,0,E),this.restitution=0,this.ri=new n,this.rj=new n,this.ni=new n}a.prototype=new r,a.prototype.constructor=a;var l=new n,h=new n,c=new n;a.prototype.computeB=function(g){var v=this.a,E=this.b,C=this.bi,S=this.bj,b=this.ri,R=this.rj,I=l,N=h,O=C.velocity,L=C.angularVelocity;C.force,C.torque;var B=S.velocity,V=S.angularVelocity;S.force,S.torque;var Z=c,ue=this.jacobianElementA,oe=this.jacobianElementB,me=this.ni;b.cross(me,I),R.cross(me,N),me.negate(ue.spatial),I.negate(ue.rotational),oe.spatial.copy(me),oe.rotational.copy(N),Z.copy(S.position),Z.vadd(R,Z),Z.vsub(C.position,Z),Z.vsub(b,Z);var le=me.dot(Z),ae=this.restitution+1,ce=ae*B.dot(me)-ae*O.dot(me)+V.dot(N)-L.dot(I),ie=this.computeGiMf(),w=-le*v-ce*E-g*ie;return w};var u=new n,d=new n,f=new n,p=new n,_=new n;a.prototype.getImpactVelocityAlongNormal=function(){var g=u,v=d,E=f,C=p,S=_;return this.bi.position.vadd(this.ri,E),this.bj.position.vadd(this.rj,C),this.bi.getVelocityAtWorldPoint(E,g),this.bj.getVelocityAtWorldPoint(C,v),g.vsub(v,S),this.ni.dot(S)}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(t,i,s){i.exports=a;var r=t("../math/JacobianElement"),n=t("../math/Vec3");function a(_,g,v,E){this.id=a.id++,this.minForce=typeof v>"u"?-1e6:v,this.maxForce=typeof E>"u"?1e6:E,this.bi=_,this.bj=g,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new r,this.jacobianElementB=new r,this.enabled=!0,this.setSpookParams(1e7,4,1/60)}a.prototype.constructor=a,a.id=0,a.prototype.setSpookParams=function(_,g,v){var E=g,C=_,S=v;this.a=4/(S*(1+4*E)),this.b=4*E/(1+4*E),this.eps=4/(S*S*C*(1+4*E))},a.prototype.computeB=function(_,g,v){var E=this.computeGW(),C=this.computeGq(),S=this.computeGiMf();return-C*_-E*g-S*v},a.prototype.computeGq=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.position,S=E.position;return _.spatial.dot(C)+g.spatial.dot(S)};var l=new n;a.prototype.computeGW=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.velocity,S=E.velocity,b=v.angularVelocity||l,R=E.angularVelocity||l;return _.multiplyVectors(C,b)+g.multiplyVectors(S,R)},a.prototype.computeGWlambda=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.vlambda,S=E.vlambda,b=v.wlambda||l,R=E.wlambda||l;return _.multiplyVectors(C,b)+g.multiplyVectors(S,R)};var h=new n,c=new n,u=new n,d=new n;a.prototype.computeGiMf=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.force,S=v.torque,b=E.force,R=E.torque,I=v.invMassSolve,N=E.invMassSolve;return v.invInertiaWorldSolve?v.invInertiaWorldSolve.vmult(S,u):u.set(0,0,0),E.invInertiaWorldSolve?E.invInertiaWorldSolve.vmult(R,d):d.set(0,0,0),C.mult(I,h),b.mult(N,c),_.multiplyVectors(h,u)+g.multiplyVectors(c,d)};var f=new n;a.prototype.computeGiMGt=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.invMassSolve,S=E.invMassSolve,b=v.invInertiaWorldSolve,R=E.invInertiaWorldSolve,I=C+S;return b&&(b.vmult(_.rotational,f),I+=f.dot(_.rotational)),R&&(R.vmult(g.rotational,f),I+=f.dot(g.rotational)),I};var p=new n;new n,new n,new n,new n,new n,a.prototype.addToWlambda=function(_){var g=this.jacobianElementA,v=this.jacobianElementB,E=this.bi,C=this.bj,S=p;g.spatial.mult(E.invMassSolve*_,S),E.vlambda.vadd(S,E.vlambda),v.spatial.mult(C.invMassSolve*_,S),C.vlambda.vadd(S,C.vlambda),E.invInertiaWorldSolve&&(E.invInertiaWorldSolve.vmult(g.rotational,S),S.mult(_,S),E.wlambda.vadd(S,E.wlambda)),C.invInertiaWorldSolve&&(C.invInertiaWorldSolve.vmult(v.rotational,S),S.mult(_,S),C.wlambda.vadd(S,C.wlambda))},a.prototype.computeC=function(){return this.computeGiMGt()+this.eps}},{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(t,i,s){i.exports=a;var r=t("./Equation"),n=t("../math/Vec3");t("../math/Mat3");function a(c,u,d){r.call(this,c,u,-d,d),this.ri=new n,this.rj=new n,this.t=new n}a.prototype=new r,a.prototype.constructor=a;var l=new n,h=new n;a.prototype.computeB=function(c){this.a;var u=this.b;this.bi,this.bj;var d=this.ri,f=this.rj,p=l,_=h,g=this.t;d.cross(g,p),f.cross(g,_);var v=this.jacobianElementA,E=this.jacobianElementB;g.negate(v.spatial),p.negate(v.rotational),E.spatial.copy(g),E.rotational.copy(_);var C=this.computeGW(),S=this.computeGiMf(),b=-C*u-c*S;return b}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(c,u,d){d=d||{};var f=typeof d.maxForce<"u"?d.maxForce:1e6;n.call(this,c,u,-f,f),this.axisA=d.axisA?d.axisA.clone():new r(1,0,0),this.axisB=d.axisB?d.axisB.clone():new r(0,1,0),this.maxAngle=Math.PI/2}a.prototype=new n,a.prototype.constructor=a;var l=new r,h=new r;a.prototype.computeB=function(c){var u=this.a,d=this.b,f=this.axisA,p=this.axisB,_=l,g=h,v=this.jacobianElementA,E=this.jacobianElementB;f.cross(p,_),p.cross(f,g),v.rotational.copy(g),E.rotational.copy(_);var C=Math.cos(this.maxAngle)-f.dot(p),S=this.computeGW(),b=this.computeGiMf(),R=-C*u-S*d-c*b;return R}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(l,h,c){c=typeof c<"u"?c:1e6,n.call(this,l,h,-c,c),this.axisA=new r,this.axisB=new r,this.targetVelocity=0}a.prototype=new n,a.prototype.constructor=a,a.prototype.computeB=function(l){this.a;var h=this.b;this.bi,this.bj;var c=this.axisA,u=this.axisB,d=this.jacobianElementA,f=this.jacobianElementB;d.rotational.copy(c),u.negate(f.rotational);var p=this.computeGW()-this.targetVelocity,_=this.computeGiMf(),g=-p*h-l*_;return g}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(t,i,s){var r=t("../utils/Utils");i.exports=n;function n(a,l,h){h=r.defaults(h,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=n.idCounter++,this.materials=[a,l],this.friction=h.friction,this.restitution=h.restitution,this.contactEquationStiffness=h.contactEquationStiffness,this.contactEquationRelaxation=h.contactEquationRelaxation,this.frictionEquationStiffness=h.frictionEquationStiffness,this.frictionEquationRelaxation=h.frictionEquationRelaxation}n.idCounter=0},{"../utils/Utils":53}],25:[function(t,i,s){i.exports=r;function r(n){var a="";n=n||{},typeof n=="string"?(a=n,n={}):typeof n=="object"&&(a=""),this.name=a,this.id=r.idCounter++,this.friction=typeof n.friction<"u"?n.friction:-1,this.restitution=typeof n.restitution<"u"?n.restitution:-1}r.idCounter=0},{}],26:[function(t,i,s){i.exports=n;var r=t("./Vec3");function n(){this.spatial=new r,this.rotational=new r}n.prototype.multiplyElement=function(a){return a.spatial.dot(this.spatial)+a.rotational.dot(this.rotational)},n.prototype.multiplyVectors=function(a,l){return a.dot(this.spatial)+l.dot(this.rotational)}},{"./Vec3":30}],27:[function(t,i,s){i.exports=n;var r=t("./Vec3");function n(a){a?this.elements=a:this.elements=[0,0,0,0,0,0,0,0,0]}n.prototype.identity=function(){var a=this.elements;a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=1,a[5]=0,a[6]=0,a[7]=0,a[8]=1},n.prototype.setZero=function(){var a=this.elements;a[0]=0,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=0,a[6]=0,a[7]=0,a[8]=0},n.prototype.setTrace=function(a){var l=this.elements;l[0]=a.x,l[4]=a.y,l[8]=a.z},n.prototype.getTrace=function(l){var l=l||new r,h=this.elements;l.x=h[0],l.y=h[4],l.z=h[8]},n.prototype.vmult=function(a,l){l=l||new r;var h=this.elements,c=a.x,u=a.y,d=a.z;return l.x=h[0]*c+h[1]*u+h[2]*d,l.y=h[3]*c+h[4]*u+h[5]*d,l.z=h[6]*c+h[7]*u+h[8]*d,l},n.prototype.smult=function(a){for(var l=0;l.499&&(p=2*Math.atan2(v,S),_=Math.PI/2,g=0),b<-.499&&(p=-2*Math.atan2(v,S),_=-Math.PI/2,g=0),isNaN(p)){var R=v*v,I=E*E,N=C*C;p=Math.atan2(2*E*S-2*v*C,1-2*I-2*N),_=Math.asin(2*b),g=Math.atan2(2*v*S-2*E*C,1-2*R-2*N)}break;default:throw new Error("Euler order "+f+" not supported yet.")}d.y=p,d.z=_,d.x=g},n.prototype.setFromEuler=function(d,f,p,_){_=_||"XYZ";var g=Math.cos(d/2),v=Math.cos(f/2),E=Math.cos(p/2),C=Math.sin(d/2),S=Math.sin(f/2),b=Math.sin(p/2);return _==="XYZ"?(this.x=C*v*E+g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E-C*S*b):_==="YXZ"?(this.x=C*v*E+g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E+C*S*b):_==="ZXY"?(this.x=C*v*E-g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E-C*S*b):_==="ZYX"?(this.x=C*v*E-g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E+C*S*b):_==="YZX"?(this.x=C*v*E+g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E-C*S*b):_==="XZY"&&(this.x=C*v*E-g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E+C*S*b),this},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)}},{"./Vec3":30}],29:[function(t,i,s){var r=t("./Vec3"),n=t("./Quaternion");i.exports=a;function a(h){h=h||{},this.position=new r,h.position&&this.position.copy(h.position),this.quaternion=new n,h.quaternion&&this.quaternion.copy(h.quaternion)}var l=new n;a.pointToLocalFrame=function(h,c,u,f){var f=f||new r;return u.vsub(h,f),c.conjugate(l),l.vmult(f,f),f},a.prototype.pointToLocal=function(h,c){return a.pointToLocalFrame(this.position,this.quaternion,h,c)},a.pointToWorldFrame=function(h,c,u,f){var f=f||new r;return c.vmult(u,f),f.vadd(h,f),f},a.prototype.pointToWorld=function(h,c){return a.pointToWorldFrame(this.position,this.quaternion,h,c)},a.prototype.vectorToWorldFrame=function(h,u){var u=u||new r;return this.quaternion.vmult(h,u),u},a.vectorToWorldFrame=function(h,c,u){return h.vmult(c,u),u},a.vectorToLocalFrame=function(h,c,u,f){var f=f||new r;return c.w*=-1,c.vmult(u,f),c.w*=-1,f}},{"./Quaternion":28,"./Vec3":30}],30:[function(t,i,s){i.exports=n;var r=t("./Mat3");function n(c,u,d){this.x=c||0,this.y=u||0,this.z=d||0}n.ZERO=new n(0,0,0),n.UNIT_X=new n(1,0,0),n.UNIT_Y=new n(0,1,0),n.UNIT_Z=new n(0,0,1),n.prototype.cross=function(c,u){var d=c.x,f=c.y,p=c.z,_=this.x,g=this.y,v=this.z;return u=u||new n,u.x=g*p-v*f,u.y=v*d-_*p,u.z=_*f-g*d,u},n.prototype.set=function(c,u,d){return this.x=c,this.y=u,this.z=d,this},n.prototype.setZero=function(){this.x=this.y=this.z=0},n.prototype.vadd=function(c,u){if(u)u.x=c.x+this.x,u.y=c.y+this.y,u.z=c.z+this.z;else return new n(this.x+c.x,this.y+c.y,this.z+c.z)},n.prototype.vsub=function(c,u){if(u)u.x=this.x-c.x,u.y=this.y-c.y,u.z=this.z-c.z;else return new n(this.x-c.x,this.y-c.y,this.z-c.z)},n.prototype.crossmat=function(){return new r([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},n.prototype.normalize=function(){var c=this.x,u=this.y,d=this.z,f=Math.sqrt(c*c+u*u+d*d);if(f>0){var p=1/f;this.x*=p,this.y*=p,this.z*=p}else this.x=0,this.y=0,this.z=0;return f},n.prototype.unit=function(c){c=c||new n;var u=this.x,d=this.y,f=this.z,p=Math.sqrt(u*u+d*d+f*f);return p>0?(p=1/p,c.x=u*p,c.y=d*p,c.z=f*p):(c.x=1,c.y=0,c.z=0),c},n.prototype.norm=function(){var c=this.x,u=this.y,d=this.z;return Math.sqrt(c*c+u*u+d*d)},n.prototype.length=n.prototype.norm,n.prototype.norm2=function(){return this.dot(this)},n.prototype.lengthSquared=n.prototype.norm2,n.prototype.distanceTo=function(c){var u=this.x,d=this.y,f=this.z,p=c.x,_=c.y,g=c.z;return Math.sqrt((p-u)*(p-u)+(_-d)*(_-d)+(g-f)*(g-f))},n.prototype.distanceSquared=function(c){var u=this.x,d=this.y,f=this.z,p=c.x,_=c.y,g=c.z;return(p-u)*(p-u)+(_-d)*(_-d)+(g-f)*(g-f)},n.prototype.mult=function(c,u){u=u||new n;var d=this.x,f=this.y,p=this.z;return u.x=c*d,u.y=c*f,u.z=c*p,u},n.prototype.scale=n.prototype.mult,n.prototype.dot=function(c){return this.x*c.x+this.y*c.y+this.z*c.z},n.prototype.isZero=function(){return this.x===0&&this.y===0&&this.z===0},n.prototype.negate=function(c){return c=c||new n,c.x=-this.x,c.y=-this.y,c.z=-this.z,c};var a=new n,l=new n;n.prototype.tangents=function(c,u){var d=this.norm();if(d>0){var f=a,p=1/d;f.set(this.x*p,this.y*p,this.z*p);var _=l;Math.abs(f.x)<.9?(_.set(1,0,0),f.cross(_,c)):(_.set(0,1,0),f.cross(_,c)),f.cross(c,u)}else c.set(1,0,0),u.set(0,1,0)},n.prototype.toString=function(){return this.x+","+this.y+","+this.z},n.prototype.toArray=function(){return[this.x,this.y,this.z]},n.prototype.copy=function(c){return this.x=c.x,this.y=c.y,this.z=c.z,this},n.prototype.lerp=function(c,u,d){var f=this.x,p=this.y,_=this.z;d.x=f+(c.x-f)*u,d.y=p+(c.y-p)*u,d.z=_+(c.z-_)*u},n.prototype.almostEquals=function(c,u){return u===void 0&&(u=1e-6),!(Math.abs(this.x-c.x)>u||Math.abs(this.y-c.y)>u||Math.abs(this.z-c.z)>u)},n.prototype.almostZero=function(c){return c===void 0&&(c=1e-6),!(Math.abs(this.x)>c||Math.abs(this.y)>c||Math.abs(this.z)>c)};var h=new n;n.prototype.isAntiparallelTo=function(c,u){return this.negate(h),h.almostEquals(c,u)},n.prototype.clone=function(){return new n(this.x,this.y,this.z)}},{"./Mat3":27}],31:[function(t,i,s){i.exports=u;var r=t("../utils/EventTarget");t("../shapes/Shape");var n=t("../math/Vec3"),a=t("../math/Mat3"),l=t("../math/Quaternion");t("../material/Material");var h=t("../collision/AABB"),c=t("../shapes/Box");function u(B){B=B||{},r.apply(this),this.id=u.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new n,this.collisionFilterGroup=typeof B.collisionFilterGroup=="number"?B.collisionFilterGroup:1,this.collisionFilterMask=typeof B.collisionFilterMask=="number"?B.collisionFilterMask:1,this.collisionResponse=!0,this.position=new n,B.position&&this.position.copy(B.position),this.previousPosition=new n,this.initPosition=new n,this.velocity=new n,B.velocity&&this.velocity.copy(B.velocity),this.initVelocity=new n,this.force=new n;var V=typeof B.mass=="number"?B.mass:0;this.mass=V,this.invMass=V>0?1/V:0,this.material=B.material||null,this.linearDamping=typeof B.linearDamping=="number"?B.linearDamping:.01,this.type=V<=0?u.STATIC:u.DYNAMIC,typeof B.type==typeof u.STATIC&&(this.type=B.type),this.allowSleep=typeof B.allowSleep<"u"?B.allowSleep:!0,this.sleepState=0,this.sleepSpeedLimit=typeof B.sleepSpeedLimit<"u"?B.sleepSpeedLimit:.1,this.sleepTimeLimit=typeof B.sleepTimeLimit<"u"?B.sleepTimeLimit:1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new n,this.quaternion=new l,B.quaternion&&this.quaternion.copy(B.quaternion),this.initQuaternion=new l,this.angularVelocity=new n,B.angularVelocity&&this.angularVelocity.copy(B.angularVelocity),this.initAngularVelocity=new n,this.interpolatedPosition=new n,this.interpolatedQuaternion=new l,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new n,this.invInertia=new n,this.invInertiaWorld=new a,this.invMassSolve=0,this.invInertiaSolve=new n,this.invInertiaWorldSolve=new a,this.fixedRotation=typeof B.fixedRotation<"u"?B.fixedRotation:!1,this.angularDamping=typeof B.angularDamping<"u"?B.angularDamping:.01,this.aabb=new h,this.aabbNeedsUpdate=!0,this.wlambda=new n,B.shape&&this.addShape(B.shape),this.updateMassProperties()}u.prototype=new r,u.prototype.constructor=u,u.DYNAMIC=1,u.STATIC=2,u.KINEMATIC=4,u.AWAKE=0,u.SLEEPY=1,u.SLEEPING=2,u.idCounter=0,u.prototype.wakeUp=function(){var B=this.sleepState;this.sleepState=0,B===u.SLEEPING&&this.dispatchEvent({type:"wakeup"})},u.prototype.sleep=function(){this.sleepState=u.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0)},u.sleepyEvent={type:"sleepy"},u.sleepEvent={type:"sleep"},u.prototype.sleepTick=function(B){if(this.allowSleep){var V=this.sleepState,Z=this.velocity.norm2()+this.angularVelocity.norm2(),ue=Math.pow(this.sleepSpeedLimit,2);V===u.AWAKE&&Zue?this.wakeUp():V===u.SLEEPY&&B-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(u.sleepEvent))}},u.prototype.updateSolveMassProperties=function(){this.sleepState===u.SLEEPING||this.type===u.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},u.prototype.pointToLocalFrame=function(B,Z){var Z=Z||new n;return B.vsub(this.position,Z),this.quaternion.conjugate().vmult(Z,Z),Z},u.prototype.vectorToLocalFrame=function(B,Z){var Z=Z||new n;return this.quaternion.conjugate().vmult(B,Z),Z},u.prototype.pointToWorldFrame=function(B,Z){var Z=Z||new n;return this.quaternion.vmult(B,Z),Z.vadd(this.position,Z),Z},u.prototype.vectorToWorldFrame=function(B,Z){var Z=Z||new n;return this.quaternion.vmult(B,Z),Z};var d=new n,f=new l;u.prototype.addShape=function(B,V,Z){var ue=new n,oe=new l;return V&&ue.copy(V),Z&&oe.copy(Z),this.shapes.push(B),this.shapeOffsets.push(ue),this.shapeOrientations.push(oe),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,this},u.prototype.updateBoundingRadius=function(){for(var B=this.shapes,V=this.shapeOffsets,Z=B.length,ue=0,oe=0;oe!==Z;oe++){var me=B[oe];me.updateBoundingSphereRadius();var le=V[oe].norm(),ae=me.boundingSphereRadius;le+ae>ue&&(ue=le+ae)}this.boundingRadius=ue};var p=new h;u.prototype.computeAABB=function(){for(var B=this.shapes,V=this.shapeOffsets,Z=this.shapeOrientations,ue=B.length,oe=d,me=f,le=this.quaternion,ae=this.aabb,ce=p,ie=0;ie!==ue;ie++){var w=B[ie];Z[ie].mult(le,me),me.vmult(V[ie],oe),oe.vadd(this.position,oe),w.calculateWorldAABB(oe,me,ce.lowerBound,ce.upperBound),ie===0?ae.copy(ce):ae.extend(ce)}this.aabbNeedsUpdate=!1};var _=new a,g=new a;new a,u.prototype.updateInertiaWorld=function(B){var V=this.invInertia;if(!(V.x===V.y&&V.y===V.z&&!B)){var Z=_,ue=g;Z.setRotationFromQuaternion(this.quaternion),Z.transpose(ue),Z.scale(V,Z),Z.mmult(ue,this.invInertiaWorld)}};var v=new n,E=new n;u.prototype.applyForce=function(B,V){if(this.type===u.DYNAMIC){var Z=v;V.vsub(this.position,Z);var ue=E;Z.cross(B,ue),this.force.vadd(B,this.force),this.torque.vadd(ue,this.torque)}};var C=new n,S=new n;u.prototype.applyLocalForce=function(B,V){if(this.type===u.DYNAMIC){var Z=C,ue=S;this.vectorToWorldFrame(B,Z),this.pointToWorldFrame(V,ue),this.applyForce(Z,ue)}};var b=new n,R=new n,I=new n;u.prototype.applyImpulse=function(B,V){if(this.type===u.DYNAMIC){var Z=b;V.vsub(this.position,Z);var ue=R;ue.copy(B),ue.mult(this.invMass,ue),this.velocity.vadd(ue,this.velocity);var oe=I;Z.cross(B,oe),this.invInertiaWorld.vmult(oe,oe),this.angularVelocity.vadd(oe,this.angularVelocity)}};var N=new n,O=new n;u.prototype.applyLocalImpulse=function(B,V){if(this.type===u.DYNAMIC){var Z=N,ue=O;this.vectorToWorldFrame(B,Z),this.pointToWorldFrame(V,ue),this.applyImpulse(Z,ue)}};var L=new n;u.prototype.updateMassProperties=function(){var B=L;this.invMass=this.mass>0?1/this.mass:0;var V=this.inertia,Z=this.fixedRotation;this.computeAABB(),B.set((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),c.calculateInertia(B,this.mass,V),this.invInertia.set(V.x>0&&!Z?1/V.x:0,V.y>0&&!Z?1/V.y:0,V.z>0&&!Z?1/V.z:0),this.updateInertiaWorld(!0)},u.prototype.getVelocityAtWorldPoint=function(B,V){var Z=new n;return B.vsub(this.position,Z),this.angularVelocity.cross(Z,V),this.velocity.vadd(V,V),V}},{"../collision/AABB":3,"../material/Material":25,"../math/Mat3":27,"../math/Quaternion":28,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Shape":43,"../utils/EventTarget":49}],32:[function(t,i,s){t("./Body");var r=t("../math/Vec3"),n=t("../math/Quaternion");t("../collision/RaycastResult");var a=t("../collision/Ray"),l=t("../objects/WheelInfo");i.exports=h;function h(le){this.chassisBody=le.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=typeof le.indexRightAxis<"u"?le.indexRightAxis:1,this.indexForwardAxis=typeof le.indexForwardAxis<"u"?le.indexForwardAxis:0,this.indexUpAxis=typeof le.indexUpAxis<"u"?le.indexUpAxis:2}new r,new r,new r;var c=new r,u=new r,d=new r;new a,h.prototype.addWheel=function(le){le=le||{};var ae=new l(le),ce=this.wheelInfos.length;return this.wheelInfos.push(ae),ce},h.prototype.setSteeringValue=function(le,ae){var ce=this.wheelInfos[ae];ce.steering=le},new r,h.prototype.applyEngineForce=function(le,ae){this.wheelInfos[ae].engineForce=le},h.prototype.setBrake=function(le,ae){this.wheelInfos[ae].brake=le},h.prototype.addToWorld=function(le){this.constraints,le.add(this.chassisBody);var ae=this;this.preStepCallback=function(){ae.updateVehicle(le.dt)},le.addEventListener("preStep",this.preStepCallback),this.world=le},h.prototype.getVehicleAxisWorld=function(le,ae){ae.set(le===0?1:0,le===1?1:0,le===2?1:0),this.chassisBody.vectorToWorldFrame(ae,ae)},h.prototype.updateVehicle=function(le){for(var ae=this.wheelInfos,ce=ae.length,ie=this.chassisBody,w=0;wQ.maxSuspensionForce&&(_e=Q.maxSuspensionForce),Q.raycastResult.hitNormalWorld.scale(_e*le,X),Q.raycastResult.hitPointWorld.vsub(ie.position,te),ie.applyImpulse(X,Q.raycastResult.hitPointWorld)}this.updateFriction(le);var q=new r,de=new r,ge=new r;for(w=0;w0?1:-1)*Q.customSlidingRotationalSpeed*le),Math.abs(Q.brake)>Math.abs(Q.engineForce)&&(Q.deltaRotation=0),Q.rotation+=Q.deltaRotation,Q.deltaRotation*=.99}},h.prototype.updateSuspension=function(le){for(var ae=this.chassisBody,ce=ae.mass,ie=this.wheelInfos,w=ie.length,H=0;Hge&&(le.suspensionLength=ge,le.raycastResult.reset());var ve=le.raycastResult.hitNormalWorld.dot(le.directionWorld),be=new r;ie.getVelocityAtWorldPoint(le.raycastResult.hitPointWorld,be);var Le=le.raycastResult.hitNormalWorld.dot(be);if(ve>=-.1)le.suspensionRelativeVelocity=0,le.clippedInvContactDotSuspension=1/.1;else{var Ye=-1/ve;le.suspensionRelativeVelocity=Le*Ye,le.clippedInvContactDotSuspension=Ye}}else le.suspensionLength=le.suspensionRestLength+0*le.maxSuspensionTravel,le.suspensionRelativeVelocity=0,le.directionWorld.scale(-1,le.raycastResult.hitNormalWorld),le.clippedInvContactDotSuspension=1;return w},h.prototype.updateWheelTransformWorld=function(le){le.isInContact=!1;var ae=this.chassisBody;ae.pointToWorldFrame(le.chassisConnectionPointLocal,le.chassisConnectionPointWorld),ae.vectorToWorldFrame(le.directionLocal,le.directionWorld),ae.vectorToWorldFrame(le.axleLocal,le.axleWorld)},h.prototype.updateWheelTransform=function(le){var ae=c,ce=u,ie=d,w=this.wheelInfos[le];this.updateWheelTransformWorld(w),w.directionLocal.scale(-1,ae),ce.copy(w.axleLocal),ae.cross(ce,ie),ie.normalize(),ce.normalize();var H=w.steering,X=new n;X.setFromAxisAngle(ae,H);var te=new n;te.setFromAxisAngle(ce,w.rotation);var Q=w.worldTransform.quaternion;this.chassisBody.quaternion.mult(X,Q),Q.mult(te,Q),Q.normalize();var _e=w.worldTransform.position;_e.copy(w.directionWorld),_e.scale(w.suspensionLength,_e),_e.vadd(w.chassisConnectionPointWorld,_e)};var _=[new r(1,0,0),new r(0,1,0),new r(0,0,1)];h.prototype.getWheelTransformWorld=function(le){return this.wheelInfos[le].worldTransform};var g=new r,v=[],E=[],C=1;h.prototype.updateFriction=function(le){for(var ae=g,ce=this.wheelInfos,ie=ce.length,w=this.chassisBody,H=E,X=v,te=0;teVi){this.sliding=!0,Q.sliding=!0;var Ge=Lt/Math.sqrt(di);Q.skidInfo*=Ge}}}if(this.sliding)for(var te=0;te1.1)return 0;var te=Z,Q=ue,_e=oe;le.getVelocityAtWorldPoint(ae,te),ce.getVelocityAtWorldPoint(ie,Q),te.vsub(Q,_e);var q=w.dot(_e),de=.2,ge=1/(le.invMass+ce.invMass),ve=-de*q*ge;return ve}},{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(t,i,s){var r=t("./Body"),n=t("../shapes/Sphere"),a=t("../shapes/Box"),l=t("../math/Vec3"),h=t("../constraints/HingeConstraint");i.exports=c;function c(f){if(this.wheelBodies=[],this.coordinateSystem=typeof f.coordinateSystem>"u"?new l(1,2,3):f.coordinateSystem.clone(),this.chassisBody=f.chassisBody,!this.chassisBody){var p=new a(new l(5,2,.5));this.chassisBody=new r(1,p)}this.constraints=[],this.wheelAxes=[],this.wheelForces=[]}c.prototype.addWheel=function(f){f=f||{};var p=f.body;p||(p=new r(1,new n(1.2))),this.wheelBodies.push(p),this.wheelForces.push(0),new l;var _=typeof f.position<"u"?f.position.clone():new l,g=new l;this.chassisBody.pointToWorldFrame(_,g),p.position.set(g.x,g.y,g.z);var v=typeof f.axis<"u"?f.axis.clone():new l(0,1,0);this.wheelAxes.push(v);var E=new h(this.chassisBody,p,{pivotA:_,axisA:v,pivotB:l.ZERO,axisB:v,collideConnected:!1});return this.constraints.push(E),this.wheelBodies.length-1},c.prototype.setSteeringValue=function(f,p){var _=this.wheelAxes[p],g=Math.cos(f),v=Math.sin(f),E=_.x,C=_.y;this.constraints[p].axisA.set(g*E-v*C,v*E+g*C,0)},c.prototype.setMotorSpeed=function(f,p){var _=this.constraints[p];_.enableMotor(),_.motorTargetVelocity=f},c.prototype.disableMotor=function(f){var p=this.constraints[f];p.disableMotor()};var u=new l;c.prototype.setWheelForce=function(f,p){this.wheelForces[p]=f},c.prototype.applyWheelForce=function(f,p){var _=this.wheelAxes[p],g=this.wheelBodies[p],v=g.torque;_.scale(f,u),g.vectorToWorldFrame(u,u),v.vadd(u,v)},c.prototype.addToWorld=function(f){for(var p=this.constraints,_=this.wheelBodies.concat([this.chassisBody]),g=0;g<_.length;g++)f.add(_[g]);for(var g=0;gthis.particles.length&&this.neighbors.pop())};var a=new r;n.prototype.getNeighbors=function(p,_){for(var g=this.particles.length,v=p.id,E=this.smoothingRadius*this.smoothingRadius,C=a,S=0;S!==g;S++){var b=this.particles[S];b.position.vsub(p.position,C),v!==b.id&&C.norm2()=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=1/.1;else{var g=-1/p;this.suspensionRelativeVelocity=_*g,this.clippedInvContactDotSuspension=g}}else f.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,f.directionWorld.scale(-1,f.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(t,i,s){i.exports=l;var r=t("./Shape"),n=t("../math/Vec3"),a=t("./ConvexPolyhedron");function l(u){r.call(this),this.type=r.types.BOX,this.halfExtents=u,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}l.prototype=new r,l.prototype.constructor=l,l.prototype.updateConvexPolyhedronRepresentation=function(){var u=this.halfExtents.x,d=this.halfExtents.y,f=this.halfExtents.z,p=n,_=[new p(-u,-d,-f),new p(u,-d,-f),new p(u,d,-f),new p(-u,d,-f),new p(-u,-d,f),new p(u,-d,f),new p(u,d,f),new p(-u,d,f)],g=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]];new p(0,0,1),new p(0,1,0),new p(1,0,0);var v=new a(_,g);this.convexPolyhedronRepresentation=v,v.material=this.material},l.prototype.calculateLocalInertia=function(u,d){return d=d||new n,l.calculateInertia(this.halfExtents,u,d),d},l.calculateInertia=function(u,d,f){var p=u;f.x=1/12*d*(2*p.y*2*p.y+2*p.z*2*p.z),f.y=1/12*d*(2*p.x*2*p.x+2*p.z*2*p.z),f.z=1/12*d*(2*p.y*2*p.y+2*p.x*2*p.x)},l.prototype.getSideNormals=function(u,d){var f=u,p=this.halfExtents;if(f[0].set(p.x,0,0),f[1].set(0,p.y,0),f[2].set(0,0,p.z),f[3].set(-p.x,0,0),f[4].set(0,-p.y,0),f[5].set(0,0,-p.z),d!==void 0)for(var _=0;_!==f.length;_++)d.vmult(f[_],f[_]);return f},l.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},l.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};var h=new n;new n,l.prototype.forEachWorldCorner=function(u,d,f){for(var p=this.halfExtents,_=[[p.x,p.y,p.z],[-p.x,p.y,p.z],[-p.x,-p.y,p.z],[-p.x,-p.y,-p.z],[p.x,-p.y,-p.z],[p.x,p.y,-p.z],[-p.x,p.y,-p.z],[p.x,-p.y,p.z]],g=0;g<_.length;g++)h.set(_[g][0],_[g][1],_[g][2]),d.vmult(h,h),u.vadd(h,h),f(h.x,h.y,h.z)};var c=[new n,new n,new n,new n,new n,new n,new n,new n];l.prototype.calculateWorldAABB=function(u,d,f,p){var _=this.halfExtents;c[0].set(_.x,_.y,_.z),c[1].set(-_.x,_.y,_.z),c[2].set(-_.x,-_.y,_.z),c[3].set(-_.x,-_.y,-_.z),c[4].set(_.x,-_.y,-_.z),c[5].set(_.x,_.y,-_.z),c[6].set(-_.x,_.y,-_.z),c[7].set(_.x,-_.y,_.z);var g=c[0];d.vmult(g,g),u.vadd(g,g),p.copy(g),f.copy(g);for(var v=1;v<8;v++){var g=c[v];d.vmult(g,g),u.vadd(g,g);var E=g.x,C=g.y,S=g.z;E>p.x&&(p.x=E),C>p.y&&(p.y=C),S>p.z&&(p.z=S),ELe&&(Le=He,be=Ye)}for(var Be=[],Ge=X.faces[be],Lt=Ge.length,Mt=0;Mt=0&&this.clipFaceAgainstHull(_e,w,H,Be,q,de,ge)};var f=new n,p=new n,_=new n,g=new n,v=new n,E=new n;l.prototype.findSeparatingAxis=function(w,H,X,te,Q,_e,q,de){var ge=f,ve=p,be=_,Le=g,Ye=v,He=E,Be=Number.MAX_VALUE,Ge=this;if(Ge.uniqueAxes)for(var Mt=0;Mt!==Ge.uniqueAxes.length;Mt++){X.vmult(Ge.uniqueAxes[Mt],ge);var at=Ge.testSepAxis(ge,w,H,X,te,Q);if(at===!1)return!1;at0&&_e.negate(_e),!0};var C=[],S=[];l.prototype.testSepAxis=function(w,H,X,te,Q,_e){var q=this;l.project(q,w,X,te,C),l.project(H,w,Q,_e,S);var de=C[0],ge=C[1],ve=S[0],be=S[1],Le=de-be,Ye=ve-ge,He=LeH.x&&(H.x=_e.x),_e.yH.y&&(H.y=_e.y),_e.zH.z&&(H.z=_e.z)}},l.prototype.computeWorldFaceNormals=function(w){for(var H=this.faceNormals.length;this.worldFaceNormals.lengthw&&(w=Q)}this.boundingSphereRadius=Math.sqrt(w)};var oe=new n;l.prototype.calculateWorldAABB=function(w,H,X,te){for(var Q=this.vertices.length,_e=this.vertices,q,de,ge,ve,be,Le,Ye=0;Yeve||ve===void 0)&&(ve=He.x),He.ybe||be===void 0)&&(be=He.y),He.zLe||Le===void 0)&&(Le=He.z)}X.set(q,de,ge),te.set(ve,be,Le)},l.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},l.prototype.getAveragePointLocal=function(w){w=w||new n;for(var H=this.vertices.length,X=this.vertices,te=0;te0||Le>0&&He<0)return!1}return _e?1:-1},new n;var ce=new n,ie=new n;l.project=function(w,H,X,te,Q){var _e=w.vertices.length,q=ce,de=0,ge=0,ve=ie,be=w.vertices;ve.setZero(),a.vectorToLocalFrame(X,te,H,q),a.pointToLocalFrame(X,te,ve,ve);var Le=ve.dot(q);ge=de=be[0].dot(q);for(var Ye=1;Ye<_e;Ye++){var He=be[Ye].dot(q);He>de&&(de=He),Hede){var Be=ge;ge=de,de=Be}Q[0]=de,Q[1]=ge}},{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(t,i,s){i.exports=l;var r=t("./Shape"),n=t("../math/Vec3");t("../math/Quaternion");var a=t("./ConvexPolyhedron");function l(h,c,u,d){var f=d,p=[],_=[],g=[],v=[],E=[],C=Math.cos,S=Math.sin;p.push(new n(c*C(0),c*S(0),-u*.5)),v.push(0),p.push(new n(h*C(0),h*S(0),u*.5)),E.push(1);for(var b=0;bu&&(u=p)}this.maxValue=u},h.prototype.setHeightValueAtIndex=function(c,u,d){var f=this.data;f[c][u]=d,this.clearCachedConvexTrianglePillar(c,u,!1),c>0&&(this.clearCachedConvexTrianglePillar(c-1,u,!0),this.clearCachedConvexTrianglePillar(c-1,u,!1)),u>0&&(this.clearCachedConvexTrianglePillar(c,u-1,!0),this.clearCachedConvexTrianglePillar(c,u-1,!1)),u>0&&c>0&&this.clearCachedConvexTrianglePillar(c-1,u-1,!0)},h.prototype.getRectMinMax=function(c,u,d,f,p){p=p||[];for(var _=this.data,g=this.minValue,v=c;v<=d;v++)for(var E=u;E<=f;E++){var C=_[v][E];C>g&&(g=C)}p[0]=this.minValue,p[1]=g},h.prototype.getIndexOfPosition=function(c,u,d,f){var p=this.elementSize,_=this.data,g=Math.floor(c/p),v=Math.floor(u/p);return d[0]=g,d[1]=v,f&&(g<0&&(g=0),v<0&&(v=0),g>=_.length-1&&(g=_.length-1),v>=_[0].length-1&&(v=_[0].length-1)),!(g<0||v<0||g>=_.length-1||v>=_[0].length-1)},h.prototype.getHeightAt=function(c,u,d){var f=[];this.getIndexOfPosition(c,u,f,d);var p=[];return this.getRectMinMax(f[0],f[1]+1,f[0],f[1]+1,p),(p[0]+p[1])/2},h.prototype.getCacheConvexTrianglePillarKey=function(c,u,d){return c+"_"+u+"_"+(d?1:0)},h.prototype.getCachedConvexTrianglePillar=function(c,u,d){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]},h.prototype.setCachedConvexTrianglePillar=function(c,u,d,f,p){this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]={convex:f,offset:p}},h.prototype.clearCachedConvexTrianglePillar=function(c,u,d){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]},h.prototype.getConvexTrianglePillar=function(c,u,d){var f=this.pillarConvex,p=this.pillarOffset;if(this.cacheEnabled){var _=this.getCachedConvexTrianglePillar(c,u,d);if(_){this.pillarConvex=_.convex,this.pillarOffset=_.offset;return}f=new n,p=new a,this.pillarConvex=f,this.pillarOffset=p}var _=this.data,g=this.elementSize,v=f.faces;f.vertices.length=6;for(var E=0;E<6;E++)f.vertices[E]||(f.vertices[E]=new a);v.length=5;for(var E=0;E<5;E++)v[E]||(v[E]=[]);var C=f.vertices,S=(Math.min(_[c][u],_[c+1][u],_[c][u+1],_[c+1][u+1])-this.minValue)/2+this.minValue;d?(p.set((c+.75)*g,(u+.75)*g,S),C[0].set(.25*g,.25*g,_[c+1][u+1]-S),C[1].set(-.75*g,.25*g,_[c][u+1]-S),C[2].set(.25*g,-.75*g,_[c+1][u]-S),C[3].set(.25*g,.25*g,-S-1),C[4].set(-.75*g,.25*g,-S-1),C[5].set(.25*g,-.75*g,-S-1),v[0][0]=0,v[0][1]=1,v[0][2]=2,v[1][0]=5,v[1][1]=4,v[1][2]=3,v[2][0]=2,v[2][1]=5,v[2][2]=3,v[2][3]=0,v[3][0]=3,v[3][1]=4,v[3][2]=1,v[3][3]=0,v[4][0]=1,v[4][1]=4,v[4][2]=5,v[4][3]=2):(p.set((c+.25)*g,(u+.25)*g,S),C[0].set(-.25*g,-.25*g,_[c][u]-S),C[1].set(.75*g,-.25*g,_[c+1][u]-S),C[2].set(-.25*g,.75*g,_[c][u+1]-S),C[3].set(-.25*g,-.25*g,-S-1),C[4].set(.75*g,-.25*g,-S-1),C[5].set(-.25*g,.75*g,-S-1),v[0][0]=0,v[0][1]=1,v[0][2]=2,v[1][0]=5,v[1][1]=4,v[1][2]=3,v[2][0]=0,v[2][1]=2,v[2][2]=5,v[2][3]=3,v[3][0]=1,v[3][1]=0,v[3][2]=3,v[3][3]=4,v[4][0]=4,v[4][1]=5,v[4][2]=2,v[4][3]=1),f.computeNormals(),f.computeEdges(),f.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(c,u,d,f,p)},h.prototype.calculateLocalInertia=function(c,u){return u=u||new a,u.set(0,0,0),u},h.prototype.volume=function(){return Number.MAX_VALUE},h.prototype.calculateWorldAABB=function(c,u,d,f){d.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),f.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},h.prototype.updateBoundingSphereRadius=function(){var c=this.data,u=this.elementSize;this.boundingSphereRadius=new a(c.length*u,c[0].length*u,Math.max(Math.abs(this.maxValue),Math.abs(this.minValue))).norm()}},{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(){r.call(this),this.type=r.types.PARTICLE}a.prototype=new r,a.prototype.constructor=a,a.prototype.calculateLocalInertia=function(l,h){return h=h||new n,h.set(0,0,0),h},a.prototype.volume=function(){return 0},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=0},a.prototype.calculateWorldAABB=function(l,h,c,u){c.copy(l),u.copy(l)}},{"../math/Vec3":30,"./Shape":43}],42:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(){r.call(this),this.type=r.types.PLANE,this.worldNormal=new n,this.worldNormalNeedsUpdate=!0,this.boundingSphereRadius=Number.MAX_VALUE}a.prototype=new r,a.prototype.constructor=a,a.prototype.computeWorldNormal=function(h){var c=this.worldNormal;c.set(0,0,1),h.vmult(c,c),this.worldNormalNeedsUpdate=!1},a.prototype.calculateLocalInertia=function(h,c){return c=c||new n,c},a.prototype.volume=function(){return Number.MAX_VALUE};var l=new n;a.prototype.calculateWorldAABB=function(h,c,u,d){l.set(0,0,1),c.vmult(l,l);var f=Number.MAX_VALUE;u.set(-f,-f,-f),d.set(f,f,f),l.x===1&&(d.x=h.x),l.y===1&&(d.y=h.y),l.z===1&&(d.z=h.z),l.x===-1&&(u.x=h.x),l.y===-1&&(u.y=h.y),l.z===-1&&(u.z=h.z)},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=Number.MAX_VALUE}},{"../math/Vec3":30,"./Shape":43}],43:[function(t,i,s){i.exports=r;var r=t("./Shape");t("../math/Vec3"),t("../math/Quaternion"),t("../material/Material");function r(){this.id=r.idCounter++,this.type=0,this.boundingSphereRadius=0,this.collisionResponse=!0,this.material=null}r.prototype.constructor=r,r.prototype.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},r.prototype.volume=function(){throw"volume() not implemented for shape type "+this.type},r.prototype.calculateLocalInertia=function(n,a){throw"calculateLocalInertia() not implemented for shape type "+this.type},r.idCounter=0,r.types={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256}},{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(l){if(r.call(this),this.radius=l!==void 0?Number(l):1,this.type=r.types.SPHERE,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}a.prototype=new r,a.prototype.constructor=a,a.prototype.calculateLocalInertia=function(l,h){h=h||new n;var c=2*l*this.radius*this.radius/5;return h.x=c,h.y=c,h.z=c,h},a.prototype.volume=function(){return 4*Math.PI*this.radius/3},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},a.prototype.calculateWorldAABB=function(l,h,c,u){for(var d=this.radius,f=["x","y","z"],p=0;pL.x&&(L.x=V.x),V.yL.y&&(L.y=V.y),V.zL.z&&(L.z=V.z)},c.prototype.updateAABB=function(){this.computeLocalAABB(this.aabb)},c.prototype.updateBoundingSphereRadius=function(){for(var N=0,O=this.vertices,L=new n,B=0,V=O.length/3;B!==V;B++){this.getVertex(B,L);var Z=L.norm2();Z>N&&(N=Z)}this.boundingSphereRadius=Math.sqrt(N)},new n;var R=new a,I=new l;c.prototype.calculateWorldAABB=function(N,O,L,B){var V=R,Z=I;V.position=N,V.quaternion=O,this.aabb.toWorldFrame(V,Z),L.copy(Z.lowerBound),B.copy(Z.upperBound)},c.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},c.createTorus=function(N,O,L,B,V){N=N||1,O=O||.5,L=L||8,B=B||6,V=V||Math.PI*2;for(var Z=[],ue=[],oe=0;oe<=L;oe++)for(var me=0;me<=B;me++){var le=me/B*V,ae=oe/L*Math.PI*2,ce=(N+O*Math.cos(ae))*Math.cos(le),ie=(N+O*Math.cos(ae))*Math.sin(le),w=O*Math.sin(ae);Z.push(ce,ie,w)}for(var oe=1;oe<=L;oe++)for(var me=1;me<=B;me++){var H=(B+1)*oe+me-1,X=(B+1)*(oe-1)+me-1,te=(B+1)*(oe-1)+me,Q=(B+1)*oe+me;ue.push(H,X,Q),ue.push(X,te,Q)}return new c(Z,ue)}},{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(t,i,s){i.exports=n,t("../math/Vec3"),t("../math/Quaternion");var r=t("./Solver");function n(){r.call(this),this.iterations=10,this.tolerance=1e-7}n.prototype=new r;var a=[],l=[],h=[];n.prototype.solve=function(c,u){var d=0,f=this.iterations,p=this.tolerance*this.tolerance,_=this.equations,g=_.length,v=u.bodies,E=v.length,C=c,S,b,R,I,N,O;if(g!==0)for(var L=0;L!==E;L++)v[L].updateSolveMassProperties();var B=l,V=h,Z=a;B.length=g,V.length=g,Z.length=g;for(var L=0;L!==g;L++){var ue=_[L];Z[L]=0,V[L]=ue.computeB(C),B[L]=1/ue.computeC()}if(g!==0){for(var L=0;L!==E;L++){var oe=v[L],me=oe.vlambda,le=oe.wlambda;me.set(0,0,0),le&&le.set(0,0,0)}for(d=0;d!==f;d++){I=0;for(var ae=0;ae!==g;ae++){var ue=_[ae];S=V[ae],b=B[ae],O=Z[ae],N=ue.computeGWlambda(),R=b*(S-N-ue.eps*O),O+Rue.maxForce&&(R=ue.maxForce-O),Z[ae]+=R,I+=R>0?R:-R,ue.addToWlambda(R)}if(I*I=0;f--)d.children[f].data.length||d.children.splice(f,1);Array.prototype.push.apply(u,d.children)}}},{"../collision/AABB":3,"../math/Vec3":30}],51:[function(t,i,s){i.exports=r;function r(){this.objects=[],this.type=Object}r.prototype.release=function(){for(var n=arguments.length,a=0;a!==n;a++)this.objects.push(arguments[a])},r.prototype.get=function(){return this.objects.length===0?this.constructObject():this.objects.pop()},r.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}},{}],52:[function(t,i,s){i.exports=r;function r(){this.data={keys:[]}}r.prototype.get=function(n,a){if(n>a){var l=a;a=n,n=l}return this.data[n+"-"+a]},r.prototype.set=function(n,a,l){if(n>a){var h=a;a=n,n=h}var c=n+"-"+a;this.get(n,a)||this.data.keys.push(c),this.data[c]=l},r.prototype.reset=function(){for(var n=this.data,a=n.keys;a.length>0;){var l=a.pop();delete n[l]}}},{}],53:[function(t,i,s){function r(){}i.exports=r,r.defaults=function(n,a){n=n||{};for(var l in a)l in n||(n[l]=a[l]);return n}},{}],54:[function(t,i,s){i.exports=a;var r=t("../math/Vec3"),n=t("./Pool");function a(){n.call(this),this.type=r}a.prototype=new n,a.prototype.constructObject=function(){return new r}},{"../math/Vec3":30,"./Pool":51}],55:[function(t,i,s){i.exports=p;var r=t("../collision/AABB"),n=t("../shapes/Shape"),a=t("../collision/Ray"),l=t("../math/Vec3"),h=t("../math/Transform");t("../shapes/ConvexPolyhedron");var c=t("../math/Quaternion");t("../solver/Solver");var u=t("../utils/Vec3Pool"),d=t("../equations/ContactEquation"),f=t("../equations/FrictionEquation");function p(Ue){this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new u,this.world=Ue,this.currentContactMaterial=null,this.enableFrictionReduction=!1}p.prototype.createContactEquation=function(Ue,ke,Je,$e,Wt,bt){var pt;this.contactPointPool.length?(pt=this.contactPointPool.pop(),pt.bi=Ue,pt.bj=ke):pt=new d(Ue,ke),pt.enabled=Ue.collisionResponse&&ke.collisionResponse&&Je.collisionResponse&&$e.collisionResponse;var Tt=this.currentContactMaterial;pt.restitution=Tt.restitution,pt.setSpookParams(Tt.contactEquationStiffness,Tt.contactEquationRelaxation,this.world.dt);var Ne=Je.material||Ue.material,_t=$e.material||ke.material;return Ne&&_t&&Ne.restitution>=0&&_t.restitution>=0&&(pt.restitution=Ne.restitution*_t.restitution),pt.si=Wt||Je,pt.sj=bt||$e,pt},p.prototype.createFrictionEquationsFromContact=function(Ue,ke){var Je=Ue.bi,$e=Ue.bj,Wt=Ue.si,bt=Ue.sj,pt=this.world,Tt=this.currentContactMaterial,Ne=Tt.friction,_t=Wt.material||Je.material,Et=bt.material||$e.material;if(_t&&Et&&_t.friction>=0&&Et.friction>=0&&(Ne=_t.friction*Et.friction),Ne>0){var Nt=Ne*pt.gravity.length(),gt=Je.invMass+$e.invMass;gt>0&&(gt=1/gt);var ct=this.frictionEquationPool,vt=ct.length?ct.pop():new f(Je,$e,Nt*gt),Ht=ct.length?ct.pop():new f(Je,$e,Nt*gt);return vt.bi=Ht.bi=Je,vt.bj=Ht.bj=$e,vt.minForce=Ht.minForce=-Nt*gt,vt.maxForce=Ht.maxForce=Nt*gt,vt.ri.copy(Ue.ri),vt.rj.copy(Ue.rj),Ht.ri.copy(Ue.ri),Ht.rj.copy(Ue.rj),Ue.ni.tangents(vt.t,Ht.t),vt.setSpookParams(Tt.frictionEquationStiffness,Tt.frictionEquationRelaxation,pt.dt),Ht.setSpookParams(Tt.frictionEquationStiffness,Tt.frictionEquationRelaxation,pt.dt),vt.enabled=Ht.enabled=Ue.enabled,ke.push(vt,Ht),!0}return!1};var _=new l,g=new l,v=new l;p.prototype.createFrictionFromAverage=function(Ue){var ke=this.result[this.result.length-1];if(!(!this.createFrictionEquationsFromContact(ke,this.frictionResult)||Ue===1)){var Je=this.frictionResult[this.frictionResult.length-2],$e=this.frictionResult[this.frictionResult.length-1];_.setZero(),g.setZero(),v.setZero();var Wt=ke.bi;ke.bj;for(var bt=0;bt!==Ue;bt++)ke=this.result[this.result.length-1-bt],ke.bodyA!==Wt?(_.vadd(ke.ni,_),g.vadd(ke.ri,g),v.vadd(ke.rj,v)):(_.vsub(ke.ni,_),g.vadd(ke.rj,g),v.vadd(ke.ri,v));var pt=1/Ue;g.scale(pt,Je.ri),v.scale(pt,Je.rj),$e.ri.copy(Je.ri),$e.rj.copy(Je.rj),_.normalize(),_.tangents(Je.t,$e.t)}};var E=new l,C=new l,S=new c,b=new c;p.prototype.getContacts=function(Ue,ke,Je,$e,Wt,bt,pt){this.contactPointPool=Wt,this.frictionEquationPool=pt,this.result=$e,this.frictionResult=bt;for(var Tt=S,Ne=b,_t=E,Et=C,Nt=0,gt=Ue.length;Nt!==gt;Nt++){var ct=Ue[Nt],vt=ke[Nt],Ht=null;ct.material&&vt.material&&(Ht=Je.getContactMaterial(ct.material,vt.material)||null);for(var fi=0;fist.boundingSphereRadius+yi.boundingSphereRadius)){var Is=null;st.material&&yi.material&&(Is=Je.getContactMaterial(st.material,yi.material)||null),this.currentContactMaterial=Is||Ht||Je.defaultContactMaterial;var Di=this[st.type|yi.type];Di&&(st.type0&&Kn<0){gt.vsub(Ne,ct),Nt.copy(Et),Nt.normalize(),qn=ct.dot(Nt),Nt.scale(qn,ct),ct.vadd(Ne,ct);var cn=ct.distanceTo(gt);if(cn0&&$e===!0||Et<=0&&$e===!1){$e===null&&($e=Et>0);continue}else return!1}return!0}var ve=new l,be=new l,Le=new l,Ye=new l,He=[new l,new l,new l,new l,new l,new l],Be=new l,Ge=new l,Lt=new l,Mt=new l;p.prototype[n.types.SPHERE|n.types.BOX]=p.prototype.sphereBox=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=this.v3pool,_t=He;Je.vsub($e,ve),ke.getSideNormals(_t,bt);for(var Et=Ue.radius,Nt=!1,gt=Ge,ct=Lt,vt=Mt,Ht=null,fi=0,st=0,vi=0,yi=null,Is=0,Di=_t.length;Is!==Di&&Nt===!1;Is++){var wi=be;wi.copy(_t[Is]);var ii=wi.norm();wi.normalize();var Kn=ve.dot(wi);if(Kn0){var qn=Le,cn=Ye;qn.copy(_t[(Is+1)%3]),cn.copy(_t[(Is+2)%3]);var Ga=qn.norm(),un=cn.norm();qn.normalize(),cn.normalize();var vs=ve.dot(qn),oo=ve.dot(cn);if(vs-Ga&&oo-un){var yr=Math.abs(Kn-ii-Et);(yi===null||yr0){for(var un=[],vs=0,oo=Di.length;vs!==oo;vs++){var Os=Ne.get();bt.vmult(Nt[Di[vs]],Os),$e.vadd(Os,Os),un.push(Os)}if(ge(un,wi,Je)){vi=!0;var st=this.createContactEquation(pt,Tt,Ue,ke);wi.mult(-gt,st.ri),wi.negate(st.ni);var lo=Ne.get();wi.mult(-cn,lo);var dn=Ne.get();wi.mult(-gt,dn),Je.vsub($e,st.rj),st.rj.vadd(dn,st.rj),st.rj.vadd(lo,st.rj),st.rj.vadd($e,st.rj),st.rj.vsub(Tt.position,st.rj),st.ri.vadd(Je,st.ri),st.ri.vsub(pt.position,st.ri),Ne.release(lo),Ne.release(dn),this.result.push(st),this.createFrictionEquationsFromContact(st,this.frictionResult);for(var vs=0,Hr=un.length;vs!==Hr;vs++)Ne.release(un[vs]);return}else for(var vs=0;vs!==Di.length;vs++){var wr=Ne.get(),Tn=Ne.get();bt.vmult(Nt[Di[(vs+1)%Di.length]],wr),bt.vmult(Nt[Di[(vs+2)%Di.length]],Tn),$e.vadd(wr,wr),$e.vadd(Tn,Tn);var ho=at;Tn.vsub(wr,ho);var li=ei;ho.unit(li);var Zr=Ne.get(),yr=Ne.get();Je.vsub(wr,yr);var rl=yr.dot(li);li.mult(rl,Zr),Zr.vadd(wr,Zr);var Po=Ne.get();if(Zr.vsub(Je,Po),rl>0&&rl*rlUe.boundingSphereRadius+ke.boundingSphereRadius)&&Ue.findSeparatingAxis(ke,Je,Wt,$e,bt,gt,Et,Nt)){var ct=[],vt=Wr;Ue.clipAgainstHull(Je,Wt,ke,$e,bt,gt,-100,100,ct);for(var Ht=0,fi=0;fi!==ct.length;fi++){var st=this.createContactEquation(pt,Tt,Ue,ke,Ne,_t),vi=st.ri,yi=st.rj;gt.negate(st.ni),ct[fi].normal.negate(vt),vt.mult(ct[fi].depth,vt),ct[fi].point.vadd(vt,vi),yi.copy(ct[fi].point),vi.vsub(Je,vi),yi.vsub($e,yi),vi.vadd(Je,vi),vi.vsub(pt.position,vi),yi.vadd($e,yi),yi.vsub(Tt.position,yi),this.result.push(st),Ht++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(st,this.frictionResult)}this.enableFrictionReduction&&Ht&&this.createFrictionFromAverage(Ht)}};var $n=new l,On=new l,vn=new l;p.prototype[n.types.PLANE|n.types.PARTICLE]=p.prototype.planeParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=$n;Ne.set(0,0,1),pt.quaternion.vmult(Ne,Ne);var _t=On;$e.vsub(pt.position,_t);var Et=Ne.dot(_t);if(Et<=0){var Nt=this.createContactEquation(Tt,pt,ke,Ue);Nt.ni.copy(Ne),Nt.ni.negate(Nt.ni),Nt.ri.set(0,0,0);var gt=vn;Ne.mult(Ne.dot($e),gt),$e.vsub(gt,gt),Nt.rj.copy(gt),this.result.push(Nt),this.createFrictionEquationsFromContact(Nt,this.frictionResult)}};var Nn=new l;p.prototype[n.types.PARTICLE|n.types.SPHERE]=p.prototype.sphereParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=Nn;Ne.set(0,0,1),$e.vsub(Je,Ne);var _t=Ne.norm2();if(_t<=Ue.radius*Ue.radius){var Et=this.createContactEquation(Tt,pt,ke,Ue);Ne.normalize(),Et.rj.copy(Ne),Et.rj.mult(Ue.radius,Et.rj),Et.ni.copy(Ne),Et.ni.negate(Et.ni),Et.ri.set(0,0,0),this.result.push(Et),this.createFrictionEquationsFromContact(Et,this.frictionResult)}};var hn=new c,xn=new l;new l;var Qr=new l,ur=new l,da=new l;p.prototype[n.types.PARTICLE|n.types.CONVEXPOLYHEDRON]=p.prototype.convexParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=-1,_t=Qr,Et=da,Nt=null,gt=xn;if(gt.copy($e),gt.vsub(Je,gt),Wt.conjugate(hn),hn.vmult(gt,gt),Ue.pointIsInside(gt)){Ue.worldVerticesNeedsUpdate&&Ue.computeWorldVertices(Je,Wt),Ue.worldFaceNormalsNeedsUpdate&&Ue.computeWorldFaceNormals(Wt);for(var ct=0,vt=Ue.faces.length;ct!==vt;ct++){var Ht=[Ue.worldVertices[Ue.faces[ct][0]]],fi=Ue.worldFaceNormals[ct];$e.vsub(Ht[0],ur);var st=-fi.dot(ur);(Nt===null||Math.abs(st)Ne.length||fi>Ne[0].length)){vt<0&&(vt=0),Ht<0&&(Ht=0),fi<0&&(fi=0),st<0&&(st=0),vt>=Ne.length&&(vt=Ne.length-1),Ht>=Ne.length&&(Ht=Ne.length-1),st>=Ne[0].length&&(st=Ne[0].length-1),fi>=Ne[0].length&&(fi=Ne[0].length-1);var vi=[];ke.getRectMinMax(vt,fi,Ht,st,vi);var yi=vi[0],Is=vi[1];if(!(ct.z-Et>Is||ct.z+EtNe.length||fi>Ne[0].length)){ct<0&&(ct=0),vt<0&&(vt=0),Ht<0&&(Ht=0),fi<0&&(fi=0),ct>=Ne.length&&(ct=Ne.length-1),vt>=Ne.length&&(vt=Ne.length-1),fi>=Ne[0].length&&(fi=Ne[0].length-1),Ht>=Ne[0].length&&(Ht=Ne[0].length-1);var st=[];ke.getRectMinMax(ct,Ht,vt,fi,st);var vi=st[0],yi=st[1];if(!(gt.z-_t>yi||gt.z+_t2)return}}}},{"../collision/AABB":3,"../collision/Ray":9,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43,"../solver/Solver":47,"../utils/Vec3Pool":54}],56:[function(t,i,s){i.exports=S;var r=t("../shapes/Shape"),n=t("../math/Vec3"),a=t("../math/Quaternion"),l=t("../solver/GSSolver");t("../utils/Vec3Pool"),t("../equations/ContactEquation"),t("../equations/FrictionEquation");var h=t("./Narrowphase"),c=t("../utils/EventTarget"),u=t("../collision/ArrayCollisionMatrix"),d=t("../material/Material"),f=t("../material/ContactMaterial"),p=t("../objects/Body"),_=t("../utils/TupleDictionary"),g=t("../collision/RaycastResult"),v=t("../collision/AABB"),E=t("../collision/Ray"),C=t("../collision/NaiveBroadphase");function S(){c.apply(this),this.dt=-1,this.allowSleep=!1,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=0,this.quatNormalizeFast=!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new n,this.broadphase=new C,this.bodies=[],this.solver=new l,this.constraints=[],this.narrowphase=new h(this),this.collisionMatrix=new u,this.collisionMatrixPrevious=new u,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new _,this.defaultMaterial=new d("default"),this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null}}S.prototype=new c,new v;var b=new E;if(S.prototype.getContactMaterial=function(ae,ce){return this.contactMaterialTable.get(ae.id,ce.id)},S.prototype.numObjects=function(){return this.bodies.length},S.prototype.collisionMatrixTick=function(){var ae=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=ae,this.collisionMatrix.reset()},S.prototype.add=S.prototype.addBody=function(ae){this.bodies.indexOf(ae)===-1&&(ae.index=this.bodies.length,this.bodies.push(ae),ae.world=this,ae.initPosition.copy(ae.position),ae.initVelocity.copy(ae.velocity),ae.timeLastSleepy=this.time,ae instanceof p&&(ae.initAngularVelocity.copy(ae.angularVelocity),ae.initQuaternion.copy(ae.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=ae,this.dispatchEvent(this.addBodyEvent))},S.prototype.addConstraint=function(ae){this.constraints.push(ae)},S.prototype.removeConstraint=function(ae){var ce=this.constraints.indexOf(ae);ce!==-1&&this.constraints.splice(ce,1)},S.prototype.rayTest=function(ae,ce,ie){ie instanceof g?this.raycastClosest(ae,ce,{skipBackfaces:!0},ie):this.raycastAll(ae,ce,{skipBackfaces:!0},ie)},S.prototype.raycastAll=function(ae,ce,ie,w){return ie.mode=E.ALL,ie.from=ae,ie.to=ce,ie.callback=w,b.intersectWorld(this,ie)},S.prototype.raycastAny=function(ae,ce,ie,w){return ie.mode=E.ANY,ie.from=ae,ie.to=ce,ie.result=w,b.intersectWorld(this,ie)},S.prototype.raycastClosest=function(ae,ce,ie,w){return ie.mode=E.CLOSEST,ie.from=ae,ie.to=ce,ie.result=w,b.intersectWorld(this,ie)},S.prototype.remove=function(ae){ae.world=null;var ce=this.bodies.length-1,ie=this.bodies,w=ie.indexOf(ae);if(w!==-1){ie.splice(w,1);for(var H=0;H!==ie.length;H++)ie[H].index=H;this.collisionMatrix.setNumObjects(ce),this.removeBodyEvent.body=ae,this.dispatchEvent(this.removeBodyEvent)}},S.prototype.removeBody=S.prototype.remove,S.prototype.addMaterial=function(ae){this.materials.push(ae)},S.prototype.addContactMaterial=function(ae){this.contactmaterials.push(ae),this.contactMaterialTable.set(ae.materials[0].id,ae.materials[1].id,ae)},typeof performance>"u"&&(performance={}),!performance.now){var R=Date.now();performance.timing&&performance.timing.navigationStart&&(R=performance.timing.navigationStart),performance.now=function(){return Date.now()-R}}var I=new n;S.prototype.step=function(ae,ce,ie){if(ie=ie||10,ce=ce||0,ce===0)this.internalStep(ae),this.time+=ae;else{var w=Math.floor((this.time+ce)/ae)-Math.floor(this.time/ae);w=Math.min(w,ie);for(var H=performance.now(),X=0;X!==w&&(this.internalStep(ae),!(performance.now()-H>ae*1e3));X++);this.time+=ce;for(var te=this.time%ae,Q=te/ae,_e=I,q=this.bodies,de=0;de!==q.length;de++){var ge=q[de];ge.type!==p.STATIC&&ge.sleepState!==p.SLEEPING?(ge.position.vsub(ge.previousPosition,_e),_e.scale(Q,_e),ge.position.vadd(_e,ge.interpolatedPosition)):(ge.interpolatedPosition.copy(ge.position),ge.interpolatedQuaternion.copy(ge.quaternion))}}};var N={type:"postStep"},O={type:"preStep"},L={type:"collide",body:null,contact:null},B=[],V=[],Z=[],ue=[];new n,new n,new n,new n,new n,new n,new n,new n,new n,new a;var oe=new a,me=new a,le=new n;S.prototype.internalStep=function(ae){this.dt=ae;var ce=this.contacts,ie=Z,w=ue,H=this.numObjects(),X=this.bodies,te=this.solver,Q=this.gravity,_e=this.doProfiling,q=this.profile,de=p.DYNAMIC,ge,ve=this.constraints,be=V;Q.norm();var Le=Q.x,Ye=Q.y,He=Q.z,Be=0;for(_e&&(ge=performance.now()),Be=0;Be!==H;Be++){var Ge=X[Be];if(Ge.type&de){var Lt=Ge.force,Mt=Ge.mass;Lt.x+=Mt*Le,Lt.y+=Mt*Ye,Lt.z+=Mt*He}}for(var Be=0,Vi=this.subsystems.length;Be!==Vi;Be++)this.subsystems[Be].update();_e&&(ge=performance.now()),ie.length=0,w.length=0,this.broadphase.collisionPairs(this,ie,w),_e&&(q.broadphase=performance.now()-ge);var jr=ve.length;for(Be=0;Be!==jr;Be++){var at=ve[Be];if(!at.collideConnected)for(var ei=ie.length-1;ei>=0;ei-=1)(at.bodyA===ie[ei]&&at.bodyB===w[ei]||at.bodyB===ie[ei]&&at.bodyA===w[ei])&&(ie.splice(ei,1),w.splice(ei,1))}this.collisionMatrixTick(),_e&&(ge=performance.now());var di=B,ci=ce.length;for(Be=0;Be!==ci;Be++)di.push(ce[Be]);ce.length=0;var Yi=this.frictionEquations.length;for(Be=0;Be!==Yi;Be++)be.push(this.frictionEquations[Be]);this.frictionEquations.length=0,this.narrowphase.getContacts(ie,w,this,ce,di,this.frictionEquations,be),_e&&(q.narrowphase=performance.now()-ge),_e&&(ge=performance.now());for(var Be=0;Be=0&&ti.material.friction>=0&&Ge.material.friction*ti.material.friction,Ge.material.restitution>=0&&ti.material.restitution>=0&&(at.restitution=Ge.material.restitution*ti.material.restitution)),te.addEquation(at),Ge.allowSleep&&Ge.type===p.DYNAMIC&&Ge.sleepState===p.SLEEPING&&ti.sleepState===p.AWAKE&&ti.type!==p.STATIC){var br=ti.velocity.norm2()+ti.angularVelocity.norm2(),gn=Math.pow(ti.sleepSpeedLimit,2);br>=gn*2&&(Ge._wakeUpAfterNarrowphase=!0)}if(ti.allowSleep&&ti.type===p.DYNAMIC&&ti.sleepState===p.SLEEPING&&Ge.sleepState===p.AWAKE&&Ge.type!==p.STATIC){var Yn=Ge.velocity.norm2()+Ge.angularVelocity.norm2(),Dn=Math.pow(Ge.sleepSpeedLimit,2);Yn>=Dn*2&&(ti._wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(Ge,ti,!0),this.collisionMatrixPrevious.get(Ge,ti)||(L.body=ti,L.contact=at,Ge.dispatchEvent(L),L.body=Ge,ti.dispatchEvent(L))}for(_e&&(q.makeContactConstraints=performance.now()-ge,ge=performance.now()),Be=0;Be!==H;Be++){var Ge=X[Be];Ge._wakeUpAfterNarrowphase&&(Ge.wakeUp(),Ge._wakeUpAfterNarrowphase=!1)}var jr=ve.length;for(Be=0;Be!==jr;Be++){var at=ve[Be];at.update();for(var ei=0,Wr=at.equations.length;ei!==Wr;ei++){var $n=at.equations[ei];te.addEquation($n)}}te.solve(ae,this),_e&&(q.solve=performance.now()-ge),te.removeAllEquations();var On=Math.pow;for(Be=0;Be!==H;Be++){var Ge=X[Be];if(Ge.type&de){var vn=On(1-Ge.linearDamping,ae),Nn=Ge.velocity;Nn.mult(vn,Nn);var hn=Ge.angularVelocity;if(hn){var xn=On(1-Ge.angularDamping,ae);hn.mult(xn,hn)}}}for(this.dispatchEvent(O),Be=0;Be!==H;Be++){var Ge=X[Be];Ge.preStep&&Ge.preStep.call(Ge)}_e&&(ge=performance.now());var Qr=oe,ur=me,da=this.stepnumber,wn=p.DYNAMIC|p.KINEMATIC,fa=da%(this.quatNormalizeSkip+1)===0,ao=this.quatNormalizeFast,pa=ae*.5;for(r.types.PLANE,r.types.CONVEXPOLYHEDRON,Be=0;Be!==H;Be++){var Zs=X[Be],Ue=Zs.force,ke=Zs.torque;if(Zs.type&wn&&Zs.sleepState!==p.SLEEPING){var Je=Zs.velocity,$e=Zs.angularVelocity,Wt=Zs.position,bt=Zs.quaternion,pt=Zs.invMass,Tt=Zs.invInertiaWorld;Je.x+=Ue.x*pt*ae,Je.y+=Ue.y*pt*ae,Je.z+=Ue.z*pt*ae,Zs.angularVelocity&&(Tt.vmult(ke,le),le.mult(ae,le),le.vadd($e,$e)),Wt.x+=Je.x*ae,Wt.y+=Je.y*ae,Wt.z+=Je.z*ae,Zs.angularVelocity&&(Qr.set($e.x,$e.y,$e.z,0),Qr.mult(bt,ur),bt.x+=pa*ur.x,bt.y+=pa*ur.y,bt.z+=pa*ur.z,bt.w+=pa*ur.w,fa&&(ao?bt.normalizeFast():bt.normalize())),Zs.aabb&&(Zs.aabbNeedsUpdate=!0),Zs.updateInertiaWorld&&Zs.updateInertiaWorld()}}for(this.clearForces(),this.broadphase.dirty=!0,_e&&(q.integrate=performance.now()-ge),this.time+=ae,this.stepnumber+=1,this.dispatchEvent(N),Be=0;Be!==H;Be++){var Ge=X[Be],Ne=Ge.postStep;Ne&&Ne.call(Ge)}if(this.allowSleep)for(Be=0;Be!==H;Be++)X[Be].sleepTick(this.time)},S.prototype.clearForces=function(){for(var ae=this.bodies,ce=ae.length,ie=0;ie!==ce;ie++){var w=ae[ie];w.force,w.torque,w.force.set(0,0,0),w.torque.set(0,0,0)}}},{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../material/ContactMaterial":24,"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Shape":43,"../solver/GSSolver":46,"../utils/EventTarget":49,"../utils/TupleDictionary":52,"../utils/Vec3Pool":54,"./Narrowphase":55}]},{},[2])(2)})})(XC);var NN=XC.exports;const wN=ON(NN);class ks{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}}ks._BabylonFileParsers={};ks._IndividualBabylonFileParsers={};class aa{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,t)&&parseInt(t)===e)return!0;return!1}}aa.Triggers={};class YC{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 FN{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 he{static FromPromise(e,t){const i=new he;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 YC(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new FN(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._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 a of this._observers)if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.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 he;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}class ye{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=e*2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=ye.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=ye.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=ye.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+ye.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=ye.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*ye.Clamp(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=ye.Clamp((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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 RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=ye.TwoPi*Math.floor((e+Math.PI)/ye.TwoPi),e}static HCF(e,t){const i=e%t;return i===0?t:ye.HCF(t,i)}}ye.TwoPi=Math.PI*2;const Qu=1/2.2,__=2.2,Ks=(1+Math.sqrt(5))/2,$t=.001;class js{static BuildArray(e,t){const i=[];for(let s=0;s{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,o[e]=r),s.next=void 0,s.previous=void 0}}const BN=["push","splice","pop","shift","unshift"];function $C(o,e){const t=BN.map(i=>LN(o,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const KC={};function j(o,e){KC[o]=e}function Ds(o){return KC[o]}class Dr{static SetMatrixPrecision(e){if(Dr.MatrixTrackPrecisionChange=!1,e&&!Dr.MatrixUse64Bits&&Dr.MatrixTrackedMatrices)for(let t=0;tparseInt(o.toString().replace(/\W/g,""));class Re{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=kn(this.x),t=kn(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 Re.FromArrayToRef(e,t,this),this}asArray(){const e=[];return this.toArray(e,0),e}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){const t=new this.constructor(0,0);return this.scaleToRef(e,t),t}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=$t){return e&&ye.WithinEpsilon(this.x,e.x,t)&&ye.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){const i=Math.cos(e),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(0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this.x,this.y):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 Re(0,0)}static One(){return new Re(1,1)}static Random(e=0,t=1){return new Re(ye.RandomRange(e,t),ye.RandomRange(e,t))}static get ZeroReadOnly(){return Re._ZeroReadOnly}static FromArray(e,t=0){return new Re(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,s,r){const n=r*r,a=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)*a),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)*a);return new e.constructor(l,h)}static Clamp(e,t,i){let s=e.x;s=s>i.x?i.x:s,s=si.y?i.y:r,r=rt.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 Re.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,a=(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 a>0&&l>0&&a+l<2*r*n}static Distance(e,t){return Math.sqrt(Re.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 Re.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=Re.DistanceSquared(t,i);if(s===0)return Re.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,Re.Dot(e.subtract(t),r)/s)),a=t.add(r.multiplyByFloats(n,n));return Re.Distance(e,a)}}Re._ZeroReadOnly=Re.Zero();class T{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=kn(this._x),t=kn(this._y),i=kn(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){const e=[];return this.toArray(e,0),e}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return T.FromArrayToRef(e,t,this),this}toQuaternion(){return Se.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,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),a=t*Math.sin(i)*Math.sin(s);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,a=e._y,l=e._z,h=e._w,c=2*(a*r-l*s),u=2*(l*i-n*r),d=2*(n*s-a*i);return t._x=i+h*c+a*d-l*u,t._y=s+h*u+l*c-n*d,t._z=r+h*d+n*u-a*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=ot.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=T.Dot(n,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const l=-(T.Dot(t,s)+r)/a,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=$t){return e&&ye.WithinEpsilon(this._x,e._x,t)&&ye.WithinEpsilon(this._y,e._y,t)&&ye.WithinEpsilon(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.divideToRef(e,this)}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!ye.WithinEpsilon(t,i,e))return!0;const s=Math.abs(this._z);return!ye.WithinEpsilon(t,s,e)||!ye.WithinEpsilon(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}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=ot.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(ot.Matrix[0]),T.TransformCoordinatesToRef(this,ot.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ot.Vector3[0]),ot.Vector3[0].rotateByQuaternionToRef(e,ot.Vector3[0]),t.addToRef(ot.Vector3[0],i),i}cross(e){const t=new this.constructor;return T.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.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=T.Dot(e,i),n=T.Dot(t,i);return(r-s)/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(ot.Vector3[1]),r=t.normalizeToRef(ot.Vector3[2]);let n=T.Dot(s,r);n=ye.Clamp(n,-1,1);const a=Math.acos(n),l=ot.Vector3[3];return T.CrossToRef(s,r,l),T.Dot(l,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){ot.Vector3[0].copyFrom(e);const s=ot.Vector3[0];ot.Vector3[1].copyFrom(t);const r=ot.Vector3[1];ot.Vector3[2].copyFrom(i);const n=ot.Vector3[2],a=ot.Vector3[3],l=ot.Vector3[4];s.normalize(),r.normalize(),n.normalize(),T.CrossToRef(n,s,a),T.CrossToRef(a,n,l);const h=Math.atan2(T.Dot(r,a),T.Dot(r,l));return ye.NormalizeRadians(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=K.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=T.Zero();return T.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ye.Clamp(i,0,1);const r=ot.Vector3[0],n=ot.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),n.copyFrom(t);const l=n.length();n.normalizeFromLength(l);const h=T.Dot(r,n);let c,u;if(h<1-$t){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(ye.Lerp(a,l,i)),s}static SmoothToRef(e,t,i,s,r){return T.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new T(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return T.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 T.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new T(0,0,0)}static One(){return new T(1,1,1)}static Up(){return new T(0,1,0)}static get UpReadOnly(){return T._UpReadOnly}static get DownReadOnly(){return T._DownReadOnly}static get RightReadOnly(){return T._RightReadOnly}static get LeftReadOnly(){return T._LeftReadOnly}static get LeftHandedForwardReadOnly(){return T._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return T._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return T._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return T._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return T._ZeroReadOnly}static get OneReadOnly(){return T._OneReadOnly}static Down(){return new T(0,-1,0)}static Forward(e=!1){return new T(0,0,e?-1:1)}static Backward(e=!1){return new T(0,0,e?1:-1)}static Right(){return new T(1,0,0)}static Left(){return new T(-1,0,0)}static Random(e=0,t=1){return new T(ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t))}static TransformCoordinates(e,t){const i=T.Zero();return T.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return T.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=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=a*c,r._y=l*c,r._z=h*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=T.Zero();return T.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,a=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)*a),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)*a),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)*a);return new e.constructor(l,h,c)}static Clamp(e,t,i){const s=new e.constructor;return T.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:a,a=a0&&L<0?(V.copyFrom(n),Z=t,ue=i):L>0&&B<0?(V.copyFrom(l),Z=i,ue=s):(V.copyFrom(a).scaleInPlace(-1),Z=s,ue=t);const oe=ot.Vector3[9],me=ot.Vector3[4];if(Z.subtractToRef(E,R),ue.subtractToRef(E,oe),T.CrossToRef(R,oe,me),!(T.Dot(me,h)<0))return r.copyFrom(E),Math.abs(_*g);const ae=ot.Vector3[5];T.CrossToRef(V,me,ae),ae.normalize();const ce=ot.Vector3[9];ce.copyFrom(Z).subtractInPlace(E);const ie=ce.length();if(ie<$t)return r.copyFrom(Z),T.Distance(e,Z);ce.normalizeFromLength(ie);const w=T.Dot(ae,ce),H=ot.Vector3[7];H.copyFrom(E).addInPlace(ae.scaleInPlace(ie*w)),R.copyFrom(H).subtractInPlace(Z),_=V.length(),V.normalizeFromLength(_);let X=T.Dot(R,V)/Math.max(_,$t);return X=ye.Clamp(X,0,1),H.copyFrom(Z).addInPlace(V.scaleInPlace(X*_)),r.copyFrom(H),T.Distance(e,H)}static Center(e,t){return T.CenterToRef(e,t,T.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 T.RotationFromAxisToRef(e,t,i,s),s}static RotationFromAxisToRef(e,t,i,s){const r=ot.Quaternion[0];return Se.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(s),s}}T._UpReadOnly=T.Up();T._DownReadOnly=T.Down();T._LeftHandedForwardReadOnly=T.Forward(!1);T._RightHandedForwardReadOnly=T.Forward(!0);T._LeftHandedBackwardReadOnly=T.Backward(!1);T._RightHandedBackwardReadOnly=T.Backward(!0);T._RightReadOnly=T.Right();T._LeftReadOnly=T.Left();T._ZeroReadOnly=T.Zero();T._OneReadOnly=T.One();class Dt{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=kn(this.x),t=kn(this.y),i=kn(this.z),s=kn(this.w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){const e=[];return this.toArray(e,0),e}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 Dt.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}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=$t){return e&&ye.WithinEpsilon(this.x,e.x,t)&&ye.WithinEpsilon(this.y,e.y,t)&&ye.WithinEpsilon(this.z,e.z,t)&&ye.WithinEpsilon(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.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){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,0);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)}toVector3(){return new T(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 Dt(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 Dt.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 Dt(0,0,0,0)}static One(){return new Dt(1,1,1,1)}static Random(e=0,t=1){return new Dt(ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t))}static get ZeroReadOnly(){return Dt._ZeroReadOnly}static Normalize(e){const t=Dt.Zero();return Dt.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(Dt.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 Dt.CenterToRef(e,t,Dt.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=Dt.Zero();return Dt.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Dt.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=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=a,r.y=l,r.z=h,r.w=c,r}static TransformNormal(e,t){const i=new e.constructor;return Dt.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],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=s,n}static FromVector3(e,t=0){return new Dt(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}Dt._ZeroReadOnly=Dt.Zero();class Se{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=kn(this._x),t=kn(this._y),i=kn(this._z),s=kn(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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=$t){return e&&ye.WithinEpsilon(this._x,e._x,t)&&ye.WithinEpsilon(this._y,e._y,t)&&ye.WithinEpsilon(this._z,e._z,t)&&ye.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,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)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,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),this}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 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=T.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,a=.4999999;if(n<-a)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)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 k.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return Se.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 Se;return Se.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[1],l=i[5],h=i[9],c=i[2],u=i[6],d=i[10],f=s+l+d;let p;return f>0?(p=.5/Math.sqrt(f+1),t._w=.25/p,t._x=(u-h)*p,t._y=(n-c)*p,t._z=(a-r)*p,t._isDirty=!0):s>l&&s>d?(p=2*Math.sqrt(1+s-l-d),t._w=(u-h)/p,t._x=.25*p,t._y=(r+a)/p,t._z=(n+c)/p,t._isDirty=!0):l>d?(p=2*Math.sqrt(1+l-s-d),t._w=(n-c)/p,t._x=(r+a)/p,t._y=.25*p,t._z=(h+u)/p,t._isDirty=!0):(p=2*Math.sqrt(1+d-s-l),t._w=(a-r)/p,t._x=(n+c)/p,t._y=(h+u)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=Se.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=ye.Clamp(n,0,1),Se.SlerpToRef(e,t,n,r),r}static Zero(){return new Se(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 Se(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 Se.RotationAxisToRef(e,t,new Se)}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 Se(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromEulerAngles(e,t,i){const s=new Se;return Se.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return Se.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new Se;return Se.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return Se.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=$t){const r=T.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(T.CrossToRef(e,t,K.Vector3[0]),i.set(K.Vector3[0].x,K.Vector3[0].y,K.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new Se;return Se.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,a=e*.5,l=Math.sin(r),h=Math.cos(r),c=Math.sin(n),u=Math.cos(n),d=Math.sin(a),f=Math.cos(a);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 Se;return Se.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,a=t*.5;return s._x=Math.cos(n)*Math.sin(a),s._y=Math.sin(n)*Math.sin(a),s._z=Math.sin(r)*Math.cos(a),s._w=Math.cos(r)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new Se(0,0,0,0);return Se.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=ot.Matrix[0];return k.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),Se.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new Se;return Se.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=ot.Matrix[0];return k.LookDirectionLHToRef(e,t,s),Se.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new Se;return Se.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=ot.Matrix[0];return k.LookDirectionRHToRef(e,t,s),Se.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=Se.Identity();return Se.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(a<0&&(l=!0,a=-a),a>.999999)n=1-i,r=l?-i:i;else{const h=Math.acos(a),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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e._z*l+i._z*h+t._z*c+s._z*u,_=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 a=r*r;return n._x=(a-r)*6*e._x+(3*a-4*r+1)*t._x+(-a+r)*6*i._x+(3*a-2*r)*s._x,n._y=(a-r)*6*e._y+(3*a-4*r+1)*t._y+(-a+r)*6*i._y+(3*a-2*r)*s._y,n._z=(a-r)*6*e._z+(3*a-4*r+1)*t._z+(-a+r)*6*i._z+(3*a-2*r)*s._z,n._w=(a-r)*6*e._w+(3*a-4*r+1)*t._w+(-a+r)*6*i._w+(3*a-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=Se.Zero();return Se.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}}class k{static get Use64Bits(){return Dr.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=k._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,Dr.MatrixTrackPrecisionChange&&Dr.MatrixTrackedMatrices.push(this),this._m=new Dr.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],a=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],f=e[11],p=e[12],_=e[13],g=e[14],v=e[15],E=d*v-g*f,C=u*v-_*f,S=u*g-_*d,b=c*v-p*f,R=c*g-d*p,I=c*_-p*u,N=+(a*E-l*C+h*S),O=-(n*E-l*b+h*R),L=+(n*C-a*b+h*I),B=-(n*S-a*R+l*I);return t*N+i*O+s*L+r*B}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +var NN=Object.defineProperty;var wN=(o,e,t)=>e in o?NN(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var wt=(o,e,t)=>(wN(o,typeof e!="symbol"?e+"":e,t),t);(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)}})();var Yu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function FN(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}function i_(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var $C={exports:{}};(function(o,e){(function(t){o.exports=t()})(function(){return function t(i,s,r){function n(h,c){if(!s[h]){if(!i[h]){var u=typeof i_=="function"&&i_;if(!c&&u)return u(h,!0);if(a)return a(h,!0);throw new Error("Cannot find module '"+h+"'")}var d=s[h]={exports:{}};i[h][0].call(d.exports,function(f){var p=i[h][1][f];return n(p||f)},d,d.exports,t,i,s,r)}return s[h].exports}for(var a=typeof i_=="function"&&i_,l=0;l (http://steffe.se)",keywords:["cannon.js","cannon","physics","engine","3d"],main:"./build/cannon.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/cannon.js.git"},bugs:{url:"https://github.com/schteppe/cannon.js/issues"},licenses:[{type:"MIT"}],devDependencies:{jshint:"latest","uglify-js":"latest",nodeunit:"^0.9.0",grunt:"~0.4.0","grunt-contrib-jshint":"~0.1.1","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-concat":"~0.1.3","grunt-contrib-uglify":"^0.5.1","grunt-browserify":"^2.1.4","grunt-contrib-yuidoc":"^0.5.2",browserify:"*"},dependencies:{}}},{}],2:[function(t,i,s){i.exports={version:t("../package.json").version,AABB:t("./collision/AABB"),ArrayCollisionMatrix:t("./collision/ArrayCollisionMatrix"),Body:t("./objects/Body"),Box:t("./shapes/Box"),Broadphase:t("./collision/Broadphase"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),Narrowphase:t("./world/Narrowphase"),ConeTwistConstraint:t("./constraints/ConeTwistConstraint"),ContactMaterial:t("./material/ContactMaterial"),ConvexPolyhedron:t("./shapes/ConvexPolyhedron"),Cylinder:t("./shapes/Cylinder"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventTarget:t("./utils/EventTarget"),FrictionEquation:t("./equations/FrictionEquation"),GSSolver:t("./solver/GSSolver"),GridBroadphase:t("./collision/GridBroadphase"),Heightfield:t("./shapes/Heightfield"),HingeConstraint:t("./constraints/HingeConstraint"),LockConstraint:t("./constraints/LockConstraint"),Mat3:t("./math/Mat3"),Material:t("./material/Material"),NaiveBroadphase:t("./collision/NaiveBroadphase"),ObjectCollisionMatrix:t("./collision/ObjectCollisionMatrix"),Pool:t("./utils/Pool"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),PointToPointConstraint:t("./constraints/PointToPointConstraint"),Quaternion:t("./math/Quaternion"),Ray:t("./collision/Ray"),RaycastVehicle:t("./objects/RaycastVehicle"),RaycastResult:t("./collision/RaycastResult"),RigidVehicle:t("./objects/RigidVehicle"),RotationalEquation:t("./equations/RotationalEquation"),RotationalMotorEquation:t("./equations/RotationalMotorEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),SPHSystem:t("./objects/SPHSystem"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Sphere:t("./shapes/Sphere"),SplitSolver:t("./solver/SplitSolver"),Spring:t("./objects/Spring"),Trimesh:t("./shapes/Trimesh"),Vec3:t("./math/Vec3"),Vec3Pool:t("./utils/Vec3Pool"),World:t("./world/World")}},{"../package.json":1,"./collision/AABB":3,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/ConeTwistConstraint":12,"./constraints/Constraint":13,"./constraints/DistanceConstraint":14,"./constraints/HingeConstraint":15,"./constraints/LockConstraint":16,"./constraints/PointToPointConstraint":17,"./equations/ContactEquation":19,"./equations/Equation":20,"./equations/FrictionEquation":21,"./equations/RotationalEquation":22,"./equations/RotationalMotorEquation":23,"./material/ContactMaterial":24,"./material/Material":25,"./math/Mat3":27,"./math/Quaternion":28,"./math/Vec3":30,"./objects/Body":31,"./objects/RaycastVehicle":32,"./objects/RigidVehicle":33,"./objects/SPHSystem":34,"./objects/Spring":35,"./shapes/Box":37,"./shapes/ConvexPolyhedron":38,"./shapes/Cylinder":39,"./shapes/Heightfield":40,"./shapes/Particle":41,"./shapes/Plane":42,"./shapes/Shape":43,"./shapes/Sphere":44,"./shapes/Trimesh":45,"./solver/GSSolver":46,"./solver/Solver":47,"./solver/SplitSolver":48,"./utils/EventTarget":49,"./utils/Pool":51,"./utils/Vec3Pool":54,"./world/Narrowphase":55,"./world/World":56}],3:[function(t,i,s){var r=t("../math/Vec3");t("../utils/Utils"),i.exports=n;function n(h){h=h||{},this.lowerBound=new r,h.lowerBound&&this.lowerBound.copy(h.lowerBound),this.upperBound=new r,h.upperBound&&this.upperBound.copy(h.upperBound)}var a=new r;n.prototype.setFromPoints=function(h,c,u,d){var f=this.lowerBound,p=this.upperBound,_=u;f.copy(h[0]),_&&_.vmult(f,f),p.copy(f);for(var g=1;gp.x&&(p.x=v.x),v.xp.y&&(p.y=v.y),v.yp.z&&(p.z=v.z),v.zc&&(this.lowerBound.x=c);var u=h.upperBound.x;this.upperBound.xc&&(this.lowerBound.y=c);var u=h.upperBound.y;this.upperBound.yc&&(this.lowerBound.z=c);var u=h.upperBound.z;this.upperBound.z=f.x&&c.y<=d.y&&u.y>=f.y&&c.z<=d.z&&u.z>=f.z},n.prototype.getCorners=function(h,c,u,d,f,p,_,g){var v=this.lowerBound,E=this.upperBound;h.copy(v),c.set(E.x,v.y,v.z),u.set(E.x,E.y,v.z),d.set(v.x,E.y,E.z),f.set(E.x,v.y,v.z),p.set(v.x,E.y,v.z),_.set(v.x,v.y,E.z),g.copy(E)};var l=[new r,new r,new r,new r,new r,new r,new r,new r];n.prototype.toLocalFrame=function(h,c){var u=l,d=u[0],f=u[1],p=u[2],_=u[3],g=u[4],v=u[5],E=u[6],C=u[7];this.getCorners(d,f,p,_,g,v,E,C);for(var S=0;S!==8;S++){var b=u[S];h.pointToLocal(b,b)}return c.setFromPoints(u)},n.prototype.toWorldFrame=function(h,c){var u=l,d=u[0],f=u[1],p=u[2],_=u[3],g=u[4],v=u[5],E=u[6],C=u[7];this.getCorners(d,f,p,_,g,v,E,C);for(var S=0;S!==8;S++){var b=u[S];h.pointToWorld(b,b)}return c.setFromPoints(u)}},{"../math/Vec3":30,"../utils/Utils":53}],4:[function(t,i,s){i.exports=r;function r(){this.matrix=[]}r.prototype.get=function(n,a){if(n=n.index,a=a.index,a>n){var l=a;a=n,n=l}return this.matrix[(n*(n+1)>>1)+a-1]},r.prototype.set=function(n,a,l){if(n=n.index,a=a.index,a>n){var h=a;a=n,n=h}this.matrix[(n*(n+1)>>1)+a-1]=l?1:0},r.prototype.reset=function(){for(var n=0,a=this.matrix.length;n!==a;n++)this.matrix[n]=0},r.prototype.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1}},{}],5:[function(t,i,s){var r=t("../objects/Body"),n=t("../math/Vec3"),a=t("../math/Quaternion");t("../shapes/Shape"),t("../shapes/Plane"),i.exports=l;function l(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}l.prototype.collisionPairs=function(_,g,v){throw new Error("collisionPairs not implemented for this BroadPhase class!")};var h=r.STATIC|r.KINEMATIC;l.prototype.needBroadphaseCollision=function(_,g){return!(!(_.collisionFilterGroup&g.collisionFilterMask)||!(g.collisionFilterGroup&_.collisionFilterMask)||(_.type&h||_.sleepState===r.SLEEPING)&&(g.type&h||g.sleepState===r.SLEEPING))},l.prototype.intersectionTest=function(_,g,v,E){this.useBoundingBoxes?this.doBoundingBoxBroadphase(_,g,v,E):this.doBoundingSphereBroadphase(_,g,v,E)};var c=new n;new n,new a,new n,l.prototype.doBoundingSphereBroadphase=function(_,g,v,E){var C=c;g.position.vsub(_.position,C);var S=Math.pow(_.boundingRadius+g.boundingRadius,2),b=C.norm2();bv.norm2()},l.prototype.aabbQuery=function(_,g,v){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(t,i,s){i.exports=l;var r=t("./Broadphase"),n=t("../math/Vec3"),a=t("../shapes/Shape");function l(c,u,d,f,p){r.apply(this),this.nx=d||10,this.ny=f||10,this.nz=p||10,this.aabbMin=c||new n(100,100,100),this.aabbMax=u||new n(-100,-100,-100);var _=this.nx*this.ny*this.nz;if(_<=0)throw"GridBroadphase: Each dimension's n must be >0";this.bins=[],this.binLengths=[],this.bins.length=_,this.binLengths.length=_;for(var g=0;g<_;g++)this.bins[g]=[],this.binLengths[g]=0}l.prototype=new r,l.prototype.constructor=l;var h=new n;new n,l.prototype.collisionPairs=function(c,u,d){var f=c.numObjects(),p=c.bodies,q=this.aabbMax,_e=this.aabbMin,_=this.nx,g=this.ny,v=this.nz,E=g*v,C=v,S=1,b=q.x,R=q.y,I=q.z,N=_e.x,O=_e.y,L=_e.z,B=_/(b-N),V=g/(R-O),Z=v/(I-L),ue=(b-N)/_,oe=(R-O)/g,me=(I-L)/v,le=Math.sqrt(ue*ue+oe*oe+me*me)*.5,ae=a.types,ce=ae.SPHERE,ie=ae.PLANE;ae.BOX,ae.COMPOUND,ae.CONVEXPOLYHEDRON;for(var w=this.bins,H=this.binLengths,X=this.bins.length,te=0;te!==X;te++)H[te]=0;var Q=Math.ceil,_e=Math.min,q=Math.max;function de(vn,Yn,Dn,jr,Wr,$n,On){var xn=(vn-N)*B|0,Nn=(Yn-O)*V|0,hn=(Dn-L)*Z|0,Tn=Q((jr-N)*B),Qr=Q((Wr-O)*V),ur=Q(($n-L)*Z);xn<0?xn=0:xn>=_&&(xn=_-1),Nn<0?Nn=0:Nn>=g&&(Nn=g-1),hn<0?hn=0:hn>=v&&(hn=v-1),Tn<0?Tn=0:Tn>=_&&(Tn=_-1),Qr<0?Qr=0:Qr>=g&&(Qr=g-1),ur<0?ur=0:ur>=v&&(ur=v-1),xn*=E,Nn*=C,hn*=S,Tn*=E,Qr*=C,ur*=S;for(var da=xn;da<=Tn;da+=E)for(var wn=Nn;wn<=Qr;wn+=C)for(var fa=hn;fa<=ur;fa+=S){var ao=da+wn+fa;w[ao][H[ao]++]=On}}for(var te=0;te!==f;te++){var ge=p[te],ve=ge.shape;switch(ve.type){case ce:var be=ge.position.x,Le=ge.position.y,Ye=ge.position.z,He=ve.radius;de(be-He,Le-He,Ye-He,be+He,Le+He,Ye+He,ge);break;case ie:ve.worldNormalNeedsUpdate&&ve.computeWorldNormal(ge.quaternion);var Be=ve.worldNormal,Ge=N+ue*.5-ge.position.x,Bt=O+oe*.5-ge.position.y,Mt=L+me*.5-ge.position.z,Vi=h;Vi.set(Ge,Bt,Mt);for(var at=0,ei=0;at!==_;at++,ei+=E,Vi.y=Bt,Vi.x+=ue)for(var di=0,ci=0;di!==g;di++,ci+=C,Vi.z=Mt,Vi.y+=oe)for(var Yi=0,Zt=0;Yi!==v;Yi++,Zt+=S,Vi.z+=me)if(Vi.dot(Be)1)for(var gs=w[te],at=0;at!==ti;at++)for(var ge=gs[at],di=0;di!==at;di++){var br=gs[di];this.needBroadphaseCollision(ge,br)&&this.intersectionTest(ge,br,u,d)}}this.makePairsUnique(u,d)}},{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(t,i,s){i.exports=a;var r=t("./Broadphase"),n=t("./AABB");function a(){r.apply(this)}a.prototype=new r,a.prototype.constructor=a,a.prototype.collisionPairs=function(l,h,c){var u=l.bodies,d=u.length,f,p,_,g;for(f=0;f!==d;f++)for(p=0;p!==f;p++)_=u[f],g=u[p],this.needBroadphaseCollision(_,g)&&this.intersectionTest(_,g,h,c)},new n,a.prototype.aabbQuery=function(l,h,c){c=c||[];for(var u=0;un){var l=a;a=n,n=l}return n+"-"+a in this.matrix},r.prototype.set=function(n,a,l){if(n=n.id,a=a.id,a>n){var h=a;a=n,n=h}l?this.matrix[n+"-"+a]=!0:delete this.matrix[n+"-"+a]},r.prototype.reset=function(){this.matrix={}},r.prototype.setNumObjects=function(n){}},{}],9:[function(t,i,s){i.exports=u;var r=t("../math/Vec3"),n=t("../math/Quaternion"),a=t("../math/Transform");t("../shapes/ConvexPolyhedron"),t("../shapes/Box");var l=t("../collision/RaycastResult"),h=t("../shapes/Shape"),c=t("../collision/AABB");function u(X,te){this.from=X?X.clone():new r,this.to=te?te.clone():new r,this._direction=new r,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=u.ANY,this.result=new l,this.hasHit=!1,this.callback=function(Q){}}u.prototype.constructor=u,u.CLOSEST=1,u.ANY=2,u.ALL=4;var d=new c,f=[];u.prototype.intersectWorld=function(X,te){return this.mode=te.mode||u.ANY,this.result=te.result||new l,this.skipBackfaces=!!te.skipBackfaces,this.collisionFilterMask=typeof te.collisionFilterMask<"u"?te.collisionFilterMask:-1,this.collisionFilterGroup=typeof te.collisionFilterGroup<"u"?te.collisionFilterGroup:-1,te.from&&this.from.copy(te.from),te.to&&this.to.copy(te.to),this.callback=te.callback||function(){},this.hasHit=!1,this.result.reset(),this._updateDirection(),this.getAABB(d),f.length=0,X.broadphase.aabbQuery(X,d,f),this.intersectBodies(f),this.hasHit};var p=new r,_=new r;u.pointInTriangle=g;function g(X,te,Q,_e){_e.vsub(te,ie),Q.vsub(te,p),X.vsub(te,_);var q=ie.dot(ie),de=ie.dot(p),ge=ie.dot(_),ve=p.dot(p),be=p.dot(_),Le,Ye;return(Le=ve*ge-de*be)>=0&&(Ye=q*be-de*ge)>=0&&Le+YeX.boundingSphereRadius)){var ge=this[X.type];ge&&ge.call(this,X,te,Q,_e)}},new r,new r;var C=new r,S=new r,b=new r,R=new r;new r,new l,u.prototype.intersectBox=function(X,te,Q,_e){return this.intersectConvex(X.convexPolyhedronRepresentation,te,Q,_e)},u.prototype[h.types.BOX]=u.prototype.intersectBox,u.prototype.intersectPlane=function(X,te,Q,_e){var q=this.from,de=this.to,ge=this._direction,ve=new r(0,0,1);te.vmult(ve,ve);var be=new r;q.vsub(Q,be);var Le=be.dot(ve);de.vsub(Q,be);var Ye=be.dot(ve);if(!(Le*Ye>0)&&!(q.distanceTo(de)Le)&&(Le=ge[0]),(be===null||ge[1]Ye)&&(Ye=ge[1])),ve!==null){var Be=[];X.getRectMinMax(ve,be,Le,Ye,Be),Be[0],Be[1];for(var Ge=ve;Ge<=Le;Ge++)for(var Bt=be;Bt<=Ye;Bt++){if(this.result._shouldStop||(X.getConvexTrianglePillar(Ge,Bt,!1),a.pointToWorldFrame(Q,te,X.pillarOffset,q),this.intersectConvex(X.pillarConvex,te,q,_e,I),this.result._shouldStop))return;X.getConvexTrianglePillar(Ge,Bt,!0),a.pointToWorldFrame(Q,te,X.pillarOffset,q),this.intersectConvex(X.pillarConvex,te,q,_e,I)}}},u.prototype[h.types.HEIGHTFIELD]=u.prototype.intersectHeightfield;var N=new r,O=new r;u.prototype.intersectSphere=function(X,te,Q,_e){var q=this.from,de=this.to,ge=X.radius,ve=Math.pow(de.x-q.x,2)+Math.pow(de.y-q.y,2)+Math.pow(de.z-q.z,2),be=2*((de.x-q.x)*(q.x-Q.x)+(de.y-q.y)*(q.y-Q.y)+(de.z-q.z)*(q.z-Q.z)),Le=Math.pow(q.x-Q.x,2)+Math.pow(q.y-Q.y,2)+Math.pow(q.z-Q.z,2)-Math.pow(ge,2),Ye=Math.pow(be,2)-4*ve*Le,He=N,Be=O;if(!(Ye<0))if(Ye===0)q.lerp(de,Ye,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1);else{var Ge=(-be-Math.sqrt(Ye))/(2*ve),Bt=(-be+Math.sqrt(Ye))/(2*ve);if(Ge>=0&&Ge<=1&&(q.lerp(de,Ge,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1)),this.result._shouldStop)return;Bt>=0&&Bt<=1&&(q.lerp(de,Bt,He),He.vsub(Q,Be),Be.normalize(),this.reportIntersection(Be,He,X,_e,-1))}},u.prototype[h.types.SPHERE]=u.prototype.intersectSphere;var L=new r;new r,new r;var B=new r;u.prototype.intersectConvex=function(te,Q,_e,q,de){for(var ge=L,ve=B,be=de&&de.faceList||null,Le=te.faces,Ye=te.vertices,He=te.faceNormals,Be=this._direction,Ge=this.from,Bt=this.to,Mt=Ge.distanceTo(Bt),Vi=be?be.length:Le.length,at=this.result,ei=0;!at._shouldStop&&eiMt||this.reportIntersection(ge,C,te,q,di)}}}}},u.prototype[h.types.CONVEXPOLYHEDRON]=u.prototype.intersectConvex;var V=new r,Z=new r,ue=new r,oe=new r,me=new r,le=new r;new c;var ae=[],ce=new a;u.prototype.intersectTrimesh=function(te,Q,_e,q,de){var ge=V,ve=ae,be=ce,Le=B,Ye=Z,He=ue,Be=oe,Ge=le,Bt=me;de&&de.faceList;var Mt=te.indices;te.vertices,te.faceNormals;var Vi=this.from,at=this.to,ei=this._direction;be.position.copy(_e),be.quaternion.copy(Q),a.vectorToLocalFrame(_e,Q,ei,Ye),a.pointToLocalFrame(_e,Q,Vi,He),a.pointToLocalFrame(_e,Q,at,Be);var di=He.distanceSquared(Be);te.tree.rayQuery(this,be,ve);for(var ci=0,Yi=ve.length;!this.result._shouldStop&&ci!==Yi;ci++){var Zt=ve[ci];te.getNormal(Zt,ge),te.getVertex(Mt[Zt*3],S),S.vsub(He,Le);var zi=Ye.dot(ge),ti=ge.dot(Le)/zi;if(!(ti<0)){Ye.scale(ti,C),C.vadd(He,C),te.getVertex(Mt[Zt*3+1],b),te.getVertex(Mt[Zt*3+2],R);var gs=C.distanceSquared(He);!(g(C,b,S,R)||g(C,S,b,R))||gs>di||(a.vectorToWorldFrame(Q,ge,Bt),a.pointToWorldFrame(_e,Q,C,Ge),this.reportIntersection(Bt,Ge,te,q,Zt))}}ve.length=0},u.prototype[h.types.TRIMESH]=u.prototype.intersectTrimesh,u.prototype.reportIntersection=function(X,te,Q,_e,q){var de=this.from,ge=this.to,ve=de.distanceTo(te),be=this.result;if(!(this.skipBackfaces&&X.dot(this._direction)>0))switch(be.hitFaceIndex=typeof q<"u"?q:-1,this.mode){case u.ALL:this.hasHit=!0,be.set(de,ge,X,te,Q,_e,ve),be.hasHit=!0,this.callback(be);break;case u.CLOSEST:(ve=0&&!(a[u].aabb.lowerBound.x<=c.aabb.lowerBound.x);u--)a[u+1]=a[u];a[u+1]=c}return a},n.insertionSortY=function(a){for(var l=1,h=a.length;l=0&&!(a[u].aabb.lowerBound.y<=c.aabb.lowerBound.y);u--)a[u+1]=a[u];a[u+1]=c}return a},n.insertionSortZ=function(a){for(var l=1,h=a.length;l=0&&!(a[u].aabb.lowerBound.z<=c.aabb.lowerBound.z);u--)a[u+1]=a[u];a[u+1]=c}return a},n.prototype.collisionPairs=function(a,l,h){var c=this.axisList,u=c.length,d=this.axisIndex,f,p;for(this.dirty&&(this.sortList(),this.dirty=!1),f=0;f!==u;f++){var _=c[f];for(p=f+1;pR?b>I?this.axisIndex=0:this.axisIndex=2:R>I?this.axisIndex=1:this.axisIndex=2},n.prototype.aabbQuery=function(a,l,h){h=h||[],this.dirty&&(this.sortList(),this.dirty=!1);var c=this.axisIndex,u="x";c===1&&(u="y"),c===2&&(u="z");var d=this.axisList;l.lowerBound[u],l.upperBound[u];for(var f=0;f"u"&&(c=l.position.distanceTo(h.position)),typeof u>"u"&&(u=1e6),this.distance=c;var d=this.distanceEquation=new n(l,h);this.equations.push(d),d.minForce=-u,d.maxForce=u}a.prototype=new r,a.prototype.update=function(){var l=this.bodyA,h=this.bodyB,c=this.distanceEquation,u=this.distance*.5,d=c.ni;h.position.vsub(l.position,d),d.normalize(),d.mult(u,c.ri),d.mult(-u,c.rj)}},{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(t,i,s){i.exports=h,t("./Constraint");var r=t("./PointToPointConstraint"),n=t("../equations/RotationalEquation"),a=t("../equations/RotationalMotorEquation");t("../equations/ContactEquation");var l=t("../math/Vec3");function h(d,f,p){p=p||{};var _=typeof p.maxForce<"u"?p.maxForce:1e6,g=p.pivotA?p.pivotA.clone():new l,v=p.pivotB?p.pivotB.clone():new l;r.call(this,d,g,f,v,_);var E=this.axisA=p.axisA?p.axisA.clone():new l(1,0,0);E.normalize();var C=this.axisB=p.axisB?p.axisB.clone():new l(1,0,0);C.normalize();var S=this.rotationalEquation1=new n(d,f,p),b=this.rotationalEquation2=new n(d,f,p),R=this.motorEquation=new a(d,f,_);R.enabled=!1,this.equations.push(S,b,R)}h.prototype=new r,h.constructor=h,h.prototype.enableMotor=function(){this.motorEquation.enabled=!0},h.prototype.disableMotor=function(){this.motorEquation.enabled=!1},h.prototype.setMotorSpeed=function(d){this.motorEquation.targetVelocity=d},h.prototype.setMotorMaxForce=function(d){this.motorEquation.maxForce=d,this.motorEquation.minForce=-d};var c=new l,u=new l;h.prototype.update=function(){var d=this.bodyA,f=this.bodyB,p=this.motorEquation,_=this.rotationalEquation1,g=this.rotationalEquation2,v=c,E=u,C=this.axisA,S=this.axisB;r.prototype.update.call(this),d.quaternion.vmult(C,v),f.quaternion.vmult(S,E),v.tangents(_.axisA,g.axisA),_.axisB.copy(E),g.axisB.copy(E),this.motorEquation.enabled&&(d.quaternion.vmult(this.axisA,p.axisA),f.quaternion.vmult(this.axisB,p.axisB))}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(t,i,s){i.exports=l,t("./Constraint");var r=t("./PointToPointConstraint"),n=t("../equations/RotationalEquation");t("../equations/RotationalMotorEquation"),t("../equations/ContactEquation");var a=t("../math/Vec3");function l(h,c,u){u=u||{};var d=typeof u.maxForce<"u"?u.maxForce:1e6,f=new a,p=new a,_=new a;h.position.vadd(c.position,_),_.scale(.5,_),c.pointToLocalFrame(_,p),h.pointToLocalFrame(_,f),r.call(this,h,f,c,p,d);var g=this.rotationalEquation1=new n(h,c,u),v=this.rotationalEquation2=new n(h,c,u),E=this.rotationalEquation3=new n(h,c,u);this.equations.push(g,v,E)}l.prototype=new r,l.constructor=l,new a,new a,l.prototype.update=function(){var h=this.bodyA,c=this.bodyB;this.motorEquation;var u=this.rotationalEquation1,d=this.rotationalEquation2,f=this.rotationalEquation3;r.prototype.update.call(this),h.vectorToWorldFrame(a.UNIT_X,u.axisA),c.vectorToWorldFrame(a.UNIT_Y,u.axisB),h.vectorToWorldFrame(a.UNIT_Y,d.axisA),c.vectorToWorldFrame(a.UNIT_Z,d.axisB),h.vectorToWorldFrame(a.UNIT_Z,f.axisA),c.vectorToWorldFrame(a.UNIT_X,f.axisB)}},{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(t,i,s){i.exports=l;var r=t("./Constraint"),n=t("../equations/ContactEquation"),a=t("../math/Vec3");function l(h,c,u,d,f){r.call(this,h,u),f=typeof f<"u"?f:1e6,this.pivotA=c?c.clone():new a,this.pivotB=d?d.clone():new a;var p=this.equationX=new n(h,u),_=this.equationY=new n(h,u),g=this.equationZ=new n(h,u);this.equations.push(p,_,g),p.minForce=_.minForce=g.minForce=-f,p.maxForce=_.maxForce=g.maxForce=f,p.ni.set(1,0,0),_.ni.set(0,1,0),g.ni.set(0,0,1)}l.prototype=new r,l.prototype.update=function(){var h=this.bodyA,c=this.bodyB,u=this.equationX,d=this.equationY,f=this.equationZ;h.quaternion.vmult(this.pivotA,u.ri),c.quaternion.vmult(this.pivotB,u.rj),d.ri.copy(u.ri),d.rj.copy(u.rj),f.ri.copy(u.ri),f.rj.copy(u.rj)}},{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(c,u,d){d=d||{};var f=typeof d.maxForce<"u"?d.maxForce:1e6;n.call(this,c,u,-f,f),this.axisA=d.axisA?d.axisA.clone():new r(1,0,0),this.axisB=d.axisB?d.axisB.clone():new r(0,1,0),this.angle=typeof d.angle<"u"?d.angle:0}a.prototype=new n,a.prototype.constructor=a;var l=new r,h=new r;a.prototype.computeB=function(c){var u=this.a,d=this.b,f=this.axisA,p=this.axisB,_=l,g=h,v=this.jacobianElementA,E=this.jacobianElementB;f.cross(p,_),p.cross(f,g),v.rotational.copy(g),E.rotational.copy(_);var C=Math.cos(this.angle)-f.dot(p),S=this.computeGW(),b=this.computeGiMf(),R=-C*u-S*d-c*b;return R}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(t,i,s){i.exports=a;var r=t("./Equation"),n=t("../math/Vec3");t("../math/Mat3");function a(g,v,E){E=typeof E<"u"?E:1e6,r.call(this,g,v,0,E),this.restitution=0,this.ri=new n,this.rj=new n,this.ni=new n}a.prototype=new r,a.prototype.constructor=a;var l=new n,h=new n,c=new n;a.prototype.computeB=function(g){var v=this.a,E=this.b,C=this.bi,S=this.bj,b=this.ri,R=this.rj,I=l,N=h,O=C.velocity,L=C.angularVelocity;C.force,C.torque;var B=S.velocity,V=S.angularVelocity;S.force,S.torque;var Z=c,ue=this.jacobianElementA,oe=this.jacobianElementB,me=this.ni;b.cross(me,I),R.cross(me,N),me.negate(ue.spatial),I.negate(ue.rotational),oe.spatial.copy(me),oe.rotational.copy(N),Z.copy(S.position),Z.vadd(R,Z),Z.vsub(C.position,Z),Z.vsub(b,Z);var le=me.dot(Z),ae=this.restitution+1,ce=ae*B.dot(me)-ae*O.dot(me)+V.dot(N)-L.dot(I),ie=this.computeGiMf(),w=-le*v-ce*E-g*ie;return w};var u=new n,d=new n,f=new n,p=new n,_=new n;a.prototype.getImpactVelocityAlongNormal=function(){var g=u,v=d,E=f,C=p,S=_;return this.bi.position.vadd(this.ri,E),this.bj.position.vadd(this.rj,C),this.bi.getVelocityAtWorldPoint(E,g),this.bj.getVelocityAtWorldPoint(C,v),g.vsub(v,S),this.ni.dot(S)}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(t,i,s){i.exports=a;var r=t("../math/JacobianElement"),n=t("../math/Vec3");function a(_,g,v,E){this.id=a.id++,this.minForce=typeof v>"u"?-1e6:v,this.maxForce=typeof E>"u"?1e6:E,this.bi=_,this.bj=g,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new r,this.jacobianElementB=new r,this.enabled=!0,this.setSpookParams(1e7,4,1/60)}a.prototype.constructor=a,a.id=0,a.prototype.setSpookParams=function(_,g,v){var E=g,C=_,S=v;this.a=4/(S*(1+4*E)),this.b=4*E/(1+4*E),this.eps=4/(S*S*C*(1+4*E))},a.prototype.computeB=function(_,g,v){var E=this.computeGW(),C=this.computeGq(),S=this.computeGiMf();return-C*_-E*g-S*v},a.prototype.computeGq=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.position,S=E.position;return _.spatial.dot(C)+g.spatial.dot(S)};var l=new n;a.prototype.computeGW=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.velocity,S=E.velocity,b=v.angularVelocity||l,R=E.angularVelocity||l;return _.multiplyVectors(C,b)+g.multiplyVectors(S,R)},a.prototype.computeGWlambda=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.vlambda,S=E.vlambda,b=v.wlambda||l,R=E.wlambda||l;return _.multiplyVectors(C,b)+g.multiplyVectors(S,R)};var h=new n,c=new n,u=new n,d=new n;a.prototype.computeGiMf=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.force,S=v.torque,b=E.force,R=E.torque,I=v.invMassSolve,N=E.invMassSolve;return v.invInertiaWorldSolve?v.invInertiaWorldSolve.vmult(S,u):u.set(0,0,0),E.invInertiaWorldSolve?E.invInertiaWorldSolve.vmult(R,d):d.set(0,0,0),C.mult(I,h),b.mult(N,c),_.multiplyVectors(h,u)+g.multiplyVectors(c,d)};var f=new n;a.prototype.computeGiMGt=function(){var _=this.jacobianElementA,g=this.jacobianElementB,v=this.bi,E=this.bj,C=v.invMassSolve,S=E.invMassSolve,b=v.invInertiaWorldSolve,R=E.invInertiaWorldSolve,I=C+S;return b&&(b.vmult(_.rotational,f),I+=f.dot(_.rotational)),R&&(R.vmult(g.rotational,f),I+=f.dot(g.rotational)),I};var p=new n;new n,new n,new n,new n,new n,a.prototype.addToWlambda=function(_){var g=this.jacobianElementA,v=this.jacobianElementB,E=this.bi,C=this.bj,S=p;g.spatial.mult(E.invMassSolve*_,S),E.vlambda.vadd(S,E.vlambda),v.spatial.mult(C.invMassSolve*_,S),C.vlambda.vadd(S,C.vlambda),E.invInertiaWorldSolve&&(E.invInertiaWorldSolve.vmult(g.rotational,S),S.mult(_,S),E.wlambda.vadd(S,E.wlambda)),C.invInertiaWorldSolve&&(C.invInertiaWorldSolve.vmult(v.rotational,S),S.mult(_,S),C.wlambda.vadd(S,C.wlambda))},a.prototype.computeC=function(){return this.computeGiMGt()+this.eps}},{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(t,i,s){i.exports=a;var r=t("./Equation"),n=t("../math/Vec3");t("../math/Mat3");function a(c,u,d){r.call(this,c,u,-d,d),this.ri=new n,this.rj=new n,this.t=new n}a.prototype=new r,a.prototype.constructor=a;var l=new n,h=new n;a.prototype.computeB=function(c){this.a;var u=this.b;this.bi,this.bj;var d=this.ri,f=this.rj,p=l,_=h,g=this.t;d.cross(g,p),f.cross(g,_);var v=this.jacobianElementA,E=this.jacobianElementB;g.negate(v.spatial),p.negate(v.rotational),E.spatial.copy(g),E.rotational.copy(_);var C=this.computeGW(),S=this.computeGiMf(),b=-C*u-c*S;return b}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(c,u,d){d=d||{};var f=typeof d.maxForce<"u"?d.maxForce:1e6;n.call(this,c,u,-f,f),this.axisA=d.axisA?d.axisA.clone():new r(1,0,0),this.axisB=d.axisB?d.axisB.clone():new r(0,1,0),this.maxAngle=Math.PI/2}a.prototype=new n,a.prototype.constructor=a;var l=new r,h=new r;a.prototype.computeB=function(c){var u=this.a,d=this.b,f=this.axisA,p=this.axisB,_=l,g=h,v=this.jacobianElementA,E=this.jacobianElementB;f.cross(p,_),p.cross(f,g),v.rotational.copy(g),E.rotational.copy(_);var C=Math.cos(this.maxAngle)-f.dot(p),S=this.computeGW(),b=this.computeGiMf(),R=-C*u-S*d-c*b;return R}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(t,i,s){i.exports=a;var r=t("../math/Vec3");t("../math/Mat3");var n=t("./Equation");function a(l,h,c){c=typeof c<"u"?c:1e6,n.call(this,l,h,-c,c),this.axisA=new r,this.axisB=new r,this.targetVelocity=0}a.prototype=new n,a.prototype.constructor=a,a.prototype.computeB=function(l){this.a;var h=this.b;this.bi,this.bj;var c=this.axisA,u=this.axisB,d=this.jacobianElementA,f=this.jacobianElementB;d.rotational.copy(c),u.negate(f.rotational);var p=this.computeGW()-this.targetVelocity,_=this.computeGiMf(),g=-p*h-l*_;return g}},{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(t,i,s){var r=t("../utils/Utils");i.exports=n;function n(a,l,h){h=r.defaults(h,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=n.idCounter++,this.materials=[a,l],this.friction=h.friction,this.restitution=h.restitution,this.contactEquationStiffness=h.contactEquationStiffness,this.contactEquationRelaxation=h.contactEquationRelaxation,this.frictionEquationStiffness=h.frictionEquationStiffness,this.frictionEquationRelaxation=h.frictionEquationRelaxation}n.idCounter=0},{"../utils/Utils":53}],25:[function(t,i,s){i.exports=r;function r(n){var a="";n=n||{},typeof n=="string"?(a=n,n={}):typeof n=="object"&&(a=""),this.name=a,this.id=r.idCounter++,this.friction=typeof n.friction<"u"?n.friction:-1,this.restitution=typeof n.restitution<"u"?n.restitution:-1}r.idCounter=0},{}],26:[function(t,i,s){i.exports=n;var r=t("./Vec3");function n(){this.spatial=new r,this.rotational=new r}n.prototype.multiplyElement=function(a){return a.spatial.dot(this.spatial)+a.rotational.dot(this.rotational)},n.prototype.multiplyVectors=function(a,l){return a.dot(this.spatial)+l.dot(this.rotational)}},{"./Vec3":30}],27:[function(t,i,s){i.exports=n;var r=t("./Vec3");function n(a){a?this.elements=a:this.elements=[0,0,0,0,0,0,0,0,0]}n.prototype.identity=function(){var a=this.elements;a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=1,a[5]=0,a[6]=0,a[7]=0,a[8]=1},n.prototype.setZero=function(){var a=this.elements;a[0]=0,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=0,a[6]=0,a[7]=0,a[8]=0},n.prototype.setTrace=function(a){var l=this.elements;l[0]=a.x,l[4]=a.y,l[8]=a.z},n.prototype.getTrace=function(l){var l=l||new r,h=this.elements;l.x=h[0],l.y=h[4],l.z=h[8]},n.prototype.vmult=function(a,l){l=l||new r;var h=this.elements,c=a.x,u=a.y,d=a.z;return l.x=h[0]*c+h[1]*u+h[2]*d,l.y=h[3]*c+h[4]*u+h[5]*d,l.z=h[6]*c+h[7]*u+h[8]*d,l},n.prototype.smult=function(a){for(var l=0;l.499&&(p=2*Math.atan2(v,S),_=Math.PI/2,g=0),b<-.499&&(p=-2*Math.atan2(v,S),_=-Math.PI/2,g=0),isNaN(p)){var R=v*v,I=E*E,N=C*C;p=Math.atan2(2*E*S-2*v*C,1-2*I-2*N),_=Math.asin(2*b),g=Math.atan2(2*v*S-2*E*C,1-2*R-2*N)}break;default:throw new Error("Euler order "+f+" not supported yet.")}d.y=p,d.z=_,d.x=g},n.prototype.setFromEuler=function(d,f,p,_){_=_||"XYZ";var g=Math.cos(d/2),v=Math.cos(f/2),E=Math.cos(p/2),C=Math.sin(d/2),S=Math.sin(f/2),b=Math.sin(p/2);return _==="XYZ"?(this.x=C*v*E+g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E-C*S*b):_==="YXZ"?(this.x=C*v*E+g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E+C*S*b):_==="ZXY"?(this.x=C*v*E-g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E-C*S*b):_==="ZYX"?(this.x=C*v*E-g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E+C*S*b):_==="YZX"?(this.x=C*v*E+g*S*b,this.y=g*S*E+C*v*b,this.z=g*v*b-C*S*E,this.w=g*v*E-C*S*b):_==="XZY"&&(this.x=C*v*E-g*S*b,this.y=g*S*E-C*v*b,this.z=g*v*b+C*S*E,this.w=g*v*E+C*S*b),this},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)}},{"./Vec3":30}],29:[function(t,i,s){var r=t("./Vec3"),n=t("./Quaternion");i.exports=a;function a(h){h=h||{},this.position=new r,h.position&&this.position.copy(h.position),this.quaternion=new n,h.quaternion&&this.quaternion.copy(h.quaternion)}var l=new n;a.pointToLocalFrame=function(h,c,u,f){var f=f||new r;return u.vsub(h,f),c.conjugate(l),l.vmult(f,f),f},a.prototype.pointToLocal=function(h,c){return a.pointToLocalFrame(this.position,this.quaternion,h,c)},a.pointToWorldFrame=function(h,c,u,f){var f=f||new r;return c.vmult(u,f),f.vadd(h,f),f},a.prototype.pointToWorld=function(h,c){return a.pointToWorldFrame(this.position,this.quaternion,h,c)},a.prototype.vectorToWorldFrame=function(h,u){var u=u||new r;return this.quaternion.vmult(h,u),u},a.vectorToWorldFrame=function(h,c,u){return h.vmult(c,u),u},a.vectorToLocalFrame=function(h,c,u,f){var f=f||new r;return c.w*=-1,c.vmult(u,f),c.w*=-1,f}},{"./Quaternion":28,"./Vec3":30}],30:[function(t,i,s){i.exports=n;var r=t("./Mat3");function n(c,u,d){this.x=c||0,this.y=u||0,this.z=d||0}n.ZERO=new n(0,0,0),n.UNIT_X=new n(1,0,0),n.UNIT_Y=new n(0,1,0),n.UNIT_Z=new n(0,0,1),n.prototype.cross=function(c,u){var d=c.x,f=c.y,p=c.z,_=this.x,g=this.y,v=this.z;return u=u||new n,u.x=g*p-v*f,u.y=v*d-_*p,u.z=_*f-g*d,u},n.prototype.set=function(c,u,d){return this.x=c,this.y=u,this.z=d,this},n.prototype.setZero=function(){this.x=this.y=this.z=0},n.prototype.vadd=function(c,u){if(u)u.x=c.x+this.x,u.y=c.y+this.y,u.z=c.z+this.z;else return new n(this.x+c.x,this.y+c.y,this.z+c.z)},n.prototype.vsub=function(c,u){if(u)u.x=this.x-c.x,u.y=this.y-c.y,u.z=this.z-c.z;else return new n(this.x-c.x,this.y-c.y,this.z-c.z)},n.prototype.crossmat=function(){return new r([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},n.prototype.normalize=function(){var c=this.x,u=this.y,d=this.z,f=Math.sqrt(c*c+u*u+d*d);if(f>0){var p=1/f;this.x*=p,this.y*=p,this.z*=p}else this.x=0,this.y=0,this.z=0;return f},n.prototype.unit=function(c){c=c||new n;var u=this.x,d=this.y,f=this.z,p=Math.sqrt(u*u+d*d+f*f);return p>0?(p=1/p,c.x=u*p,c.y=d*p,c.z=f*p):(c.x=1,c.y=0,c.z=0),c},n.prototype.norm=function(){var c=this.x,u=this.y,d=this.z;return Math.sqrt(c*c+u*u+d*d)},n.prototype.length=n.prototype.norm,n.prototype.norm2=function(){return this.dot(this)},n.prototype.lengthSquared=n.prototype.norm2,n.prototype.distanceTo=function(c){var u=this.x,d=this.y,f=this.z,p=c.x,_=c.y,g=c.z;return Math.sqrt((p-u)*(p-u)+(_-d)*(_-d)+(g-f)*(g-f))},n.prototype.distanceSquared=function(c){var u=this.x,d=this.y,f=this.z,p=c.x,_=c.y,g=c.z;return(p-u)*(p-u)+(_-d)*(_-d)+(g-f)*(g-f)},n.prototype.mult=function(c,u){u=u||new n;var d=this.x,f=this.y,p=this.z;return u.x=c*d,u.y=c*f,u.z=c*p,u},n.prototype.scale=n.prototype.mult,n.prototype.dot=function(c){return this.x*c.x+this.y*c.y+this.z*c.z},n.prototype.isZero=function(){return this.x===0&&this.y===0&&this.z===0},n.prototype.negate=function(c){return c=c||new n,c.x=-this.x,c.y=-this.y,c.z=-this.z,c};var a=new n,l=new n;n.prototype.tangents=function(c,u){var d=this.norm();if(d>0){var f=a,p=1/d;f.set(this.x*p,this.y*p,this.z*p);var _=l;Math.abs(f.x)<.9?(_.set(1,0,0),f.cross(_,c)):(_.set(0,1,0),f.cross(_,c)),f.cross(c,u)}else c.set(1,0,0),u.set(0,1,0)},n.prototype.toString=function(){return this.x+","+this.y+","+this.z},n.prototype.toArray=function(){return[this.x,this.y,this.z]},n.prototype.copy=function(c){return this.x=c.x,this.y=c.y,this.z=c.z,this},n.prototype.lerp=function(c,u,d){var f=this.x,p=this.y,_=this.z;d.x=f+(c.x-f)*u,d.y=p+(c.y-p)*u,d.z=_+(c.z-_)*u},n.prototype.almostEquals=function(c,u){return u===void 0&&(u=1e-6),!(Math.abs(this.x-c.x)>u||Math.abs(this.y-c.y)>u||Math.abs(this.z-c.z)>u)},n.prototype.almostZero=function(c){return c===void 0&&(c=1e-6),!(Math.abs(this.x)>c||Math.abs(this.y)>c||Math.abs(this.z)>c)};var h=new n;n.prototype.isAntiparallelTo=function(c,u){return this.negate(h),h.almostEquals(c,u)},n.prototype.clone=function(){return new n(this.x,this.y,this.z)}},{"./Mat3":27}],31:[function(t,i,s){i.exports=u;var r=t("../utils/EventTarget");t("../shapes/Shape");var n=t("../math/Vec3"),a=t("../math/Mat3"),l=t("../math/Quaternion");t("../material/Material");var h=t("../collision/AABB"),c=t("../shapes/Box");function u(B){B=B||{},r.apply(this),this.id=u.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new n,this.collisionFilterGroup=typeof B.collisionFilterGroup=="number"?B.collisionFilterGroup:1,this.collisionFilterMask=typeof B.collisionFilterMask=="number"?B.collisionFilterMask:1,this.collisionResponse=!0,this.position=new n,B.position&&this.position.copy(B.position),this.previousPosition=new n,this.initPosition=new n,this.velocity=new n,B.velocity&&this.velocity.copy(B.velocity),this.initVelocity=new n,this.force=new n;var V=typeof B.mass=="number"?B.mass:0;this.mass=V,this.invMass=V>0?1/V:0,this.material=B.material||null,this.linearDamping=typeof B.linearDamping=="number"?B.linearDamping:.01,this.type=V<=0?u.STATIC:u.DYNAMIC,typeof B.type==typeof u.STATIC&&(this.type=B.type),this.allowSleep=typeof B.allowSleep<"u"?B.allowSleep:!0,this.sleepState=0,this.sleepSpeedLimit=typeof B.sleepSpeedLimit<"u"?B.sleepSpeedLimit:.1,this.sleepTimeLimit=typeof B.sleepTimeLimit<"u"?B.sleepTimeLimit:1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new n,this.quaternion=new l,B.quaternion&&this.quaternion.copy(B.quaternion),this.initQuaternion=new l,this.angularVelocity=new n,B.angularVelocity&&this.angularVelocity.copy(B.angularVelocity),this.initAngularVelocity=new n,this.interpolatedPosition=new n,this.interpolatedQuaternion=new l,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new n,this.invInertia=new n,this.invInertiaWorld=new a,this.invMassSolve=0,this.invInertiaSolve=new n,this.invInertiaWorldSolve=new a,this.fixedRotation=typeof B.fixedRotation<"u"?B.fixedRotation:!1,this.angularDamping=typeof B.angularDamping<"u"?B.angularDamping:.01,this.aabb=new h,this.aabbNeedsUpdate=!0,this.wlambda=new n,B.shape&&this.addShape(B.shape),this.updateMassProperties()}u.prototype=new r,u.prototype.constructor=u,u.DYNAMIC=1,u.STATIC=2,u.KINEMATIC=4,u.AWAKE=0,u.SLEEPY=1,u.SLEEPING=2,u.idCounter=0,u.prototype.wakeUp=function(){var B=this.sleepState;this.sleepState=0,B===u.SLEEPING&&this.dispatchEvent({type:"wakeup"})},u.prototype.sleep=function(){this.sleepState=u.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0)},u.sleepyEvent={type:"sleepy"},u.sleepEvent={type:"sleep"},u.prototype.sleepTick=function(B){if(this.allowSleep){var V=this.sleepState,Z=this.velocity.norm2()+this.angularVelocity.norm2(),ue=Math.pow(this.sleepSpeedLimit,2);V===u.AWAKE&&Zue?this.wakeUp():V===u.SLEEPY&&B-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(u.sleepEvent))}},u.prototype.updateSolveMassProperties=function(){this.sleepState===u.SLEEPING||this.type===u.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},u.prototype.pointToLocalFrame=function(B,Z){var Z=Z||new n;return B.vsub(this.position,Z),this.quaternion.conjugate().vmult(Z,Z),Z},u.prototype.vectorToLocalFrame=function(B,Z){var Z=Z||new n;return this.quaternion.conjugate().vmult(B,Z),Z},u.prototype.pointToWorldFrame=function(B,Z){var Z=Z||new n;return this.quaternion.vmult(B,Z),Z.vadd(this.position,Z),Z},u.prototype.vectorToWorldFrame=function(B,Z){var Z=Z||new n;return this.quaternion.vmult(B,Z),Z};var d=new n,f=new l;u.prototype.addShape=function(B,V,Z){var ue=new n,oe=new l;return V&&ue.copy(V),Z&&oe.copy(Z),this.shapes.push(B),this.shapeOffsets.push(ue),this.shapeOrientations.push(oe),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,this},u.prototype.updateBoundingRadius=function(){for(var B=this.shapes,V=this.shapeOffsets,Z=B.length,ue=0,oe=0;oe!==Z;oe++){var me=B[oe];me.updateBoundingSphereRadius();var le=V[oe].norm(),ae=me.boundingSphereRadius;le+ae>ue&&(ue=le+ae)}this.boundingRadius=ue};var p=new h;u.prototype.computeAABB=function(){for(var B=this.shapes,V=this.shapeOffsets,Z=this.shapeOrientations,ue=B.length,oe=d,me=f,le=this.quaternion,ae=this.aabb,ce=p,ie=0;ie!==ue;ie++){var w=B[ie];Z[ie].mult(le,me),me.vmult(V[ie],oe),oe.vadd(this.position,oe),w.calculateWorldAABB(oe,me,ce.lowerBound,ce.upperBound),ie===0?ae.copy(ce):ae.extend(ce)}this.aabbNeedsUpdate=!1};var _=new a,g=new a;new a,u.prototype.updateInertiaWorld=function(B){var V=this.invInertia;if(!(V.x===V.y&&V.y===V.z&&!B)){var Z=_,ue=g;Z.setRotationFromQuaternion(this.quaternion),Z.transpose(ue),Z.scale(V,Z),Z.mmult(ue,this.invInertiaWorld)}};var v=new n,E=new n;u.prototype.applyForce=function(B,V){if(this.type===u.DYNAMIC){var Z=v;V.vsub(this.position,Z);var ue=E;Z.cross(B,ue),this.force.vadd(B,this.force),this.torque.vadd(ue,this.torque)}};var C=new n,S=new n;u.prototype.applyLocalForce=function(B,V){if(this.type===u.DYNAMIC){var Z=C,ue=S;this.vectorToWorldFrame(B,Z),this.pointToWorldFrame(V,ue),this.applyForce(Z,ue)}};var b=new n,R=new n,I=new n;u.prototype.applyImpulse=function(B,V){if(this.type===u.DYNAMIC){var Z=b;V.vsub(this.position,Z);var ue=R;ue.copy(B),ue.mult(this.invMass,ue),this.velocity.vadd(ue,this.velocity);var oe=I;Z.cross(B,oe),this.invInertiaWorld.vmult(oe,oe),this.angularVelocity.vadd(oe,this.angularVelocity)}};var N=new n,O=new n;u.prototype.applyLocalImpulse=function(B,V){if(this.type===u.DYNAMIC){var Z=N,ue=O;this.vectorToWorldFrame(B,Z),this.pointToWorldFrame(V,ue),this.applyImpulse(Z,ue)}};var L=new n;u.prototype.updateMassProperties=function(){var B=L;this.invMass=this.mass>0?1/this.mass:0;var V=this.inertia,Z=this.fixedRotation;this.computeAABB(),B.set((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),c.calculateInertia(B,this.mass,V),this.invInertia.set(V.x>0&&!Z?1/V.x:0,V.y>0&&!Z?1/V.y:0,V.z>0&&!Z?1/V.z:0),this.updateInertiaWorld(!0)},u.prototype.getVelocityAtWorldPoint=function(B,V){var Z=new n;return B.vsub(this.position,Z),this.angularVelocity.cross(Z,V),this.velocity.vadd(V,V),V}},{"../collision/AABB":3,"../material/Material":25,"../math/Mat3":27,"../math/Quaternion":28,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Shape":43,"../utils/EventTarget":49}],32:[function(t,i,s){t("./Body");var r=t("../math/Vec3"),n=t("../math/Quaternion");t("../collision/RaycastResult");var a=t("../collision/Ray"),l=t("../objects/WheelInfo");i.exports=h;function h(le){this.chassisBody=le.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=typeof le.indexRightAxis<"u"?le.indexRightAxis:1,this.indexForwardAxis=typeof le.indexForwardAxis<"u"?le.indexForwardAxis:0,this.indexUpAxis=typeof le.indexUpAxis<"u"?le.indexUpAxis:2}new r,new r,new r;var c=new r,u=new r,d=new r;new a,h.prototype.addWheel=function(le){le=le||{};var ae=new l(le),ce=this.wheelInfos.length;return this.wheelInfos.push(ae),ce},h.prototype.setSteeringValue=function(le,ae){var ce=this.wheelInfos[ae];ce.steering=le},new r,h.prototype.applyEngineForce=function(le,ae){this.wheelInfos[ae].engineForce=le},h.prototype.setBrake=function(le,ae){this.wheelInfos[ae].brake=le},h.prototype.addToWorld=function(le){this.constraints,le.add(this.chassisBody);var ae=this;this.preStepCallback=function(){ae.updateVehicle(le.dt)},le.addEventListener("preStep",this.preStepCallback),this.world=le},h.prototype.getVehicleAxisWorld=function(le,ae){ae.set(le===0?1:0,le===1?1:0,le===2?1:0),this.chassisBody.vectorToWorldFrame(ae,ae)},h.prototype.updateVehicle=function(le){for(var ae=this.wheelInfos,ce=ae.length,ie=this.chassisBody,w=0;wQ.maxSuspensionForce&&(_e=Q.maxSuspensionForce),Q.raycastResult.hitNormalWorld.scale(_e*le,X),Q.raycastResult.hitPointWorld.vsub(ie.position,te),ie.applyImpulse(X,Q.raycastResult.hitPointWorld)}this.updateFriction(le);var q=new r,de=new r,ge=new r;for(w=0;w0?1:-1)*Q.customSlidingRotationalSpeed*le),Math.abs(Q.brake)>Math.abs(Q.engineForce)&&(Q.deltaRotation=0),Q.rotation+=Q.deltaRotation,Q.deltaRotation*=.99}},h.prototype.updateSuspension=function(le){for(var ae=this.chassisBody,ce=ae.mass,ie=this.wheelInfos,w=ie.length,H=0;Hge&&(le.suspensionLength=ge,le.raycastResult.reset());var ve=le.raycastResult.hitNormalWorld.dot(le.directionWorld),be=new r;ie.getVelocityAtWorldPoint(le.raycastResult.hitPointWorld,be);var Le=le.raycastResult.hitNormalWorld.dot(be);if(ve>=-.1)le.suspensionRelativeVelocity=0,le.clippedInvContactDotSuspension=1/.1;else{var Ye=-1/ve;le.suspensionRelativeVelocity=Le*Ye,le.clippedInvContactDotSuspension=Ye}}else le.suspensionLength=le.suspensionRestLength+0*le.maxSuspensionTravel,le.suspensionRelativeVelocity=0,le.directionWorld.scale(-1,le.raycastResult.hitNormalWorld),le.clippedInvContactDotSuspension=1;return w},h.prototype.updateWheelTransformWorld=function(le){le.isInContact=!1;var ae=this.chassisBody;ae.pointToWorldFrame(le.chassisConnectionPointLocal,le.chassisConnectionPointWorld),ae.vectorToWorldFrame(le.directionLocal,le.directionWorld),ae.vectorToWorldFrame(le.axleLocal,le.axleWorld)},h.prototype.updateWheelTransform=function(le){var ae=c,ce=u,ie=d,w=this.wheelInfos[le];this.updateWheelTransformWorld(w),w.directionLocal.scale(-1,ae),ce.copy(w.axleLocal),ae.cross(ce,ie),ie.normalize(),ce.normalize();var H=w.steering,X=new n;X.setFromAxisAngle(ae,H);var te=new n;te.setFromAxisAngle(ce,w.rotation);var Q=w.worldTransform.quaternion;this.chassisBody.quaternion.mult(X,Q),Q.mult(te,Q),Q.normalize();var _e=w.worldTransform.position;_e.copy(w.directionWorld),_e.scale(w.suspensionLength,_e),_e.vadd(w.chassisConnectionPointWorld,_e)};var _=[new r(1,0,0),new r(0,1,0),new r(0,0,1)];h.prototype.getWheelTransformWorld=function(le){return this.wheelInfos[le].worldTransform};var g=new r,v=[],E=[],C=1;h.prototype.updateFriction=function(le){for(var ae=g,ce=this.wheelInfos,ie=ce.length,w=this.chassisBody,H=E,X=v,te=0;teVi){this.sliding=!0,Q.sliding=!0;var Ge=Bt/Math.sqrt(di);Q.skidInfo*=Ge}}}if(this.sliding)for(var te=0;te1.1)return 0;var te=Z,Q=ue,_e=oe;le.getVelocityAtWorldPoint(ae,te),ce.getVelocityAtWorldPoint(ie,Q),te.vsub(Q,_e);var q=w.dot(_e),de=.2,ge=1/(le.invMass+ce.invMass),ve=-de*q*ge;return ve}},{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(t,i,s){var r=t("./Body"),n=t("../shapes/Sphere"),a=t("../shapes/Box"),l=t("../math/Vec3"),h=t("../constraints/HingeConstraint");i.exports=c;function c(f){if(this.wheelBodies=[],this.coordinateSystem=typeof f.coordinateSystem>"u"?new l(1,2,3):f.coordinateSystem.clone(),this.chassisBody=f.chassisBody,!this.chassisBody){var p=new a(new l(5,2,.5));this.chassisBody=new r(1,p)}this.constraints=[],this.wheelAxes=[],this.wheelForces=[]}c.prototype.addWheel=function(f){f=f||{};var p=f.body;p||(p=new r(1,new n(1.2))),this.wheelBodies.push(p),this.wheelForces.push(0),new l;var _=typeof f.position<"u"?f.position.clone():new l,g=new l;this.chassisBody.pointToWorldFrame(_,g),p.position.set(g.x,g.y,g.z);var v=typeof f.axis<"u"?f.axis.clone():new l(0,1,0);this.wheelAxes.push(v);var E=new h(this.chassisBody,p,{pivotA:_,axisA:v,pivotB:l.ZERO,axisB:v,collideConnected:!1});return this.constraints.push(E),this.wheelBodies.length-1},c.prototype.setSteeringValue=function(f,p){var _=this.wheelAxes[p],g=Math.cos(f),v=Math.sin(f),E=_.x,C=_.y;this.constraints[p].axisA.set(g*E-v*C,v*E+g*C,0)},c.prototype.setMotorSpeed=function(f,p){var _=this.constraints[p];_.enableMotor(),_.motorTargetVelocity=f},c.prototype.disableMotor=function(f){var p=this.constraints[f];p.disableMotor()};var u=new l;c.prototype.setWheelForce=function(f,p){this.wheelForces[p]=f},c.prototype.applyWheelForce=function(f,p){var _=this.wheelAxes[p],g=this.wheelBodies[p],v=g.torque;_.scale(f,u),g.vectorToWorldFrame(u,u),v.vadd(u,v)},c.prototype.addToWorld=function(f){for(var p=this.constraints,_=this.wheelBodies.concat([this.chassisBody]),g=0;g<_.length;g++)f.add(_[g]);for(var g=0;gthis.particles.length&&this.neighbors.pop())};var a=new r;n.prototype.getNeighbors=function(p,_){for(var g=this.particles.length,v=p.id,E=this.smoothingRadius*this.smoothingRadius,C=a,S=0;S!==g;S++){var b=this.particles[S];b.position.vsub(p.position,C),v!==b.id&&C.norm2()=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=1/.1;else{var g=-1/p;this.suspensionRelativeVelocity=_*g,this.clippedInvContactDotSuspension=g}}else f.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,f.directionWorld.scale(-1,f.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(t,i,s){i.exports=l;var r=t("./Shape"),n=t("../math/Vec3"),a=t("./ConvexPolyhedron");function l(u){r.call(this),this.type=r.types.BOX,this.halfExtents=u,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}l.prototype=new r,l.prototype.constructor=l,l.prototype.updateConvexPolyhedronRepresentation=function(){var u=this.halfExtents.x,d=this.halfExtents.y,f=this.halfExtents.z,p=n,_=[new p(-u,-d,-f),new p(u,-d,-f),new p(u,d,-f),new p(-u,d,-f),new p(-u,-d,f),new p(u,-d,f),new p(u,d,f),new p(-u,d,f)],g=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]];new p(0,0,1),new p(0,1,0),new p(1,0,0);var v=new a(_,g);this.convexPolyhedronRepresentation=v,v.material=this.material},l.prototype.calculateLocalInertia=function(u,d){return d=d||new n,l.calculateInertia(this.halfExtents,u,d),d},l.calculateInertia=function(u,d,f){var p=u;f.x=1/12*d*(2*p.y*2*p.y+2*p.z*2*p.z),f.y=1/12*d*(2*p.x*2*p.x+2*p.z*2*p.z),f.z=1/12*d*(2*p.y*2*p.y+2*p.x*2*p.x)},l.prototype.getSideNormals=function(u,d){var f=u,p=this.halfExtents;if(f[0].set(p.x,0,0),f[1].set(0,p.y,0),f[2].set(0,0,p.z),f[3].set(-p.x,0,0),f[4].set(0,-p.y,0),f[5].set(0,0,-p.z),d!==void 0)for(var _=0;_!==f.length;_++)d.vmult(f[_],f[_]);return f},l.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},l.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};var h=new n;new n,l.prototype.forEachWorldCorner=function(u,d,f){for(var p=this.halfExtents,_=[[p.x,p.y,p.z],[-p.x,p.y,p.z],[-p.x,-p.y,p.z],[-p.x,-p.y,-p.z],[p.x,-p.y,-p.z],[p.x,p.y,-p.z],[-p.x,p.y,-p.z],[p.x,-p.y,p.z]],g=0;g<_.length;g++)h.set(_[g][0],_[g][1],_[g][2]),d.vmult(h,h),u.vadd(h,h),f(h.x,h.y,h.z)};var c=[new n,new n,new n,new n,new n,new n,new n,new n];l.prototype.calculateWorldAABB=function(u,d,f,p){var _=this.halfExtents;c[0].set(_.x,_.y,_.z),c[1].set(-_.x,_.y,_.z),c[2].set(-_.x,-_.y,_.z),c[3].set(-_.x,-_.y,-_.z),c[4].set(_.x,-_.y,-_.z),c[5].set(_.x,_.y,-_.z),c[6].set(-_.x,_.y,-_.z),c[7].set(_.x,-_.y,_.z);var g=c[0];d.vmult(g,g),u.vadd(g,g),p.copy(g),f.copy(g);for(var v=1;v<8;v++){var g=c[v];d.vmult(g,g),u.vadd(g,g);var E=g.x,C=g.y,S=g.z;E>p.x&&(p.x=E),C>p.y&&(p.y=C),S>p.z&&(p.z=S),ELe&&(Le=He,be=Ye)}for(var Be=[],Ge=X.faces[be],Bt=Ge.length,Mt=0;Mt=0&&this.clipFaceAgainstHull(_e,w,H,Be,q,de,ge)};var f=new n,p=new n,_=new n,g=new n,v=new n,E=new n;l.prototype.findSeparatingAxis=function(w,H,X,te,Q,_e,q,de){var ge=f,ve=p,be=_,Le=g,Ye=v,He=E,Be=Number.MAX_VALUE,Ge=this;if(Ge.uniqueAxes)for(var Mt=0;Mt!==Ge.uniqueAxes.length;Mt++){X.vmult(Ge.uniqueAxes[Mt],ge);var at=Ge.testSepAxis(ge,w,H,X,te,Q);if(at===!1)return!1;at0&&_e.negate(_e),!0};var C=[],S=[];l.prototype.testSepAxis=function(w,H,X,te,Q,_e){var q=this;l.project(q,w,X,te,C),l.project(H,w,Q,_e,S);var de=C[0],ge=C[1],ve=S[0],be=S[1],Le=de-be,Ye=ve-ge,He=LeH.x&&(H.x=_e.x),_e.yH.y&&(H.y=_e.y),_e.zH.z&&(H.z=_e.z)}},l.prototype.computeWorldFaceNormals=function(w){for(var H=this.faceNormals.length;this.worldFaceNormals.lengthw&&(w=Q)}this.boundingSphereRadius=Math.sqrt(w)};var oe=new n;l.prototype.calculateWorldAABB=function(w,H,X,te){for(var Q=this.vertices.length,_e=this.vertices,q,de,ge,ve,be,Le,Ye=0;Yeve||ve===void 0)&&(ve=He.x),He.ybe||be===void 0)&&(be=He.y),He.zLe||Le===void 0)&&(Le=He.z)}X.set(q,de,ge),te.set(ve,be,Le)},l.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},l.prototype.getAveragePointLocal=function(w){w=w||new n;for(var H=this.vertices.length,X=this.vertices,te=0;te0||Le>0&&He<0)return!1}return _e?1:-1},new n;var ce=new n,ie=new n;l.project=function(w,H,X,te,Q){var _e=w.vertices.length,q=ce,de=0,ge=0,ve=ie,be=w.vertices;ve.setZero(),a.vectorToLocalFrame(X,te,H,q),a.pointToLocalFrame(X,te,ve,ve);var Le=ve.dot(q);ge=de=be[0].dot(q);for(var Ye=1;Ye<_e;Ye++){var He=be[Ye].dot(q);He>de&&(de=He),Hede){var Be=ge;ge=de,de=Be}Q[0]=de,Q[1]=ge}},{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(t,i,s){i.exports=l;var r=t("./Shape"),n=t("../math/Vec3");t("../math/Quaternion");var a=t("./ConvexPolyhedron");function l(h,c,u,d){var f=d,p=[],_=[],g=[],v=[],E=[],C=Math.cos,S=Math.sin;p.push(new n(c*C(0),c*S(0),-u*.5)),v.push(0),p.push(new n(h*C(0),h*S(0),u*.5)),E.push(1);for(var b=0;bu&&(u=p)}this.maxValue=u},h.prototype.setHeightValueAtIndex=function(c,u,d){var f=this.data;f[c][u]=d,this.clearCachedConvexTrianglePillar(c,u,!1),c>0&&(this.clearCachedConvexTrianglePillar(c-1,u,!0),this.clearCachedConvexTrianglePillar(c-1,u,!1)),u>0&&(this.clearCachedConvexTrianglePillar(c,u-1,!0),this.clearCachedConvexTrianglePillar(c,u-1,!1)),u>0&&c>0&&this.clearCachedConvexTrianglePillar(c-1,u-1,!0)},h.prototype.getRectMinMax=function(c,u,d,f,p){p=p||[];for(var _=this.data,g=this.minValue,v=c;v<=d;v++)for(var E=u;E<=f;E++){var C=_[v][E];C>g&&(g=C)}p[0]=this.minValue,p[1]=g},h.prototype.getIndexOfPosition=function(c,u,d,f){var p=this.elementSize,_=this.data,g=Math.floor(c/p),v=Math.floor(u/p);return d[0]=g,d[1]=v,f&&(g<0&&(g=0),v<0&&(v=0),g>=_.length-1&&(g=_.length-1),v>=_[0].length-1&&(v=_[0].length-1)),!(g<0||v<0||g>=_.length-1||v>=_[0].length-1)},h.prototype.getHeightAt=function(c,u,d){var f=[];this.getIndexOfPosition(c,u,f,d);var p=[];return this.getRectMinMax(f[0],f[1]+1,f[0],f[1]+1,p),(p[0]+p[1])/2},h.prototype.getCacheConvexTrianglePillarKey=function(c,u,d){return c+"_"+u+"_"+(d?1:0)},h.prototype.getCachedConvexTrianglePillar=function(c,u,d){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]},h.prototype.setCachedConvexTrianglePillar=function(c,u,d,f,p){this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]={convex:f,offset:p}},h.prototype.clearCachedConvexTrianglePillar=function(c,u,d){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(c,u,d)]},h.prototype.getConvexTrianglePillar=function(c,u,d){var f=this.pillarConvex,p=this.pillarOffset;if(this.cacheEnabled){var _=this.getCachedConvexTrianglePillar(c,u,d);if(_){this.pillarConvex=_.convex,this.pillarOffset=_.offset;return}f=new n,p=new a,this.pillarConvex=f,this.pillarOffset=p}var _=this.data,g=this.elementSize,v=f.faces;f.vertices.length=6;for(var E=0;E<6;E++)f.vertices[E]||(f.vertices[E]=new a);v.length=5;for(var E=0;E<5;E++)v[E]||(v[E]=[]);var C=f.vertices,S=(Math.min(_[c][u],_[c+1][u],_[c][u+1],_[c+1][u+1])-this.minValue)/2+this.minValue;d?(p.set((c+.75)*g,(u+.75)*g,S),C[0].set(.25*g,.25*g,_[c+1][u+1]-S),C[1].set(-.75*g,.25*g,_[c][u+1]-S),C[2].set(.25*g,-.75*g,_[c+1][u]-S),C[3].set(.25*g,.25*g,-S-1),C[4].set(-.75*g,.25*g,-S-1),C[5].set(.25*g,-.75*g,-S-1),v[0][0]=0,v[0][1]=1,v[0][2]=2,v[1][0]=5,v[1][1]=4,v[1][2]=3,v[2][0]=2,v[2][1]=5,v[2][2]=3,v[2][3]=0,v[3][0]=3,v[3][1]=4,v[3][2]=1,v[3][3]=0,v[4][0]=1,v[4][1]=4,v[4][2]=5,v[4][3]=2):(p.set((c+.25)*g,(u+.25)*g,S),C[0].set(-.25*g,-.25*g,_[c][u]-S),C[1].set(.75*g,-.25*g,_[c+1][u]-S),C[2].set(-.25*g,.75*g,_[c][u+1]-S),C[3].set(-.25*g,-.25*g,-S-1),C[4].set(.75*g,-.25*g,-S-1),C[5].set(-.25*g,.75*g,-S-1),v[0][0]=0,v[0][1]=1,v[0][2]=2,v[1][0]=5,v[1][1]=4,v[1][2]=3,v[2][0]=0,v[2][1]=2,v[2][2]=5,v[2][3]=3,v[3][0]=1,v[3][1]=0,v[3][2]=3,v[3][3]=4,v[4][0]=4,v[4][1]=5,v[4][2]=2,v[4][3]=1),f.computeNormals(),f.computeEdges(),f.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(c,u,d,f,p)},h.prototype.calculateLocalInertia=function(c,u){return u=u||new a,u.set(0,0,0),u},h.prototype.volume=function(){return Number.MAX_VALUE},h.prototype.calculateWorldAABB=function(c,u,d,f){d.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),f.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},h.prototype.updateBoundingSphereRadius=function(){var c=this.data,u=this.elementSize;this.boundingSphereRadius=new a(c.length*u,c[0].length*u,Math.max(Math.abs(this.maxValue),Math.abs(this.minValue))).norm()}},{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(){r.call(this),this.type=r.types.PARTICLE}a.prototype=new r,a.prototype.constructor=a,a.prototype.calculateLocalInertia=function(l,h){return h=h||new n,h.set(0,0,0),h},a.prototype.volume=function(){return 0},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=0},a.prototype.calculateWorldAABB=function(l,h,c,u){c.copy(l),u.copy(l)}},{"../math/Vec3":30,"./Shape":43}],42:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(){r.call(this),this.type=r.types.PLANE,this.worldNormal=new n,this.worldNormalNeedsUpdate=!0,this.boundingSphereRadius=Number.MAX_VALUE}a.prototype=new r,a.prototype.constructor=a,a.prototype.computeWorldNormal=function(h){var c=this.worldNormal;c.set(0,0,1),h.vmult(c,c),this.worldNormalNeedsUpdate=!1},a.prototype.calculateLocalInertia=function(h,c){return c=c||new n,c},a.prototype.volume=function(){return Number.MAX_VALUE};var l=new n;a.prototype.calculateWorldAABB=function(h,c,u,d){l.set(0,0,1),c.vmult(l,l);var f=Number.MAX_VALUE;u.set(-f,-f,-f),d.set(f,f,f),l.x===1&&(d.x=h.x),l.y===1&&(d.y=h.y),l.z===1&&(d.z=h.z),l.x===-1&&(u.x=h.x),l.y===-1&&(u.y=h.y),l.z===-1&&(u.z=h.z)},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=Number.MAX_VALUE}},{"../math/Vec3":30,"./Shape":43}],43:[function(t,i,s){i.exports=r;var r=t("./Shape");t("../math/Vec3"),t("../math/Quaternion"),t("../material/Material");function r(){this.id=r.idCounter++,this.type=0,this.boundingSphereRadius=0,this.collisionResponse=!0,this.material=null}r.prototype.constructor=r,r.prototype.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},r.prototype.volume=function(){throw"volume() not implemented for shape type "+this.type},r.prototype.calculateLocalInertia=function(n,a){throw"calculateLocalInertia() not implemented for shape type "+this.type},r.idCounter=0,r.types={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256}},{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(t,i,s){i.exports=a;var r=t("./Shape"),n=t("../math/Vec3");function a(l){if(r.call(this),this.radius=l!==void 0?Number(l):1,this.type=r.types.SPHERE,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}a.prototype=new r,a.prototype.constructor=a,a.prototype.calculateLocalInertia=function(l,h){h=h||new n;var c=2*l*this.radius*this.radius/5;return h.x=c,h.y=c,h.z=c,h},a.prototype.volume=function(){return 4*Math.PI*this.radius/3},a.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},a.prototype.calculateWorldAABB=function(l,h,c,u){for(var d=this.radius,f=["x","y","z"],p=0;pL.x&&(L.x=V.x),V.yL.y&&(L.y=V.y),V.zL.z&&(L.z=V.z)},c.prototype.updateAABB=function(){this.computeLocalAABB(this.aabb)},c.prototype.updateBoundingSphereRadius=function(){for(var N=0,O=this.vertices,L=new n,B=0,V=O.length/3;B!==V;B++){this.getVertex(B,L);var Z=L.norm2();Z>N&&(N=Z)}this.boundingSphereRadius=Math.sqrt(N)},new n;var R=new a,I=new l;c.prototype.calculateWorldAABB=function(N,O,L,B){var V=R,Z=I;V.position=N,V.quaternion=O,this.aabb.toWorldFrame(V,Z),L.copy(Z.lowerBound),B.copy(Z.upperBound)},c.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},c.createTorus=function(N,O,L,B,V){N=N||1,O=O||.5,L=L||8,B=B||6,V=V||Math.PI*2;for(var Z=[],ue=[],oe=0;oe<=L;oe++)for(var me=0;me<=B;me++){var le=me/B*V,ae=oe/L*Math.PI*2,ce=(N+O*Math.cos(ae))*Math.cos(le),ie=(N+O*Math.cos(ae))*Math.sin(le),w=O*Math.sin(ae);Z.push(ce,ie,w)}for(var oe=1;oe<=L;oe++)for(var me=1;me<=B;me++){var H=(B+1)*oe+me-1,X=(B+1)*(oe-1)+me-1,te=(B+1)*(oe-1)+me,Q=(B+1)*oe+me;ue.push(H,X,Q),ue.push(X,te,Q)}return new c(Z,ue)}},{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(t,i,s){i.exports=n,t("../math/Vec3"),t("../math/Quaternion");var r=t("./Solver");function n(){r.call(this),this.iterations=10,this.tolerance=1e-7}n.prototype=new r;var a=[],l=[],h=[];n.prototype.solve=function(c,u){var d=0,f=this.iterations,p=this.tolerance*this.tolerance,_=this.equations,g=_.length,v=u.bodies,E=v.length,C=c,S,b,R,I,N,O;if(g!==0)for(var L=0;L!==E;L++)v[L].updateSolveMassProperties();var B=l,V=h,Z=a;B.length=g,V.length=g,Z.length=g;for(var L=0;L!==g;L++){var ue=_[L];Z[L]=0,V[L]=ue.computeB(C),B[L]=1/ue.computeC()}if(g!==0){for(var L=0;L!==E;L++){var oe=v[L],me=oe.vlambda,le=oe.wlambda;me.set(0,0,0),le&&le.set(0,0,0)}for(d=0;d!==f;d++){I=0;for(var ae=0;ae!==g;ae++){var ue=_[ae];S=V[ae],b=B[ae],O=Z[ae],N=ue.computeGWlambda(),R=b*(S-N-ue.eps*O),O+Rue.maxForce&&(R=ue.maxForce-O),Z[ae]+=R,I+=R>0?R:-R,ue.addToWlambda(R)}if(I*I=0;f--)d.children[f].data.length||d.children.splice(f,1);Array.prototype.push.apply(u,d.children)}}},{"../collision/AABB":3,"../math/Vec3":30}],51:[function(t,i,s){i.exports=r;function r(){this.objects=[],this.type=Object}r.prototype.release=function(){for(var n=arguments.length,a=0;a!==n;a++)this.objects.push(arguments[a])},r.prototype.get=function(){return this.objects.length===0?this.constructObject():this.objects.pop()},r.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}},{}],52:[function(t,i,s){i.exports=r;function r(){this.data={keys:[]}}r.prototype.get=function(n,a){if(n>a){var l=a;a=n,n=l}return this.data[n+"-"+a]},r.prototype.set=function(n,a,l){if(n>a){var h=a;a=n,n=h}var c=n+"-"+a;this.get(n,a)||this.data.keys.push(c),this.data[c]=l},r.prototype.reset=function(){for(var n=this.data,a=n.keys;a.length>0;){var l=a.pop();delete n[l]}}},{}],53:[function(t,i,s){function r(){}i.exports=r,r.defaults=function(n,a){n=n||{};for(var l in a)l in n||(n[l]=a[l]);return n}},{}],54:[function(t,i,s){i.exports=a;var r=t("../math/Vec3"),n=t("./Pool");function a(){n.call(this),this.type=r}a.prototype=new n,a.prototype.constructObject=function(){return new r}},{"../math/Vec3":30,"./Pool":51}],55:[function(t,i,s){i.exports=p;var r=t("../collision/AABB"),n=t("../shapes/Shape"),a=t("../collision/Ray"),l=t("../math/Vec3"),h=t("../math/Transform");t("../shapes/ConvexPolyhedron");var c=t("../math/Quaternion");t("../solver/Solver");var u=t("../utils/Vec3Pool"),d=t("../equations/ContactEquation"),f=t("../equations/FrictionEquation");function p(Ue){this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new u,this.world=Ue,this.currentContactMaterial=null,this.enableFrictionReduction=!1}p.prototype.createContactEquation=function(Ue,ke,Je,$e,Wt,bt){var pt;this.contactPointPool.length?(pt=this.contactPointPool.pop(),pt.bi=Ue,pt.bj=ke):pt=new d(Ue,ke),pt.enabled=Ue.collisionResponse&&ke.collisionResponse&&Je.collisionResponse&&$e.collisionResponse;var Tt=this.currentContactMaterial;pt.restitution=Tt.restitution,pt.setSpookParams(Tt.contactEquationStiffness,Tt.contactEquationRelaxation,this.world.dt);var Ne=Je.material||Ue.material,_t=$e.material||ke.material;return Ne&&_t&&Ne.restitution>=0&&_t.restitution>=0&&(pt.restitution=Ne.restitution*_t.restitution),pt.si=Wt||Je,pt.sj=bt||$e,pt},p.prototype.createFrictionEquationsFromContact=function(Ue,ke){var Je=Ue.bi,$e=Ue.bj,Wt=Ue.si,bt=Ue.sj,pt=this.world,Tt=this.currentContactMaterial,Ne=Tt.friction,_t=Wt.material||Je.material,Et=bt.material||$e.material;if(_t&&Et&&_t.friction>=0&&Et.friction>=0&&(Ne=_t.friction*Et.friction),Ne>0){var Nt=Ne*pt.gravity.length(),gt=Je.invMass+$e.invMass;gt>0&&(gt=1/gt);var ct=this.frictionEquationPool,vt=ct.length?ct.pop():new f(Je,$e,Nt*gt),Ht=ct.length?ct.pop():new f(Je,$e,Nt*gt);return vt.bi=Ht.bi=Je,vt.bj=Ht.bj=$e,vt.minForce=Ht.minForce=-Nt*gt,vt.maxForce=Ht.maxForce=Nt*gt,vt.ri.copy(Ue.ri),vt.rj.copy(Ue.rj),Ht.ri.copy(Ue.ri),Ht.rj.copy(Ue.rj),Ue.ni.tangents(vt.t,Ht.t),vt.setSpookParams(Tt.frictionEquationStiffness,Tt.frictionEquationRelaxation,pt.dt),Ht.setSpookParams(Tt.frictionEquationStiffness,Tt.frictionEquationRelaxation,pt.dt),vt.enabled=Ht.enabled=Ue.enabled,ke.push(vt,Ht),!0}return!1};var _=new l,g=new l,v=new l;p.prototype.createFrictionFromAverage=function(Ue){var ke=this.result[this.result.length-1];if(!(!this.createFrictionEquationsFromContact(ke,this.frictionResult)||Ue===1)){var Je=this.frictionResult[this.frictionResult.length-2],$e=this.frictionResult[this.frictionResult.length-1];_.setZero(),g.setZero(),v.setZero();var Wt=ke.bi;ke.bj;for(var bt=0;bt!==Ue;bt++)ke=this.result[this.result.length-1-bt],ke.bodyA!==Wt?(_.vadd(ke.ni,_),g.vadd(ke.ri,g),v.vadd(ke.rj,v)):(_.vsub(ke.ni,_),g.vadd(ke.rj,g),v.vadd(ke.ri,v));var pt=1/Ue;g.scale(pt,Je.ri),v.scale(pt,Je.rj),$e.ri.copy(Je.ri),$e.rj.copy(Je.rj),_.normalize(),_.tangents(Je.t,$e.t)}};var E=new l,C=new l,S=new c,b=new c;p.prototype.getContacts=function(Ue,ke,Je,$e,Wt,bt,pt){this.contactPointPool=Wt,this.frictionEquationPool=pt,this.result=$e,this.frictionResult=bt;for(var Tt=S,Ne=b,_t=E,Et=C,Nt=0,gt=Ue.length;Nt!==gt;Nt++){var ct=Ue[Nt],vt=ke[Nt],Ht=null;ct.material&&vt.material&&(Ht=Je.getContactMaterial(ct.material,vt.material)||null);for(var fi=0;fist.boundingSphereRadius+yi.boundingSphereRadius)){var Is=null;st.material&&yi.material&&(Is=Je.getContactMaterial(st.material,yi.material)||null),this.currentContactMaterial=Is||Ht||Je.defaultContactMaterial;var Di=this[st.type|yi.type];Di&&(st.type0&&Kn<0){gt.vsub(Ne,ct),Nt.copy(Et),Nt.normalize(),qn=ct.dot(Nt),Nt.scale(qn,ct),ct.vadd(Ne,ct);var cn=ct.distanceTo(gt);if(cn0&&$e===!0||Et<=0&&$e===!1){$e===null&&($e=Et>0);continue}else return!1}return!0}var ve=new l,be=new l,Le=new l,Ye=new l,He=[new l,new l,new l,new l,new l,new l],Be=new l,Ge=new l,Bt=new l,Mt=new l;p.prototype[n.types.SPHERE|n.types.BOX]=p.prototype.sphereBox=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=this.v3pool,_t=He;Je.vsub($e,ve),ke.getSideNormals(_t,bt);for(var Et=Ue.radius,Nt=!1,gt=Ge,ct=Bt,vt=Mt,Ht=null,fi=0,st=0,vi=0,yi=null,Is=0,Di=_t.length;Is!==Di&&Nt===!1;Is++){var wi=be;wi.copy(_t[Is]);var ii=wi.norm();wi.normalize();var Kn=ve.dot(wi);if(Kn0){var qn=Le,cn=Ye;qn.copy(_t[(Is+1)%3]),cn.copy(_t[(Is+2)%3]);var Ga=qn.norm(),un=cn.norm();qn.normalize(),cn.normalize();var vs=ve.dot(qn),oo=ve.dot(cn);if(vs-Ga&&oo-un){var yr=Math.abs(Kn-ii-Et);(yi===null||yr0){for(var un=[],vs=0,oo=Di.length;vs!==oo;vs++){var Os=Ne.get();bt.vmult(Nt[Di[vs]],Os),$e.vadd(Os,Os),un.push(Os)}if(ge(un,wi,Je)){vi=!0;var st=this.createContactEquation(pt,Tt,Ue,ke);wi.mult(-gt,st.ri),wi.negate(st.ni);var lo=Ne.get();wi.mult(-cn,lo);var dn=Ne.get();wi.mult(-gt,dn),Je.vsub($e,st.rj),st.rj.vadd(dn,st.rj),st.rj.vadd(lo,st.rj),st.rj.vadd($e,st.rj),st.rj.vsub(Tt.position,st.rj),st.ri.vadd(Je,st.ri),st.ri.vsub(pt.position,st.ri),Ne.release(lo),Ne.release(dn),this.result.push(st),this.createFrictionEquationsFromContact(st,this.frictionResult);for(var vs=0,Hr=un.length;vs!==Hr;vs++)Ne.release(un[vs]);return}else for(var vs=0;vs!==Di.length;vs++){var wr=Ne.get(),En=Ne.get();bt.vmult(Nt[Di[(vs+1)%Di.length]],wr),bt.vmult(Nt[Di[(vs+2)%Di.length]],En),$e.vadd(wr,wr),$e.vadd(En,En);var ho=at;En.vsub(wr,ho);var li=ei;ho.unit(li);var Zr=Ne.get(),yr=Ne.get();Je.vsub(wr,yr);var rl=yr.dot(li);li.mult(rl,Zr),Zr.vadd(wr,Zr);var Po=Ne.get();if(Zr.vsub(Je,Po),rl>0&&rl*rlUe.boundingSphereRadius+ke.boundingSphereRadius)&&Ue.findSeparatingAxis(ke,Je,Wt,$e,bt,gt,Et,Nt)){var ct=[],vt=Wr;Ue.clipAgainstHull(Je,Wt,ke,$e,bt,gt,-100,100,ct);for(var Ht=0,fi=0;fi!==ct.length;fi++){var st=this.createContactEquation(pt,Tt,Ue,ke,Ne,_t),vi=st.ri,yi=st.rj;gt.negate(st.ni),ct[fi].normal.negate(vt),vt.mult(ct[fi].depth,vt),ct[fi].point.vadd(vt,vi),yi.copy(ct[fi].point),vi.vsub(Je,vi),yi.vsub($e,yi),vi.vadd(Je,vi),vi.vsub(pt.position,vi),yi.vadd($e,yi),yi.vsub(Tt.position,yi),this.result.push(st),Ht++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(st,this.frictionResult)}this.enableFrictionReduction&&Ht&&this.createFrictionFromAverage(Ht)}};var $n=new l,On=new l,xn=new l;p.prototype[n.types.PLANE|n.types.PARTICLE]=p.prototype.planeParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=$n;Ne.set(0,0,1),pt.quaternion.vmult(Ne,Ne);var _t=On;$e.vsub(pt.position,_t);var Et=Ne.dot(_t);if(Et<=0){var Nt=this.createContactEquation(Tt,pt,ke,Ue);Nt.ni.copy(Ne),Nt.ni.negate(Nt.ni),Nt.ri.set(0,0,0);var gt=xn;Ne.mult(Ne.dot($e),gt),$e.vsub(gt,gt),Nt.rj.copy(gt),this.result.push(Nt),this.createFrictionEquationsFromContact(Nt,this.frictionResult)}};var Nn=new l;p.prototype[n.types.PARTICLE|n.types.SPHERE]=p.prototype.sphereParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=Nn;Ne.set(0,0,1),$e.vsub(Je,Ne);var _t=Ne.norm2();if(_t<=Ue.radius*Ue.radius){var Et=this.createContactEquation(Tt,pt,ke,Ue);Ne.normalize(),Et.rj.copy(Ne),Et.rj.mult(Ue.radius,Et.rj),Et.ni.copy(Ne),Et.ni.negate(Et.ni),Et.ri.set(0,0,0),this.result.push(Et),this.createFrictionEquationsFromContact(Et,this.frictionResult)}};var hn=new c,Tn=new l;new l;var Qr=new l,ur=new l,da=new l;p.prototype[n.types.PARTICLE|n.types.CONVEXPOLYHEDRON]=p.prototype.convexParticle=function(Ue,ke,Je,$e,Wt,bt,pt,Tt){var Ne=-1,_t=Qr,Et=da,Nt=null,gt=Tn;if(gt.copy($e),gt.vsub(Je,gt),Wt.conjugate(hn),hn.vmult(gt,gt),Ue.pointIsInside(gt)){Ue.worldVerticesNeedsUpdate&&Ue.computeWorldVertices(Je,Wt),Ue.worldFaceNormalsNeedsUpdate&&Ue.computeWorldFaceNormals(Wt);for(var ct=0,vt=Ue.faces.length;ct!==vt;ct++){var Ht=[Ue.worldVertices[Ue.faces[ct][0]]],fi=Ue.worldFaceNormals[ct];$e.vsub(Ht[0],ur);var st=-fi.dot(ur);(Nt===null||Math.abs(st)Ne.length||fi>Ne[0].length)){vt<0&&(vt=0),Ht<0&&(Ht=0),fi<0&&(fi=0),st<0&&(st=0),vt>=Ne.length&&(vt=Ne.length-1),Ht>=Ne.length&&(Ht=Ne.length-1),st>=Ne[0].length&&(st=Ne[0].length-1),fi>=Ne[0].length&&(fi=Ne[0].length-1);var vi=[];ke.getRectMinMax(vt,fi,Ht,st,vi);var yi=vi[0],Is=vi[1];if(!(ct.z-Et>Is||ct.z+EtNe.length||fi>Ne[0].length)){ct<0&&(ct=0),vt<0&&(vt=0),Ht<0&&(Ht=0),fi<0&&(fi=0),ct>=Ne.length&&(ct=Ne.length-1),vt>=Ne.length&&(vt=Ne.length-1),fi>=Ne[0].length&&(fi=Ne[0].length-1),Ht>=Ne[0].length&&(Ht=Ne[0].length-1);var st=[];ke.getRectMinMax(ct,Ht,vt,fi,st);var vi=st[0],yi=st[1];if(!(gt.z-_t>yi||gt.z+_t2)return}}}},{"../collision/AABB":3,"../collision/Ray":9,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43,"../solver/Solver":47,"../utils/Vec3Pool":54}],56:[function(t,i,s){i.exports=S;var r=t("../shapes/Shape"),n=t("../math/Vec3"),a=t("../math/Quaternion"),l=t("../solver/GSSolver");t("../utils/Vec3Pool"),t("../equations/ContactEquation"),t("../equations/FrictionEquation");var h=t("./Narrowphase"),c=t("../utils/EventTarget"),u=t("../collision/ArrayCollisionMatrix"),d=t("../material/Material"),f=t("../material/ContactMaterial"),p=t("../objects/Body"),_=t("../utils/TupleDictionary"),g=t("../collision/RaycastResult"),v=t("../collision/AABB"),E=t("../collision/Ray"),C=t("../collision/NaiveBroadphase");function S(){c.apply(this),this.dt=-1,this.allowSleep=!1,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=0,this.quatNormalizeFast=!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new n,this.broadphase=new C,this.bodies=[],this.solver=new l,this.constraints=[],this.narrowphase=new h(this),this.collisionMatrix=new u,this.collisionMatrixPrevious=new u,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new _,this.defaultMaterial=new d("default"),this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null}}S.prototype=new c,new v;var b=new E;if(S.prototype.getContactMaterial=function(ae,ce){return this.contactMaterialTable.get(ae.id,ce.id)},S.prototype.numObjects=function(){return this.bodies.length},S.prototype.collisionMatrixTick=function(){var ae=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=ae,this.collisionMatrix.reset()},S.prototype.add=S.prototype.addBody=function(ae){this.bodies.indexOf(ae)===-1&&(ae.index=this.bodies.length,this.bodies.push(ae),ae.world=this,ae.initPosition.copy(ae.position),ae.initVelocity.copy(ae.velocity),ae.timeLastSleepy=this.time,ae instanceof p&&(ae.initAngularVelocity.copy(ae.angularVelocity),ae.initQuaternion.copy(ae.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=ae,this.dispatchEvent(this.addBodyEvent))},S.prototype.addConstraint=function(ae){this.constraints.push(ae)},S.prototype.removeConstraint=function(ae){var ce=this.constraints.indexOf(ae);ce!==-1&&this.constraints.splice(ce,1)},S.prototype.rayTest=function(ae,ce,ie){ie instanceof g?this.raycastClosest(ae,ce,{skipBackfaces:!0},ie):this.raycastAll(ae,ce,{skipBackfaces:!0},ie)},S.prototype.raycastAll=function(ae,ce,ie,w){return ie.mode=E.ALL,ie.from=ae,ie.to=ce,ie.callback=w,b.intersectWorld(this,ie)},S.prototype.raycastAny=function(ae,ce,ie,w){return ie.mode=E.ANY,ie.from=ae,ie.to=ce,ie.result=w,b.intersectWorld(this,ie)},S.prototype.raycastClosest=function(ae,ce,ie,w){return ie.mode=E.CLOSEST,ie.from=ae,ie.to=ce,ie.result=w,b.intersectWorld(this,ie)},S.prototype.remove=function(ae){ae.world=null;var ce=this.bodies.length-1,ie=this.bodies,w=ie.indexOf(ae);if(w!==-1){ie.splice(w,1);for(var H=0;H!==ie.length;H++)ie[H].index=H;this.collisionMatrix.setNumObjects(ce),this.removeBodyEvent.body=ae,this.dispatchEvent(this.removeBodyEvent)}},S.prototype.removeBody=S.prototype.remove,S.prototype.addMaterial=function(ae){this.materials.push(ae)},S.prototype.addContactMaterial=function(ae){this.contactmaterials.push(ae),this.contactMaterialTable.set(ae.materials[0].id,ae.materials[1].id,ae)},typeof performance>"u"&&(performance={}),!performance.now){var R=Date.now();performance.timing&&performance.timing.navigationStart&&(R=performance.timing.navigationStart),performance.now=function(){return Date.now()-R}}var I=new n;S.prototype.step=function(ae,ce,ie){if(ie=ie||10,ce=ce||0,ce===0)this.internalStep(ae),this.time+=ae;else{var w=Math.floor((this.time+ce)/ae)-Math.floor(this.time/ae);w=Math.min(w,ie);for(var H=performance.now(),X=0;X!==w&&(this.internalStep(ae),!(performance.now()-H>ae*1e3));X++);this.time+=ce;for(var te=this.time%ae,Q=te/ae,_e=I,q=this.bodies,de=0;de!==q.length;de++){var ge=q[de];ge.type!==p.STATIC&&ge.sleepState!==p.SLEEPING?(ge.position.vsub(ge.previousPosition,_e),_e.scale(Q,_e),ge.position.vadd(_e,ge.interpolatedPosition)):(ge.interpolatedPosition.copy(ge.position),ge.interpolatedQuaternion.copy(ge.quaternion))}}};var N={type:"postStep"},O={type:"preStep"},L={type:"collide",body:null,contact:null},B=[],V=[],Z=[],ue=[];new n,new n,new n,new n,new n,new n,new n,new n,new n,new a;var oe=new a,me=new a,le=new n;S.prototype.internalStep=function(ae){this.dt=ae;var ce=this.contacts,ie=Z,w=ue,H=this.numObjects(),X=this.bodies,te=this.solver,Q=this.gravity,_e=this.doProfiling,q=this.profile,de=p.DYNAMIC,ge,ve=this.constraints,be=V;Q.norm();var Le=Q.x,Ye=Q.y,He=Q.z,Be=0;for(_e&&(ge=performance.now()),Be=0;Be!==H;Be++){var Ge=X[Be];if(Ge.type&de){var Bt=Ge.force,Mt=Ge.mass;Bt.x+=Mt*Le,Bt.y+=Mt*Ye,Bt.z+=Mt*He}}for(var Be=0,Vi=this.subsystems.length;Be!==Vi;Be++)this.subsystems[Be].update();_e&&(ge=performance.now()),ie.length=0,w.length=0,this.broadphase.collisionPairs(this,ie,w),_e&&(q.broadphase=performance.now()-ge);var jr=ve.length;for(Be=0;Be!==jr;Be++){var at=ve[Be];if(!at.collideConnected)for(var ei=ie.length-1;ei>=0;ei-=1)(at.bodyA===ie[ei]&&at.bodyB===w[ei]||at.bodyB===ie[ei]&&at.bodyA===w[ei])&&(ie.splice(ei,1),w.splice(ei,1))}this.collisionMatrixTick(),_e&&(ge=performance.now());var di=B,ci=ce.length;for(Be=0;Be!==ci;Be++)di.push(ce[Be]);ce.length=0;var Yi=this.frictionEquations.length;for(Be=0;Be!==Yi;Be++)be.push(this.frictionEquations[Be]);this.frictionEquations.length=0,this.narrowphase.getContacts(ie,w,this,ce,di,this.frictionEquations,be),_e&&(q.narrowphase=performance.now()-ge),_e&&(ge=performance.now());for(var Be=0;Be=0&&ti.material.friction>=0&&Ge.material.friction*ti.material.friction,Ge.material.restitution>=0&&ti.material.restitution>=0&&(at.restitution=Ge.material.restitution*ti.material.restitution)),te.addEquation(at),Ge.allowSleep&&Ge.type===p.DYNAMIC&&Ge.sleepState===p.SLEEPING&&ti.sleepState===p.AWAKE&&ti.type!==p.STATIC){var br=ti.velocity.norm2()+ti.angularVelocity.norm2(),vn=Math.pow(ti.sleepSpeedLimit,2);br>=vn*2&&(Ge._wakeUpAfterNarrowphase=!0)}if(ti.allowSleep&&ti.type===p.DYNAMIC&&ti.sleepState===p.SLEEPING&&Ge.sleepState===p.AWAKE&&Ge.type!==p.STATIC){var Yn=Ge.velocity.norm2()+Ge.angularVelocity.norm2(),Dn=Math.pow(Ge.sleepSpeedLimit,2);Yn>=Dn*2&&(ti._wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(Ge,ti,!0),this.collisionMatrixPrevious.get(Ge,ti)||(L.body=ti,L.contact=at,Ge.dispatchEvent(L),L.body=Ge,ti.dispatchEvent(L))}for(_e&&(q.makeContactConstraints=performance.now()-ge,ge=performance.now()),Be=0;Be!==H;Be++){var Ge=X[Be];Ge._wakeUpAfterNarrowphase&&(Ge.wakeUp(),Ge._wakeUpAfterNarrowphase=!1)}var jr=ve.length;for(Be=0;Be!==jr;Be++){var at=ve[Be];at.update();for(var ei=0,Wr=at.equations.length;ei!==Wr;ei++){var $n=at.equations[ei];te.addEquation($n)}}te.solve(ae,this),_e&&(q.solve=performance.now()-ge),te.removeAllEquations();var On=Math.pow;for(Be=0;Be!==H;Be++){var Ge=X[Be];if(Ge.type&de){var xn=On(1-Ge.linearDamping,ae),Nn=Ge.velocity;Nn.mult(xn,Nn);var hn=Ge.angularVelocity;if(hn){var Tn=On(1-Ge.angularDamping,ae);hn.mult(Tn,hn)}}}for(this.dispatchEvent(O),Be=0;Be!==H;Be++){var Ge=X[Be];Ge.preStep&&Ge.preStep.call(Ge)}_e&&(ge=performance.now());var Qr=oe,ur=me,da=this.stepnumber,wn=p.DYNAMIC|p.KINEMATIC,fa=da%(this.quatNormalizeSkip+1)===0,ao=this.quatNormalizeFast,pa=ae*.5;for(r.types.PLANE,r.types.CONVEXPOLYHEDRON,Be=0;Be!==H;Be++){var Zs=X[Be],Ue=Zs.force,ke=Zs.torque;if(Zs.type&wn&&Zs.sleepState!==p.SLEEPING){var Je=Zs.velocity,$e=Zs.angularVelocity,Wt=Zs.position,bt=Zs.quaternion,pt=Zs.invMass,Tt=Zs.invInertiaWorld;Je.x+=Ue.x*pt*ae,Je.y+=Ue.y*pt*ae,Je.z+=Ue.z*pt*ae,Zs.angularVelocity&&(Tt.vmult(ke,le),le.mult(ae,le),le.vadd($e,$e)),Wt.x+=Je.x*ae,Wt.y+=Je.y*ae,Wt.z+=Je.z*ae,Zs.angularVelocity&&(Qr.set($e.x,$e.y,$e.z,0),Qr.mult(bt,ur),bt.x+=pa*ur.x,bt.y+=pa*ur.y,bt.z+=pa*ur.z,bt.w+=pa*ur.w,fa&&(ao?bt.normalizeFast():bt.normalize())),Zs.aabb&&(Zs.aabbNeedsUpdate=!0),Zs.updateInertiaWorld&&Zs.updateInertiaWorld()}}for(this.clearForces(),this.broadphase.dirty=!0,_e&&(q.integrate=performance.now()-ge),this.time+=ae,this.stepnumber+=1,this.dispatchEvent(N),Be=0;Be!==H;Be++){var Ge=X[Be],Ne=Ge.postStep;Ne&&Ne.call(Ge)}if(this.allowSleep)for(Be=0;Be!==H;Be++)X[Be].sleepTick(this.time)},S.prototype.clearForces=function(){for(var ae=this.bodies,ce=ae.length,ie=0;ie!==ce;ie++){var w=ae[ie];w.force,w.torque,w.force.set(0,0,0),w.torque.set(0,0,0)}}},{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../material/ContactMaterial":24,"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Shape":43,"../solver/GSSolver":46,"../utils/EventTarget":49,"../utils/TupleDictionary":52,"../utils/Vec3Pool":54,"./Narrowphase":55}]},{},[2])(2)})})($C);var LN=$C.exports;const BN=FN(LN);class ks{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}}ks._BabylonFileParsers={};ks._IndividualBabylonFileParsers={};class aa{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in aa.Triggers)if(Object.prototype.hasOwnProperty.call(aa.Triggers,t)&&parseInt(t)===e)return!0;return!1}}aa.Triggers={};class KC{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 VN{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 he{static FromPromise(e,t){const i=new he;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 KC(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new VN(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._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 a of this._observers)if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.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 he;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}class ye{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=e*2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=ye.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=ye.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=ye.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+ye.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=ye.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*ye.Clamp(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=ye.Clamp((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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 RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=ye.TwoPi*Math.floor((e+Math.PI)/ye.TwoPi),e}static HCF(e,t){const i=e%t;return i===0?t:ye.HCF(t,i)}}ye.TwoPi=Math.PI*2;const Qu=1/2.2,__=2.2,Ks=(1+Math.sqrt(5))/2,$t=.001;class js{static BuildArray(e,t){const i=[];for(let s=0;s{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,o[e]=r),s.next=void 0,s.previous=void 0}}const kN=["push","splice","pop","shift","unshift"];function qC(o,e){const t=kN.map(i=>UN(o,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const jC={};function j(o,e){jC[o]=e}function Ds(o){return jC[o]}class Dr{static SetMatrixPrecision(e){if(Dr.MatrixTrackPrecisionChange=!1,e&&!Dr.MatrixUse64Bits&&Dr.MatrixTrackedMatrices)for(let t=0;tparseInt(o.toString().replace(/\W/g,""));class Re{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=kn(this.x),t=kn(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 Re.FromArrayToRef(e,t,this),this}asArray(){const e=[];return this.toArray(e,0),e}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){const t=new this.constructor(0,0);return this.scaleToRef(e,t),t}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=$t){return e&&ye.WithinEpsilon(this.x,e.x,t)&&ye.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){const i=Math.cos(e),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(0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this.x,this.y):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 Re(0,0)}static One(){return new Re(1,1)}static Random(e=0,t=1){return new Re(ye.RandomRange(e,t),ye.RandomRange(e,t))}static get ZeroReadOnly(){return Re._ZeroReadOnly}static FromArray(e,t=0){return new Re(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,s,r){const n=r*r,a=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)*a),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)*a);return new e.constructor(l,h)}static Clamp(e,t,i){let s=e.x;s=s>i.x?i.x:s,s=si.y?i.y:r,r=rt.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 Re.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,a=(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 a>0&&l>0&&a+l<2*r*n}static Distance(e,t){return Math.sqrt(Re.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 Re.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=Re.DistanceSquared(t,i);if(s===0)return Re.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,Re.Dot(e.subtract(t),r)/s)),a=t.add(r.multiplyByFloats(n,n));return Re.Distance(e,a)}}Re._ZeroReadOnly=Re.Zero();class T{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=kn(this._x),t=kn(this._y),i=kn(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){const e=[];return this.toArray(e,0),e}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return T.FromArrayToRef(e,t,this),this}toQuaternion(){return Se.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,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),a=t*Math.sin(i)*Math.sin(s);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,a=e._y,l=e._z,h=e._w,c=2*(a*r-l*s),u=2*(l*i-n*r),d=2*(n*s-a*i);return t._x=i+h*c+a*d-l*u,t._y=s+h*u+l*c-n*d,t._z=r+h*d+n*u-a*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=ot.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=T.Dot(n,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const l=-(T.Dot(t,s)+r)/a,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=$t){return e&&ye.WithinEpsilon(this._x,e._x,t)&&ye.WithinEpsilon(this._y,e._y,t)&&ye.WithinEpsilon(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.divideToRef(e,this)}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!ye.WithinEpsilon(t,i,e))return!0;const s=Math.abs(this._z);return!ye.WithinEpsilon(t,s,e)||!ye.WithinEpsilon(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}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=ot.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(ot.Matrix[0]),T.TransformCoordinatesToRef(this,ot.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ot.Vector3[0]),ot.Vector3[0].rotateByQuaternionToRef(e,ot.Vector3[0]),t.addToRef(ot.Vector3[0],i),i}cross(e){const t=new this.constructor;return T.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.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=T.Dot(e,i),n=T.Dot(t,i);return(r-s)/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(ot.Vector3[1]),r=t.normalizeToRef(ot.Vector3[2]);let n=T.Dot(s,r);n=ye.Clamp(n,-1,1);const a=Math.acos(n),l=ot.Vector3[3];return T.CrossToRef(s,r,l),T.Dot(l,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){ot.Vector3[0].copyFrom(e);const s=ot.Vector3[0];ot.Vector3[1].copyFrom(t);const r=ot.Vector3[1];ot.Vector3[2].copyFrom(i);const n=ot.Vector3[2],a=ot.Vector3[3],l=ot.Vector3[4];s.normalize(),r.normalize(),n.normalize(),T.CrossToRef(n,s,a),T.CrossToRef(a,n,l);const h=Math.atan2(T.Dot(r,a),T.Dot(r,l));return ye.NormalizeRadians(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=K.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=T.Zero();return T.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ye.Clamp(i,0,1);const r=ot.Vector3[0],n=ot.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),n.copyFrom(t);const l=n.length();n.normalizeFromLength(l);const h=T.Dot(r,n);let c,u;if(h<1-$t){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(ye.Lerp(a,l,i)),s}static SmoothToRef(e,t,i,s,r){return T.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new T(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return T.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 T.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new T(0,0,0)}static One(){return new T(1,1,1)}static Up(){return new T(0,1,0)}static get UpReadOnly(){return T._UpReadOnly}static get DownReadOnly(){return T._DownReadOnly}static get RightReadOnly(){return T._RightReadOnly}static get LeftReadOnly(){return T._LeftReadOnly}static get LeftHandedForwardReadOnly(){return T._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return T._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return T._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return T._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return T._ZeroReadOnly}static get OneReadOnly(){return T._OneReadOnly}static Down(){return new T(0,-1,0)}static Forward(e=!1){return new T(0,0,e?-1:1)}static Backward(e=!1){return new T(0,0,e?1:-1)}static Right(){return new T(1,0,0)}static Left(){return new T(-1,0,0)}static Random(e=0,t=1){return new T(ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t))}static TransformCoordinates(e,t){const i=T.Zero();return T.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return T.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=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=a*c,r._y=l*c,r._z=h*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=T.Zero();return T.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,a=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)*a),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)*a),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)*a);return new e.constructor(l,h,c)}static Clamp(e,t,i){const s=new e.constructor;return T.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:a,a=a0&&L<0?(V.copyFrom(n),Z=t,ue=i):L>0&&B<0?(V.copyFrom(l),Z=i,ue=s):(V.copyFrom(a).scaleInPlace(-1),Z=s,ue=t);const oe=ot.Vector3[9],me=ot.Vector3[4];if(Z.subtractToRef(E,R),ue.subtractToRef(E,oe),T.CrossToRef(R,oe,me),!(T.Dot(me,h)<0))return r.copyFrom(E),Math.abs(_*g);const ae=ot.Vector3[5];T.CrossToRef(V,me,ae),ae.normalize();const ce=ot.Vector3[9];ce.copyFrom(Z).subtractInPlace(E);const ie=ce.length();if(ie<$t)return r.copyFrom(Z),T.Distance(e,Z);ce.normalizeFromLength(ie);const w=T.Dot(ae,ce),H=ot.Vector3[7];H.copyFrom(E).addInPlace(ae.scaleInPlace(ie*w)),R.copyFrom(H).subtractInPlace(Z),_=V.length(),V.normalizeFromLength(_);let X=T.Dot(R,V)/Math.max(_,$t);return X=ye.Clamp(X,0,1),H.copyFrom(Z).addInPlace(V.scaleInPlace(X*_)),r.copyFrom(H),T.Distance(e,H)}static Center(e,t){return T.CenterToRef(e,t,T.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 T.RotationFromAxisToRef(e,t,i,s),s}static RotationFromAxisToRef(e,t,i,s){const r=ot.Quaternion[0];return Se.RotationQuaternionFromAxisToRef(e,t,i,r),r.toEulerAnglesToRef(s),s}}T._UpReadOnly=T.Up();T._DownReadOnly=T.Down();T._LeftHandedForwardReadOnly=T.Forward(!1);T._RightHandedForwardReadOnly=T.Forward(!0);T._LeftHandedBackwardReadOnly=T.Backward(!1);T._RightHandedBackwardReadOnly=T.Backward(!0);T._RightReadOnly=T.Right();T._LeftReadOnly=T.Left();T._ZeroReadOnly=T.Zero();T._OneReadOnly=T.One();class Dt{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=kn(this.x),t=kn(this.y),i=kn(this.z),s=kn(this.w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}asArray(){const e=[];return this.toArray(e,0),e}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 Dt.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}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=$t){return e&&ye.WithinEpsilon(this.x,e.x,t)&&ye.WithinEpsilon(this.y,e.y,t)&&ye.WithinEpsilon(this.z,e.z,t)&&ye.WithinEpsilon(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.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){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,0);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)}toVector3(){return new T(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 Dt(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 Dt.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 Dt(0,0,0,0)}static One(){return new Dt(1,1,1,1)}static Random(e=0,t=1){return new Dt(ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t),ye.RandomRange(e,t))}static get ZeroReadOnly(){return Dt._ZeroReadOnly}static Normalize(e){const t=Dt.Zero();return Dt.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(Dt.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 Dt.CenterToRef(e,t,Dt.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=Dt.Zero();return Dt.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Dt.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=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=a,r.y=l,r.z=h,r.w=c,r}static TransformNormal(e,t){const i=new e.constructor;return Dt.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],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=s,n}static FromVector3(e,t=0){return new Dt(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}Dt._ZeroReadOnly=Dt.Zero();class Se{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=kn(this._x),t=kn(this._y),i=kn(this._z),s=kn(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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=$t){return e&&ye.WithinEpsilon(this._x,e._x,t)&&ye.WithinEpsilon(this._y,e._y,t)&&ye.WithinEpsilon(this._z,e._z,t)&&ye.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,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)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,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),this}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 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=T.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,a=.4999999;if(n<-a)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)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 k.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return Se.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 Se;return Se.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[1],l=i[5],h=i[9],c=i[2],u=i[6],d=i[10],f=s+l+d;let p;return f>0?(p=.5/Math.sqrt(f+1),t._w=.25/p,t._x=(u-h)*p,t._y=(n-c)*p,t._z=(a-r)*p,t._isDirty=!0):s>l&&s>d?(p=2*Math.sqrt(1+s-l-d),t._w=(u-h)/p,t._x=.25*p,t._y=(r+a)/p,t._z=(n+c)/p,t._isDirty=!0):l>d?(p=2*Math.sqrt(1+l-s-d),t._w=(n-c)/p,t._x=(r+a)/p,t._y=.25*p,t._z=(h+u)/p,t._isDirty=!0):(p=2*Math.sqrt(1+d-s-l),t._w=(a-r)/p,t._x=(n+c)/p,t._y=(h+u)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=Se.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=ye.Clamp(n,0,1),Se.SlerpToRef(e,t,n,r),r}static Zero(){return new Se(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 Se(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 Se.RotationAxisToRef(e,t,new Se)}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 Se(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromEulerAngles(e,t,i){const s=new Se;return Se.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return Se.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new Se;return Se.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return Se.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=$t){const r=T.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(T.CrossToRef(e,t,K.Vector3[0]),i.set(K.Vector3[0].x,K.Vector3[0].y,K.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new Se;return Se.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,a=e*.5,l=Math.sin(r),h=Math.cos(r),c=Math.sin(n),u=Math.cos(n),d=Math.sin(a),f=Math.cos(a);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 Se;return Se.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,a=t*.5;return s._x=Math.cos(n)*Math.sin(a),s._y=Math.sin(n)*Math.sin(a),s._z=Math.sin(r)*Math.cos(a),s._w=Math.cos(r)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new Se(0,0,0,0);return Se.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=ot.Matrix[0];return k.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),Se.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new Se;return Se.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=ot.Matrix[0];return k.LookDirectionLHToRef(e,t,s),Se.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new Se;return Se.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=ot.Matrix[0];return k.LookDirectionRHToRef(e,t,s),Se.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=Se.Identity();return Se.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(a<0&&(l=!0,a=-a),a>.999999)n=1-i,r=l?-i:i;else{const h=Math.acos(a),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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e._z*l+i._z*h+t._z*c+s._z*u,_=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 a=r*r;return n._x=(a-r)*6*e._x+(3*a-4*r+1)*t._x+(-a+r)*6*i._x+(3*a-2*r)*s._x,n._y=(a-r)*6*e._y+(3*a-4*r+1)*t._y+(-a+r)*6*i._y+(3*a-2*r)*s._y,n._z=(a-r)*6*e._z+(3*a-4*r+1)*t._z+(-a+r)*6*i._z+(3*a-2*r)*s._z,n._w=(a-r)*6*e._w+(3*a-4*r+1)*t._w+(-a+r)*6*i._w+(3*a-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=Se.Zero();return Se.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}}class k{static get Use64Bits(){return Dr.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=k._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,Dr.MatrixTrackPrecisionChange&&Dr.MatrixTrackedMatrices.push(this),this._m=new Dr.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],a=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],f=e[11],p=e[12],_=e[13],g=e[14],v=e[15],E=d*v-g*f,C=u*v-_*f,S=u*g-_*d,b=c*v-p*f,R=c*g-d*p,I=c*_-p*u,N=+(a*E-l*C+h*S),O=-(n*E-l*b+h*R),L=+(n*C-a*b+h*I),B=-(n*S-a*R+l*I);return t*N+i*O+s*L+r*B}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(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return k.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}invertToRef(e){if(this._isIdentity===!0)return k.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],f=t[10],p=t[11],_=t[12],g=t[13],v=t[14],E=t[15],C=f*E-v*p,S=d*E-g*p,b=d*v-g*f,R=u*E-_*p,I=u*v-f*_,N=u*g-_*d,O=+(l*C-h*S+c*b),L=-(a*C-h*R+c*I),B=+(a*S-l*R+c*N),V=-(a*b-l*I+h*N),Z=i*O+s*L+r*B+n*V;if(Z===0)return e.copyFrom(this),e;const ue=1/Z,oe=h*E-v*c,me=l*E-g*c,le=l*v-g*h,ae=a*E-_*c,ce=a*v-_*h,ie=a*g-_*l,w=h*p-f*c,H=l*p-d*c,X=l*f-d*h,te=a*p-u*c,Q=a*f-u*h,_e=a*d-u*l,q=-(s*C-r*S+n*b),de=+(i*C-r*R+n*I),ge=-(i*S-s*R+n*N),ve=+(i*b-s*I+r*N),be=+(s*oe-r*me+n*le),Le=-(i*oe-r*ae+n*ce),Ye=+(i*me-s*ae+n*ie),He=-(i*le-s*ce+r*ie),Be=-(s*w-r*H+n*X),Ge=+(i*w-r*te+n*Q),Lt=-(i*H-s*te+n*_e),Mt=+(i*X-s*Q+r*_e);return k.FromValuesToRef(O*ue,q*ue,be*ue,Be*ue,L*ue,de*ue,Le*ue,Ge*ue,B*ue,ge*ue,Ye*ue,Lt*ue,V*ue,ve*ue,He*ue,Mt*ue,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 T(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 k.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}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],a=s[1],l=s[2],h=s[3],c=s[4],u=s[5],d=s[6],f=s[7],p=s[8],_=s[9],g=s[10],v=s[11],E=s[12],C=s[13],S=s[14],b=s[15],R=r[0],I=r[1],N=r[2],O=r[3],L=r[4],B=r[5],V=r[6],Z=r[7],ue=r[8],oe=r[9],me=r[10],le=r[11],ae=r[12],ce=r[13],ie=r[14],w=r[15];return t[i]=n*R+a*L+l*ue+h*ae,t[i+1]=n*I+a*B+l*oe+h*ce,t[i+2]=n*N+a*V+l*me+h*ie,t[i+3]=n*O+a*Z+l*le+h*w,t[i+4]=c*R+u*L+d*ue+f*ae,t[i+5]=c*I+u*B+d*oe+f*ce,t[i+6]=c*N+u*V+d*me+f*ie,t[i+7]=c*O+u*Z+d*le+f*w,t[i+8]=p*R+_*L+g*ue+v*ae,t[i+9]=p*I+_*B+g*oe+v*ce,t[i+10]=p*N+_*V+g*me+v*ie,t[i+11]=p*O+_*Z+g*le+v*w,t[i+12]=E*R+C*L+S*ue+b*ae,t[i+13]=E*I+C*B+S*oe+b*ce,t[i+14]=E*N+C*V+S*me+b*ie,t[i+15]=E*O+C*Z+S*le+b*w,this}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,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]}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=kn(this._m[0]);for(let t=1;t<16;t++)e=e*397^kn(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Se,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||ot.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 a=(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*=a,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 a=1/e._x,l=1/e._y,h=1/e._z;k.FromValuesToRef(n[0]*a,n[1]*a,n[2]*a,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,ot.Matrix[0]),Se.FromRotationMatrixToRef(ot.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Dt(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 k.TransposeToRef(this,e),e}transposeToRef(e){return k.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}toNormalMatrix(e){const t=ot.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return k.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=ot.Vector3[0];if(!this.decompose(t))return k.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return k.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 k;return k.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 k._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v){const E=v._m;E[0]=e,E[1]=t,E[2]=i,E[3]=s,E[4]=r,E[5]=n,E[6]=a,E[7]=l,E[8]=h,E[9]=c,E[10]=u,E[11]=d,E[12]=f,E[13]=p,E[14]=_,E[15]=g,v.markAsUpdated()}static FromValues(e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g){const v=new k,E=v._m;return E[0]=e,E[1]=t,E[2]=i,E[3]=s,E[4]=r,E[5]=n,E[6]=a,E[7]=l,E[8]=h,E[9]=c,E[10]=u,E[11]=d,E[12]=f,E[13]=p,E[14]=_,E[15]=g,v.markAsUpdated(),v}static Compose(e,t,i){const s=new k;return k.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,a=t._y,l=t._z,h=t._w,c=n+n,u=a+a,d=l+l,f=n*c,p=n*u,_=n*d,g=a*u,v=a*d,E=l*d,C=h*c,S=h*u,b=h*d,R=e._x,I=e._y,N=e._z;return r[0]=(1-(g+E))*R,r[1]=(p+b)*R,r[2]=(_-S)*R,r[3]=0,r[4]=(p-b)*I,r[5]=(1-(f+E))*I,r[6]=(v+C)*I,r[7]=0,r[8]=(_+S)*N,r[9]=(v-C)*N,r[10]=(1-(f+g))*N,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=k.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 k.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=k.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 k;return k.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 k.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 k;return k.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return k.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 k;return k.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return k.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 k;return k.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 a=i._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*s,a[2]=e._x*e._z*n+e._y*s,a[3]=0,a[4]=e._y*e._x*n+e._z*s,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*s,a[7]=0,a[8]=e._z*e._x*n-e._y*s,a[9]=e._z*e._y*n+e._x*s,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=T.Dot(t,e),n=i._m;if(r<-1+$t)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 a=T.Cross(t,e),l=1/(1+r);n[0]=a._x*a._x*l+r,n[1]=a._y*a._x*l-a._z,n[2]=a._z*a._x*l+a._y,n[3]=0,n[4]=a._x*a._y*l+a._z,n[5]=a._y*a._y*l+r,n[6]=a._z*a._y*l-a._x,n[7]=0,n[8]=a._x*a._z*l-a._y,n[9]=a._y*a._z*l+a._x,n[10]=a._z*a._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 k;return k.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return Se.RotationYawPitchRollToRef(e,t,i,ot.Quaternion[0]),ot.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new k;return k.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return k.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 k;return k.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return k.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 k.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,a=t.m;for(let l=0;l<16;l++)r[l]=n[l]*(1-i)+a[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return k.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Quaternion[0],a=ot.Vector3[1];e.decompose(r,n,a);const l=ot.Vector3[2],h=ot.Quaternion[1],c=ot.Vector3[3];t.decompose(l,h,c);const u=ot.Vector3[4];T.LerpToRef(r,l,i,u);const d=ot.Quaternion[2];Se.SlerpToRef(n,h,i,d);const f=ot.Vector3[5];return T.LerpToRef(a,c,i,f),k.ComposeToRef(u,d,f,s),s}static LookAtLH(e,t,i){const s=new k;return k.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Vector3[1],a=ot.Vector3[2];t.subtractToRef(e,a),a.normalize(),T.CrossToRef(i,a,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(a,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(a,e);return k.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,c,u,1,s),s}static LookAtRH(e,t,i){const s=new k;return k.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Vector3[1],a=ot.Vector3[2];e.subtractToRef(t,a),a.normalize(),T.CrossToRef(i,a,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(a,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(a,e);return k.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new k;return k.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=ot.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=ot.Vector3[1];return T.CrossToRef(t,s,r),k.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 k;return k.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=ot.Vector3[2];return T.CrossToRef(t,e,s),k.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 k;return k.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const a=i,l=s,h=2/e,c=2/t,u=2/(l-a),d=-(l+a)/(l-a);return k.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,d,1,r),n&&r.multiplyToRef(Dh,r),r._updateIdentityStatus(h===1&&c===1&&u===1&&d===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,a){const l=new k;return k.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,a),l}static OrthoOffCenterLHToRef(e,t,i,s,r,n,a,l){const h=r,c=n,u=2/(t-e),d=2/(s-i),f=2/(c-h),p=-(c+h)/(c-h),_=(e+t)/(e-t),g=(s+i)/(i-s);return k.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,f,0,_,g,p,1,a),l&&a.multiplyToRef(Dh,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,a,l,h,c,u){const d=-a*Math.cos(l),f=-a*Math.sin(l);return k.TranslationToRef(0,0,-h,ot.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,ot.Matrix[0]),ot.Matrix[1].multiplyToRef(ot.Matrix[0],ot.Matrix[0]),k.TranslationToRef(0,0,h,ot.Matrix[1]),ot.Matrix[0].multiplyToRef(ot.Matrix[1],ot.Matrix[0]),k.OrthoOffCenterLHToRef(e,t,i,s,r,n,c,u),ot.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,r,n,a){const l=new k;return k.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,a),l}static OrthoOffCenterRHToRef(e,t,i,s,r,n,a,l){return k.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,l),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,a,l,h,c,u){const d=a*Math.cos(l),f=a*Math.sin(l);return k.TranslationToRef(0,0,h,ot.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,ot.Matrix[0]),ot.Matrix[1].multiplyToRef(ot.Matrix[0],ot.Matrix[0]),k.TranslationToRef(0,0,-h,ot.Matrix[1]),ot.Matrix[0].multiplyToRef(ot.Matrix[1],ot.Matrix[0]),k.OrthoOffCenterRHToRef(e,t,i,s,r,n,c,u),ot.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,r,n=0){const a=new k,l=i,h=s,c=2*l/e,u=2*l/t,d=(h+l)/(h-l),f=-2*h*l/(h-l),p=Math.tan(n);return k.FromValuesToRef(c,0,0,0,0,u,0,p,0,0,d,1,0,0,f,0,a),r&&a.multiplyToRef(Dh,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,r,n=0,a=!1){const l=new k;return k.PerspectiveFovLHToRef(e,t,i,s,l,!0,r,n,a),l}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,a,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,p=n?d:d*t,_=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,v=Math.tan(l);return k.FromValuesToRef(f,0,0,0,0,p,0,v,0,0,_,1,0,0,g,0,r),a&&r.multiplyToRef(Dh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,a,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return k.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(Dh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,a=!1){const l=new k;return k.PerspectiveFovRHToRef(e,t,i,s,l,!0,r,n,a),l}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,a,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,p=n?d:d*t,_=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,v=Math.tan(l);return k.FromValuesToRef(f,0,0,0,0,p,0,v,0,0,_,-1,0,0,g,0,r),a&&r.multiplyToRef(Dh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,a,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return k.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(Dh,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const a=e.width,l=e.height,h=e.x,c=e.y,u=k.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,n-r,0,h+a/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 Dr.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 Dr.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return k.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[12],l=i[1],h=i[5],c=i[9],u=i[13],d=i[2],f=i[6],p=i[10],_=i[14],g=i[3],v=i[7],E=i[11],C=i[15],S=t._m;return S[0]=s,S[1]=r,S[2]=n,S[3]=a,S[4]=l,S[5]=h,S[6]=c,S[7]=u,S[8]=d,S[9]=f,S[10]=p,S[11]=_,S[12]=g,S[13]=v,S[14]=E,S[15]=C,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new k;return k.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,a=-2*s,l=-2*r;return k.FromValuesToRef(n*i+1,a*i,l*i,0,n*s,a*s+1,l*s,0,n*r,a*r,l*r+1,0,n*e.d,a*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return k.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,a=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+a),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(n-a),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}}k._UpdateFlagSeed=0;k._IdentityReadOnly=k.Identity();class ot{}ot.Vector3=js.BuildTuple(11,T.Zero);ot.Matrix=js.BuildTuple(2,k.Identity);ot.Quaternion=js.BuildTuple(3,Se.Zero);class K{}K.Vector2=js.BuildTuple(3,Re.Zero);K.Vector3=js.BuildTuple(13,T.Zero);K.Vector4=js.BuildTuple(3,Dt.Zero);K.Quaternion=js.BuildTuple(2,Se.Zero);K.Matrix=js.BuildTuple(8,k.Identity);j("BABYLON.Vector2",Re);j("BABYLON.Vector3",T);j("BABYLON.Vector4",Dt);j("BABYLON.Matrix",k);const Dh=k.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);function Vc(o){return Math.pow(o,__)}function Uc(o){return o<=.04045?.0773993808*o:Math.pow(.947867299*(o+.055),2.4)}function kc(o){return Math.pow(o,Qu)}function Gc(o){return o<=.0031308?12.92*o:1.055*Math.pow(o,.41666)-.055}class Te{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 Te.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ze(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 Te(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new Te(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=ye.Clamp(this.r,e,t),i.g=ye.Clamp(this.g,e,t),i.b=ye.Clamp(this.b,e,t),this}add(e){return new Te(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new Te(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this}clone(){return new Te(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+ye.ToHex(e)+ye.ToHex(t)+ye.ToHex(i)}toHSV(){const e=new Te;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 a=0,l=0;const h=r,c=r-n;r!==0&&(l=c/r),r!=n&&(r==t?(a=(i-s)/c,i=0&&n<=1?(l=r,h=a):n>=1&&n<=2?(l=a,h=r):n>=2&&n<=3?(h=r,c=a):n>=3&&n<=4?(h=a,c=r):n>=4&&n<=5?(l=a,c=r):n>=5&&n<=6&&(l=r,c=a);const u=i-r;s.set(l+u,h+u,c+u)}static FromHSV(e,t,i){const s=new Te(0,0,0);return Te.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Te(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 Te.FromInts(t,i,s)}static FromArray(e,t=0){return new Te(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 Te(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Te(0,0,0);return Te.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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e.b*l+i.b*h+t.b*c+s.b*u;return new Te(d,f,p)}static Hermite1stDerivative(e,t,i,s,r){const n=Te.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b}static Red(){return new Te(1,0,0)}static Green(){return new Te(0,1,0)}static Blue(){return new Te(0,0,1)}static Black(){return new Te(0,0,0)}static get BlackReadOnly(){return Te._BlackReadOnly}static White(){return new Te(1,1,1)}static Purple(){return new Te(.5,0,.5)}static Magenta(){return new Te(1,0,1)}static Yellow(){return new Te(1,1,0)}static Gray(){return new Te(.5,.5,.5)}static Teal(){return new Te(0,1,1)}static Random(){return new Te(Math.random(),Math.random(),Math.random())}}Te._BlackReadOnly=Te.Black();class Ze{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return Ze.FromArrayToRef(e,t,this),this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ze(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Ze(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this}scale(e){return new Ze(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=ye.Clamp(this.r,e,t),i.g=ye.Clamp(this.g,e,t),i.b=ye.Clamp(this.b,e,t),i.a=ye.Clamp(this.a,e,t),this}multiply(e){return new Ze(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=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 Ze(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,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)}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"#"+ye.ToHex(t)+ye.ToHex(i)+ye.ToHex(s);const r=Math.round(this.a*255);return"#"+ye.ToHex(t)+ye.ToHex(i)+ye.ToHex(s)+ye.ToHex(r)}toLinearSpace(e=!1){const t=new Ze;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Uc(this.r),e.g=Uc(this.g),e.b=Uc(this.b)):(e.r=Vc(this.r),e.g=Vc(this.g),e.b=Vc(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ze;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Gc(this.r),e.g=Gc(this.g),e.b=Gc(this.b)):(e.r=kc(this.r),e.g=kc(this.g),e.b=kc(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Ze(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 Ze.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Ze(0,0,0,0);return Ze.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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e.b*l+i.b*h+t.b*c+s.b*u,_=e.a*l+i.a*h+t.a*c+s.a*u;return new Ze(d,f,p,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ze;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b,n.a=(a-r)*6*e.a+(3*a-4*r+1)*t.a+(-a+r)*6*i.a+(3*a-2*r)*s.a}static FromColor3(e,t=1){return new Ze(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ze(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 Ze(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew Ze(0,0,0,0));j("BABYLON.Color3",Te);j("BABYLON.Color4",Ze);class Qi{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new he,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){}_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}}Qi._SerializeValueAsString=o=>typeof o=="number"?o.toString():typeof o=="boolean"?o?"true":"false":o instanceof Re?o.x+", "+o.y:o instanceof T?o.x+", "+o.y+", "+o.z:o instanceof Te?o.r+", "+o.g+", "+o.b:o instanceof Ze?o.r+", "+o.g+", "+o.b+", "+o.a:o;Qi._GetTargetProperty=o=>({name:"target",targetType:o._isMesh?"MeshProperties":o._isLight?"LightProperties":o._isCamera?"CameraProperties":o._isMaterial?"MaterialProperties":"SceneProperties",value:o._isScene?"Scene":o.name});j("BABYLON.Action",Qi);class _r{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 _r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new _r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new _r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new _r(e,t.x,t.y,null,i,s)}}class Sd{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 pr extends Sd{static get IsEqual(){return pr._IsEqual}static get IsDifferent(){return pr._IsDifferent}static get IsGreater(){return pr._IsGreater}static get IsLesser(){return pr._IsLesser}constructor(e,t,i,s,r=pr.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 pr.IsGreater:return this._effectiveTarget[this._property]>this.value;case pr.IsLesser:return this._effectiveTarget[this._property]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&&!G._CheckLimit(s,i))return;const r=G._FormatMessage(s),n=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...a);const l=`
${r}

`;G._AddLogEntry(l),G._GenerateLimitMessage(s,e)}static get LogCache(){return G._LogCache}static ClearLogCache(){G._LogCache="",G._LogLimitOutputs={},G.errorsCount=0}static set LogLevels(e){G.Log=G._LogDisabled,G.Warn=G._LogDisabled,G.Error=G._LogDisabled,[G.MessageLogLevel,G.WarningLogLevel,G.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];G[i.name]=G._LogEnabled.bind(G,t)}})}}G.NoneLogLevel=0;G.MessageLogLevel=1;G.WarningLogLevel=2;G.ErrorLogLevel=4;G.AllLogLevel=7;G.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";G._LogCache="";G._LogLimitOutputs={};G._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];G.errorsCount=0;G.Log=G._LogEnabled.bind(G,G.MessageLogLevel);G.Warn=G._LogEnabled.bind(G,G.WarningLogLevel);G.Error=G._LogEnabled.bind(G,G.ErrorLogLevel);class kN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class GN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class zN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)}]},e)}}class WN extends Qi{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"&&G.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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)}]},e)}}class HN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Qi._SerializeValueAsString(this.loop)||!1}]},e)}}class XN extends Qi{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:[Qi._GetTargetProperty(this._target)]},e)}}class qC extends Qi{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class YN extends Qi{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;e!o||o.getClassName&&o.getClassName()==="Mesh"?null:o.getClassName&&(o.getClassName()==="SubMesh"||o.getClassName()==="PhysicsBody")?o.clone(e):o.clone?o.clone():Array.isArray(o)?o.slice():t&&typeof o=="object"?Object.assign({},o):null;function KN(o){const e=[];do Object.getOwnPropertyNames(o).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(o=Object.getPrototypeOf(o));return e}class Ur{static DeepCopy(e,t,i,s,r=!1){const n=KN(e);for(const a of n){if(a[0]==="_"&&(!s||s.indexOf(a)===-1)||a.endsWith("Observable")||i&&i.indexOf(a)!==-1)continue;const l=e[a],h=typeof l;if(h!=="function")try{if(h==="object")if(l instanceof Uint8Array)t[a]=Uint8Array.from(l);else if(l instanceof Array){if(t[a]=[],l.length>0)if(typeof l[0]=="object")for(let c=0;c-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-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Ii.OnPickTrigger&&t.trigger<=Ii.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Ii.OnPickTrigger&&t.trigger<=Ii.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Ii.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(G.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Ii.Triggers[e.trigger]?Ii.Triggers[e.trigger]++:Ii.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),Ii.Triggers[e.trigger]-=1,Ii.Triggers[e.trigger]===0&&delete Ii.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const c=Ds("BABYLON."+l);return c&&new c(...h)},n=(l,h,c,u)=>{if(u===null){const _=parseFloat(h);return h==="true"||h==="false"?h==="true":isNaN(_)?h:_}const d=u.split("."),f=h.split(",");for(let _=0;_{if(l.detached)return;const f=[];let p=null,_=null;const g=l.combine&&l.combine.length>0;if(l.type===2?f.push(s):f.push(h),g){const E=[];for(let C=0;C0){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:Ii[c.name],parameter:d}}else h=Ii[c.name];for(let u=0;u(i=i.slice(1,i.length-1),Nh._HandleParenthesisContent(i,t))):e=Nh._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Nh.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=Nh._SimplifyNegation(s[r].trim());const a=n.split("&&");if(a.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class ui{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ui.HasTags(e),e.addTags=t=>ui.AddTagsTo(e,t),e.removeTags=t=>ui.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ui.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){ui._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ui.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ui.HasTags(e))return;const i=t.split(" ");for(const s in i)ui._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?ui.HasTags(e):Nh.Eval(t,i=>ui.HasTags(e)&&e._tags[i])}}const US={};function xt(o,e=!1){if(!(e&&US[o]))return US[o]=!0,`${o} needs to be imported before as it contains a side-effect required by your code.`}const m_={},s_={},kS=function(o,e,t,i={}){const s=o();ui&&ui.HasTags(e)&&ui.AddTagsTo(s,ui.GetTags(e,!0));const r=Pv(s),n={};for(const a in r){const l=r[a],h=e[a],c=l.type;if(h!=null&&(a!=="uniqueId"||Xe.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[a]=h;break;case 1:i.cloneTexturesOnlyOnce&&n[h.uniqueId]?s[a]=n[h.uniqueId]:(s[a]=t||h.isRenderTarget?h:h.clone(),n[h.uniqueId]=s[a]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[a]=t?h:h.clone();break}}return s};function QN(o){const e=o.getClassName();return m_[e]||(m_[e]={}),m_[e]}function Pv(o){const e=o.getClassName();if(s_[e])return s_[e];s_[e]={};const t=s_[e];let i=o,s=e;for(;s;){const r=m_[s];for(const l in r)t[l]=r[l];let n,a=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){a=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(a)break;s=n.getClassName(),i=n}return t}function Fa(o,e){return(t,i)=>{const s=QN(t);s[i]||(s[i]={type:o,sourceName:e})}}function ZN(o,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[o].apply(this))},enumerable:!0,configurable:!0})}}function Ce(o,e=null){return ZN(o,e)}function D(o){return Fa(0,o)}function Jt(o){return Fa(1,o)}function ds(o){return Fa(2,o)}function jf(o){return Fa(3,o)}function ix(o){return Fa(4,o)}function kr(o){return Fa(5,o)}function Qf(o){return Fa(6,o)}function JN(o){return Fa(7,o)}function sx(o){return Fa(8,o)}function QC(o){return Fa(9,o)}function ew(o){return Fa(10,o)}function rx(o){return Fa(12,o)}function tw(o){return Fa(11,o)}class Xe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw xt("ImageProcessingConfiguration")};Xe._FresnelParametersParser=o=>{throw xt("FresnelParameters")};Xe._ColorCurvesParser=o=>{throw xt("ColorCurves")};Xe._TextureParser=(o,e,t)=>{throw xt("Texture")};function hh(o,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const a=_native[e];i?n=(...l)=>i(...l)?a(...l):s(...l):n=a}return o[e]=n,n(...r)}}hh.filter=function(o){return(e,t,i)=>hh(e,t,i,o)};var Mv;(function(o){o[o.NONE=0]="NONE",o[o.STEP=1]="STEP"})(Mv||(Mv={}));class qc{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new qc(this.name,this.from,this.to)}}function A(o,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(o,e,t,i);else for(var a=o.length-1;a>=0;a--)(n=o[a])&&(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}class iw{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new he,this._onClonedObservable=new he}}let Mi=class Dv{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 iw,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new he,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=k.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new he,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||ht.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(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew Dv(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n{throw xt("AnimationRange")};Mi._NodeConstructors={};A([D()],Mi.prototype,"name",void 0);A([D()],Mi.prototype,"id",void 0);A([D()],Mi.prototype,"uniqueId",void 0);A([D()],Mi.prototype,"state",void 0);A([D()],Mi.prototype,"metadata",void 0);class ya{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 ya(this.width*e,this.height*t)}clone(){return new ya(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 ya(0,0)}add(e){return new ya(this.width+e.width,this.height+e.height)}subtract(e){return new ya(this.width-e.width,this.height-e.height)}scale(e){return new ya(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 ya(s,r)}}function sw(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class Hs{constructor(){this._xhr=sw(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Hs.CustomRequestHeaders).length>0||Hs.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Hs.CustomRequestHeaders){const t=Hs.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Hs.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){Hs.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of Hs.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}return 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)}}Hs.CustomRequestHeaders={};Hs.CustomRequestModifiers=new Array;Hs.SkipRequestModificationForBabylonCDN=!0;const ZC=Object.freeze(new Se(0,0,0,0)),JC=Object.freeze(T.Zero()),eb=Object.freeze(Re.Zero()),tb=Object.freeze(ya.Zero()),ib=Object.freeze(Te.Black()),sb=Object.freeze(new Ze(0,0,0,0)),_o={key:0,repeatCount:0,loopMode:2};class Ee{static _PrepareAnimation(e,t,i,s,r,n,a,l){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=Ee.ANIMATIONTYPE_FLOAT:r instanceof Se?h=Ee.ANIMATIONTYPE_QUATERNION:r instanceof T?h=Ee.ANIMATIONTYPE_VECTOR3:r instanceof Re?h=Ee.ANIMATIONTYPE_VECTOR2:r instanceof Te?h=Ee.ANIMATIONTYPE_COLOR3:r instanceof Ze?h=Ee.ANIMATIONTYPE_COLOR4:r instanceof ya&&(h=Ee.ANIMATIONTYPE_SIZE),h==null)return null;const c=new Ee(e,t,i,h,a),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 Ee(e+"Animation",e,i,t,Ee.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,a,l,h,c,u){const d=Ee._PrepareAnimation(e,i,s,r,n,a,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,a,l,h,c,u){const d=Ee._PrepareAnimation(e,s,r,n,a,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,a,l,h,c){const u=Ee._PrepareAnimation(e,i,s,r,n,a,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){var n,a;let l;typeof t=="object"?l=t:l={referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let h=e;if(l.cloneOriginalAnimation&&(h=e.clone(),h.name=l.clonedAnimationName||h.name),!h._keys.length)return h;const c=l.referenceFrame&&l.referenceFrame>=0?l.referenceFrame:0;let u=0;const d=h._keys[0];let f=h._keys.length-1;const p=h._keys[f],_={referenceValue:d.value,referencePosition:K.Vector3[0],referenceQuaternion:K.Quaternion[0],referenceScaling:K.Vector3[1],keyPosition:K.Vector3[2],keyQuaternion:K.Quaternion[1],keyScaling:K.Vector3[3]};let g=d.frame,v=p.frame;if(l.range){const S=h.getRange(l.range);S&&(g=S.from,v=S.to)}else g=(n=l.fromFrame)!==null&&n!==void 0?n:g,v=(a=l.toFrame)!==null&&a!==void 0?a:v;if(g!==d.frame&&(u=h.createKeyForFrame(g)),v!==p.frame&&(f=h.createKeyForFrame(v)),h._keys.length===1){const S=h._getKeyValue(h._keys[0]);_.referenceValue=S.clone?S.clone():S}else if(c<=d.frame){const S=h._getKeyValue(d.value);_.referenceValue=S.clone?S.clone():S}else if(c>=p.frame){const S=h._getKeyValue(p.value);_.referenceValue=S.clone?S.clone():S}else{_o.key=0;const S=h._interpolate(c,_o);_.referenceValue=S.clone?S.clone():S}h.dataType===Ee.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():h.dataType===Ee.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let E=Number.MAX_VALUE;const C=l.clipKeys?[]:null;for(let S=u;S<=f;S++){let b=h._keys[S];if(C&&(b={frame:b.frame,value:b.value.clone?b.value.clone():b.value,inTangent:b.inTangent,outTangent:b.outTangent,interpolation:b.interpolation,lockedTangent:b.lockedTangent},E===Number.MAX_VALUE&&(E=b.frame),b.frame-=E,C.push(b)),!(S&&h.dataType!==Ee.ANIMATIONTYPE_FLOAT&&b.value===d.value))switch(h.dataType){case Ee.ANIMATIONTYPE_MATRIX:b.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),k.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,b.value);break;case Ee.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(b.value,b.value);break;case Ee.ANIMATIONTYPE_VECTOR2:case Ee.ANIMATIONTYPE_VECTOR3:case Ee.ANIMATIONTYPE_COLOR3:case Ee.ANIMATIONTYPE_COLOR4:b.value.subtractToRef(_.referenceValue,b.value);break;case Ee.ANIMATIONTYPE_SIZE:b.value.width-=_.referenceValue.width,b.value.height-=_.referenceValue.height;break;default:b.value-=_.referenceValue}}return C&&h.setKeys(C,!0),h}static TransitionTo(e,t,i,s,r,n,a,l=null){if(a<=0)return i[e]=t,l&&l(),null;const h=r*(a/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?Ee.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ee._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const s in this._ranges)i&&(t+=", ",i=!1),t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;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;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,n=r.length;let a=t.key;for(;a>=0&&e=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>n-1)return i?void 0:this._getKeyValue(r[n-1].value);const l=r[a],h=r[a+1];if(i&&(e===l.frame||e===h.frame))return;const c=this._getKeyValue(l.value),u=this._getKeyValue(h.value);if(l.interpolation===Mv.STEP)return h.frame>e?c:u;const d=l.outTangent!==void 0&&h.inTangent!==void 0,f=h.frame-l.frame;let p=(e-l.frame)/f;const _=l.easingFunction||this.getEasingFunction();switch(_!==null&&(p=_.ease(p)),this.dataType){case Ee.ANIMATIONTYPE_FLOAT:{const g=d?this.floatInterpolateFunctionWithTangents(c,l.outTangent*f,u,h.inTangent*f,p):this.floatInterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((s=t.offsetValue)!==null&&s!==void 0?s:0)*t.repeatCount+g}break}case Ee.ANIMATIONTYPE_QUATERNION:{const g=d?this.quaternionInterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.quaternionInterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((t.offsetValue||ZC).scale(t.repeatCount))}return g}case Ee.ANIMATIONTYPE_VECTOR3:{const g=d?this.vector3InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.vector3InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||JC).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_VECTOR2:{const g=d?this.vector2InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.vector2InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||eb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(c,u,p);case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(c,u,p).add((t.offsetValue||tb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_COLOR3:{const g=d?this.color3InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.color3InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||ib).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_COLOR4:{const g=d?this.color4InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.color4InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||sb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return Ee.AllowMatricesInterpolation?this.matrixInterpolateFunction(c,u,p,t.workValue):c;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return c}break}}return 0}matrixInterpolateFunction(e,t,i,s){return Ee.AllowMatrixDecomposeForInterpolation?s?(k.DecomposeLerpToRef(e,t,i,s),s):k.DecomposeLerp(e,t,i):s?(k.LerpToRef(e,t,i,s),s):k.Lerp(e,t,i)}clone(){const e=new Ee(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){_o.key=0;const t=this._interpolate(e,_o,!0);if(!t)return this._keys[_o.key].frame===e?_o.key:_o.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(_o.key+1,0,i),_o.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(l=a.values[1]),a.values.length>=3&&(h=a.values[2]),a.values.length>=4&&(c=a.values[3]);break;case Ee.ANIMATIONTYPE_QUATERNION:if(r=Se.FromArray(a.values),a.values.length>=8){const d=Se.FromArray(a.values.slice(4,8));d.equals(Se.Zero())||(l=d)}if(a.values.length>=12){const d=Se.FromArray(a.values.slice(8,12));d.equals(Se.Zero())||(h=d)}a.values.length>=13&&(c=a.values[12]);break;case Ee.ANIMATIONTYPE_MATRIX:r=k.FromArray(a.values),a.values.length>=17&&(c=a.values[16]);break;case Ee.ANIMATIONTYPE_COLOR3:r=Te.FromArray(a.values),a.values[3]&&(l=Te.FromArray(a.values[3])),a.values[4]&&(h=Te.FromArray(a.values[4])),a.values[5]&&(c=a.values[5]);break;case Ee.ANIMATIONTYPE_COLOR4:r=Ze.FromArray(a.values),a.values[4]&&(l=Ze.FromArray(a.values[4])),a.values[5]&&(h=Ze.FromArray(a.values[5])),a.values[6]&&(c=Ze.FromArray(a.values[6]));break;case Ee.ANIMATIONTYPE_VECTOR3:default:r=T.FromArray(a.values),a.values[3]&&(l=T.FromArray(a.values[3])),a.values[4]&&(h=T.FromArray(a.values[4])),a.values[5]&&(c=a.values[5]);break}const u={};u.frame=a.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{const r=new Hs;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 a=[];for(const l of n)a.push(this.Parse(l));i(a)}else{const a=this.Parse(n);e&&(a.name=e),i(a)}}else s("Unable to load the animation")}),r.open("GET",t),r.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new Hs;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),a=[];for(const l of n.animations){const h=this.Parse(l);h.snippetId=e,a.push(h)}t(a)}else{const n=JSON.parse(r.animation),a=this.Parse(n);a.snippetId=e,t(a)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}Ee._UniqueIdGenerator=0;Ee.AllowMatricesInterpolation=!1;Ee.AllowMatrixDecomposeForInterpolation=!0;Ee.SnippetUrl="https://snippet.babylonjs.com";Ee.ANIMATIONTYPE_FLOAT=0;Ee.ANIMATIONTYPE_VECTOR3=1;Ee.ANIMATIONTYPE_QUATERNION=2;Ee.ANIMATIONTYPE_MATRIX=3;Ee.ANIMATIONTYPE_COLOR3=4;Ee.ANIMATIONTYPE_COLOR4=7;Ee.ANIMATIONTYPE_VECTOR2=5;Ee.ANIMATIONTYPE_SIZE=6;Ee.ANIMATIONLOOPMODE_RELATIVE=0;Ee.ANIMATIONLOOPMODE_CYCLE=1;Ee.ANIMATIONLOOPMODE_CONSTANT=2;Ee.ANIMATIONLOOPMODE_YOYO=4;Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;Ee.CreateFromSnippetAsync=Ee.ParseFromSnippetAsync;j("BABYLON.Animation",Ee);Mi._AnimationRangeFactory=(o,e,t)=>new qc(o,e,t);class rw extends Qi{constructor(e,t,i,s,r=1e3,n,a,l){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new he,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=a,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=Ee.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Te)i=Ee.ANIMATIONTYPE_COLOR3;else if(this.value instanceof T)i=Ee.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof k)i=Ee.ANIMATIONTYPE_MATRIX;else if(this.value instanceof Se)i=Ee.ANIMATIONTYPE_QUATERNION;else{G.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const s=new Ee("InterpolateValueAction",this._property,100*(1e3/this.duration),i,Ee.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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)},{name:"duration",value:Qi._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Qi._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}j("BABYLON.InterpolateValueAction",rw);class nw{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===Ee.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=k.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 a of this._target)this._preparePath(a,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-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let r=0;rthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(a.framePerSecond*r)/1e3+this._absoluteFrameOffset,f=0;if(s&&this._animationState.loopMode===Ee.ANIMATIONLOOPMODE_YOYO){const v=(d-t)/c;d=Math.abs(Math.sin(v*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&d>=c)h=!1,f=a._getKeyValue(this._maxValue);else if(!s&&t>=i&&d<=c)h=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ee.ANIMATIONLOOPMODE_CYCLE){const v=i.toString()+t.toString();if(!this._offsetsCache[v]){this._animationState.repeatCount=0,this._animationState.loopMode=Ee.ANIMATIONLOOPMODE_CYCLE;const E=a._interpolate(t,this._animationState),C=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case Ee.ANIMATIONTYPE_FLOAT:this._offsetsCache[v]=C-E;break;case Ee.ANIMATIONTYPE_QUATERNION:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_VECTOR3:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_VECTOR2:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_SIZE:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_COLOR3:this._offsetsCache[v]=C.subtract(E);break}this._highLimitsCache[v]=C}f=this._highLimitsCache[v],u=this._offsetsCache[v]}if(u===void 0)switch(a.dataType){case Ee.ANIMATIONTYPE_FLOAT:u=0;break;case Ee.ANIMATIONTYPE_QUATERNION:u=ZC;break;case Ee.ANIMATIONTYPE_VECTOR3:u=JC;break;case Ee.ANIMATIONTYPE_VECTOR2:u=eb;break;case Ee.ANIMATIONTYPE_SIZE:u=tb;break;case Ee.ANIMATIONTYPE_COLOR3:u=ib;break;case Ee.ANIMATIONTYPE_COLOR4:u=sb;break}let p;if(this._host&&this._host.syncRoot){const v=this._host.syncRoot,E=(v.masterFrame-v.fromFrame)/(v.toFrame-v.fromFrame);p=t+c*E}else d>0&&t>i||d<0&&t0&&this.currentFrame>p||r<0&&this.currentFrame0?0:a.getKeys().length-1}this._currentFrame=p,this._animationState.repeatCount=c===0?0:d/c>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const g=a._interpolate(p,this._animationState);if(this.setValue(g,n),_.length){for(let v=0;v<_.length;v++)if(c>0&&p>=_[v].frame&&_[v].frame>=t||c<0&&p<=_[v].frame&&_[v].frame<=t){const E=_[v];E.isDone||(E.onlyOnce&&(_.splice(v,1),v--),E.isDone=!0,E.action(p))}}return h||(this._stopped=!0),h}}function gr(){return typeof window<"u"}function ju(){return typeof navigator<"u"}function Zu(){return typeof document<"u"}function nx(o){let e="",t=o.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}class ar{static get Now(){return gr()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Ju{}Ju.FilesToLoad={};class aw{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 jc extends Error{}jc._setPrototypeOf=Object.setPrototypeOf||((o,e)=>(o.__proto__=e,o));const sh={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Ko extends jc{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",jc._setPrototypeOf(this,Ko.prototype)}}const rb=o=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,a,l,h,c=0;const u=ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):new Uint8Array(o);for(;c>2,a=(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(a)+e.charAt(l)+e.charAt(h);return t},nb=o=>atob(o),ow=o=>{const e=nb(o),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s{c+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),c}}class cw{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n{c=c.trim(),c!==""&&(i.push(c),c="")},n=u=>{sMs._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":Ms._Stack[s--];let h=0,c="";for(;h1){for(r();s!==-1&&Ms._OperatorPriority[a()]>=Ms._OperatorPriority[d];)i.push(l());n(d),h++}else c+=u;h++}for(r();s!==-1;)a()==="("?l():i.push(l());return Ms._InfixToPostfixCache.size>=Ms.InfixToPostfixCacheLimitSize&&Ms.ClearCache(),Ms._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Ms._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r;break}return i}}var is;(function(o){o[o.GLSL=0]="GLSL",o[o.WGSL=1]="WGSL"})(is||(is={}));const _w=/defined\s*?\((.+?)\)/g,av=/defined\s*?\[(.+?)\]/g,mw=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,gw=/__decl__/,GS=/light\{X\}.(\w*)/g,zS=/\{X\}/g,n_=[];class Ia{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===void 0)&&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 a=this._ProcessShaderConversion(n,t,s);i(a,n)})}static PreProcess(e,t,i,s){var r;!((r=t.processor)===null||r===void 0)&&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 a=this._ApplyPreProcessing(n,t,s);i(a,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 i;if(!((i=t.processor)===null||i===void 0)&&i.noPrecision)return e;const s=t.shouldUseHighPrecisionShader;return e.indexOf("precision highp float")===-1?s?e=`precision highp float; +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return k.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}invertToRef(e){if(this._isIdentity===!0)return k.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],f=t[10],p=t[11],_=t[12],g=t[13],v=t[14],E=t[15],C=f*E-v*p,S=d*E-g*p,b=d*v-g*f,R=u*E-_*p,I=u*v-f*_,N=u*g-_*d,O=+(l*C-h*S+c*b),L=-(a*C-h*R+c*I),B=+(a*S-l*R+c*N),V=-(a*b-l*I+h*N),Z=i*O+s*L+r*B+n*V;if(Z===0)return e.copyFrom(this),e;const ue=1/Z,oe=h*E-v*c,me=l*E-g*c,le=l*v-g*h,ae=a*E-_*c,ce=a*v-_*h,ie=a*g-_*l,w=h*p-f*c,H=l*p-d*c,X=l*f-d*h,te=a*p-u*c,Q=a*f-u*h,_e=a*d-u*l,q=-(s*C-r*S+n*b),de=+(i*C-r*R+n*I),ge=-(i*S-s*R+n*N),ve=+(i*b-s*I+r*N),be=+(s*oe-r*me+n*le),Le=-(i*oe-r*ae+n*ce),Ye=+(i*me-s*ae+n*ie),He=-(i*le-s*ce+r*ie),Be=-(s*w-r*H+n*X),Ge=+(i*w-r*te+n*Q),Bt=-(i*H-s*te+n*_e),Mt=+(i*X-s*Q+r*_e);return k.FromValuesToRef(O*ue,q*ue,be*ue,Be*ue,L*ue,de*ue,Le*ue,Ge*ue,B*ue,ge*ue,Ye*ue,Bt*ue,V*ue,ve*ue,He*ue,Mt*ue,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 T(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 k.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}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],a=s[1],l=s[2],h=s[3],c=s[4],u=s[5],d=s[6],f=s[7],p=s[8],_=s[9],g=s[10],v=s[11],E=s[12],C=s[13],S=s[14],b=s[15],R=r[0],I=r[1],N=r[2],O=r[3],L=r[4],B=r[5],V=r[6],Z=r[7],ue=r[8],oe=r[9],me=r[10],le=r[11],ae=r[12],ce=r[13],ie=r[14],w=r[15];return t[i]=n*R+a*L+l*ue+h*ae,t[i+1]=n*I+a*B+l*oe+h*ce,t[i+2]=n*N+a*V+l*me+h*ie,t[i+3]=n*O+a*Z+l*le+h*w,t[i+4]=c*R+u*L+d*ue+f*ae,t[i+5]=c*I+u*B+d*oe+f*ce,t[i+6]=c*N+u*V+d*me+f*ie,t[i+7]=c*O+u*Z+d*le+f*w,t[i+8]=p*R+_*L+g*ue+v*ae,t[i+9]=p*I+_*B+g*oe+v*ce,t[i+10]=p*N+_*V+g*me+v*ie,t[i+11]=p*O+_*Z+g*le+v*w,t[i+12]=E*R+C*L+S*ue+b*ae,t[i+13]=E*I+C*B+S*oe+b*ce,t[i+14]=E*N+C*V+S*me+b*ie,t[i+15]=E*O+C*Z+S*le+b*w,this}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,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]}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=kn(this._m[0]);for(let t=1;t<16;t++)e=e*397^kn(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Se,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||ot.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 a=(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*=a,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 a=1/e._x,l=1/e._y,h=1/e._z;k.FromValuesToRef(n[0]*a,n[1]*a,n[2]*a,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,ot.Matrix[0]),Se.FromRotationMatrixToRef(ot.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Dt(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 k.TransposeToRef(this,e),e}transposeToRef(e){return k.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}toNormalMatrix(e){const t=ot.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return k.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=ot.Vector3[0];if(!this.decompose(t))return k.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return k.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 k;return k.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 k._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v){const E=v._m;E[0]=e,E[1]=t,E[2]=i,E[3]=s,E[4]=r,E[5]=n,E[6]=a,E[7]=l,E[8]=h,E[9]=c,E[10]=u,E[11]=d,E[12]=f,E[13]=p,E[14]=_,E[15]=g,v.markAsUpdated()}static FromValues(e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g){const v=new k,E=v._m;return E[0]=e,E[1]=t,E[2]=i,E[3]=s,E[4]=r,E[5]=n,E[6]=a,E[7]=l,E[8]=h,E[9]=c,E[10]=u,E[11]=d,E[12]=f,E[13]=p,E[14]=_,E[15]=g,v.markAsUpdated(),v}static Compose(e,t,i){const s=new k;return k.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,a=t._y,l=t._z,h=t._w,c=n+n,u=a+a,d=l+l,f=n*c,p=n*u,_=n*d,g=a*u,v=a*d,E=l*d,C=h*c,S=h*u,b=h*d,R=e._x,I=e._y,N=e._z;return r[0]=(1-(g+E))*R,r[1]=(p+b)*R,r[2]=(_-S)*R,r[3]=0,r[4]=(p-b)*I,r[5]=(1-(f+E))*I,r[6]=(v+C)*I,r[7]=0,r[8]=(_+S)*N,r[9]=(v-C)*N,r[10]=(1-(f+g))*N,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=k.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 k.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=k.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 k;return k.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 k.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 k;return k.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return k.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 k;return k.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return k.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 k;return k.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 a=i._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*s,a[2]=e._x*e._z*n+e._y*s,a[3]=0,a[4]=e._y*e._x*n+e._z*s,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*s,a[7]=0,a[8]=e._z*e._x*n-e._y*s,a[9]=e._z*e._y*n+e._x*s,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=T.Dot(t,e),n=i._m;if(r<-1+$t)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 a=T.Cross(t,e),l=1/(1+r);n[0]=a._x*a._x*l+r,n[1]=a._y*a._x*l-a._z,n[2]=a._z*a._x*l+a._y,n[3]=0,n[4]=a._x*a._y*l+a._z,n[5]=a._y*a._y*l+r,n[6]=a._z*a._y*l-a._x,n[7]=0,n[8]=a._x*a._z*l-a._y,n[9]=a._y*a._z*l+a._x,n[10]=a._z*a._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 k;return k.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return Se.RotationYawPitchRollToRef(e,t,i,ot.Quaternion[0]),ot.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new k;return k.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return k.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 k;return k.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return k.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 k.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,a=t.m;for(let l=0;l<16;l++)r[l]=n[l]*(1-i)+a[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return k.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Quaternion[0],a=ot.Vector3[1];e.decompose(r,n,a);const l=ot.Vector3[2],h=ot.Quaternion[1],c=ot.Vector3[3];t.decompose(l,h,c);const u=ot.Vector3[4];T.LerpToRef(r,l,i,u);const d=ot.Quaternion[2];Se.SlerpToRef(n,h,i,d);const f=ot.Vector3[5];return T.LerpToRef(a,c,i,f),k.ComposeToRef(u,d,f,s),s}static LookAtLH(e,t,i){const s=new k;return k.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Vector3[1],a=ot.Vector3[2];t.subtractToRef(e,a),a.normalize(),T.CrossToRef(i,a,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(a,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(a,e);return k.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,c,u,1,s),s}static LookAtRH(e,t,i){const s=new k;return k.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=ot.Vector3[0],n=ot.Vector3[1],a=ot.Vector3[2];e.subtractToRef(t,a),a.normalize(),T.CrossToRef(i,a,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(a,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(a,e);return k.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new k;return k.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=ot.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=ot.Vector3[1];return T.CrossToRef(t,s,r),k.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 k;return k.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=ot.Vector3[2];return T.CrossToRef(t,e,s),k.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 k;return k.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const a=i,l=s,h=2/e,c=2/t,u=2/(l-a),d=-(l+a)/(l-a);return k.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,d,1,r),n&&r.multiplyToRef(Oh,r),r._updateIdentityStatus(h===1&&c===1&&u===1&&d===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,a){const l=new k;return k.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,a),l}static OrthoOffCenterLHToRef(e,t,i,s,r,n,a,l){const h=r,c=n,u=2/(t-e),d=2/(s-i),f=2/(c-h),p=-(c+h)/(c-h),_=(e+t)/(e-t),g=(s+i)/(i-s);return k.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,f,0,_,g,p,1,a),l&&a.multiplyToRef(Oh,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,a,l,h,c,u){const d=-a*Math.cos(l),f=-a*Math.sin(l);return k.TranslationToRef(0,0,-h,ot.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,ot.Matrix[0]),ot.Matrix[1].multiplyToRef(ot.Matrix[0],ot.Matrix[0]),k.TranslationToRef(0,0,h,ot.Matrix[1]),ot.Matrix[0].multiplyToRef(ot.Matrix[1],ot.Matrix[0]),k.OrthoOffCenterLHToRef(e,t,i,s,r,n,c,u),ot.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,r,n,a){const l=new k;return k.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,a),l}static OrthoOffCenterRHToRef(e,t,i,s,r,n,a,l){return k.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,l),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,a,l,h,c,u){const d=a*Math.cos(l),f=a*Math.sin(l);return k.TranslationToRef(0,0,h,ot.Matrix[1]),k.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,ot.Matrix[0]),ot.Matrix[1].multiplyToRef(ot.Matrix[0],ot.Matrix[0]),k.TranslationToRef(0,0,-h,ot.Matrix[1]),ot.Matrix[0].multiplyToRef(ot.Matrix[1],ot.Matrix[0]),k.OrthoOffCenterRHToRef(e,t,i,s,r,n,c,u),ot.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,r,n=0){const a=new k,l=i,h=s,c=2*l/e,u=2*l/t,d=(h+l)/(h-l),f=-2*h*l/(h-l),p=Math.tan(n);return k.FromValuesToRef(c,0,0,0,0,u,0,p,0,0,d,1,0,0,f,0,a),r&&a.multiplyToRef(Oh,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,r,n=0,a=!1){const l=new k;return k.PerspectiveFovLHToRef(e,t,i,s,l,!0,r,n,a),l}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,a,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,p=n?d:d*t,_=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,v=Math.tan(l);return k.FromValuesToRef(f,0,0,0,0,p,0,v,0,0,_,1,0,0,g,0,r),a&&r.multiplyToRef(Oh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,a,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return k.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(Oh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,a=!1){const l=new k;return k.PerspectiveFovRHToRef(e,t,i,s,l,!0,r,n,a),l}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,a,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,p=n?d:d*t,_=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,v=Math.tan(l);return k.FromValuesToRef(f,0,0,0,0,p,0,v,0,0,_,-1,0,0,g,0,r),a&&r.multiplyToRef(Oh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,a,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return k.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(Oh,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const a=e.width,l=e.height,h=e.x,c=e.y,u=k.FromValues(a/2,0,0,0,0,-l/2,0,0,0,0,n-r,0,h+a/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 Dr.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 Dr.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return k.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[12],l=i[1],h=i[5],c=i[9],u=i[13],d=i[2],f=i[6],p=i[10],_=i[14],g=i[3],v=i[7],E=i[11],C=i[15],S=t._m;return S[0]=s,S[1]=r,S[2]=n,S[3]=a,S[4]=l,S[5]=h,S[6]=c,S[7]=u,S[8]=d,S[9]=f,S[10]=p,S[11]=_,S[12]=g,S[13]=v,S[14]=E,S[15]=C,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new k;return k.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,a=-2*s,l=-2*r;return k.FromValuesToRef(n*i+1,a*i,l*i,0,n*s,a*s+1,l*s,0,n*r,a*r,l*r+1,0,n*e.d,a*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return k.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,a=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+a),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(n-a),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}}k._UpdateFlagSeed=0;k._IdentityReadOnly=k.Identity();class ot{}ot.Vector3=js.BuildTuple(11,T.Zero);ot.Matrix=js.BuildTuple(2,k.Identity);ot.Quaternion=js.BuildTuple(3,Se.Zero);class K{}K.Vector2=js.BuildTuple(3,Re.Zero);K.Vector3=js.BuildTuple(13,T.Zero);K.Vector4=js.BuildTuple(3,Dt.Zero);K.Quaternion=js.BuildTuple(2,Se.Zero);K.Matrix=js.BuildTuple(8,k.Identity);j("BABYLON.Vector2",Re);j("BABYLON.Vector3",T);j("BABYLON.Vector4",Dt);j("BABYLON.Matrix",k);const Oh=k.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);function Vc(o){return Math.pow(o,__)}function Uc(o){return o<=.04045?.0773993808*o:Math.pow(.947867299*(o+.055),2.4)}function kc(o){return Math.pow(o,Qu)}function Gc(o){return o<=.0031308?12.92*o:1.055*Math.pow(o,.41666)-.055}class Te{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 Te.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ze(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 Te(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new Te(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=ye.Clamp(this.r,e,t),i.g=ye.Clamp(this.g,e,t),i.b=ye.Clamp(this.b,e,t),this}add(e){return new Te(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new Te(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this}clone(){return new Te(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+ye.ToHex(e)+ye.ToHex(t)+ye.ToHex(i)}toHSV(){const e=new Te;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 a=0,l=0;const h=r,c=r-n;r!==0&&(l=c/r),r!=n&&(r==t?(a=(i-s)/c,i=0&&n<=1?(l=r,h=a):n>=1&&n<=2?(l=a,h=r):n>=2&&n<=3?(h=r,c=a):n>=3&&n<=4?(h=a,c=r):n>=4&&n<=5?(l=a,c=r):n>=5&&n<=6&&(l=r,c=a);const u=i-r;s.set(l+u,h+u,c+u)}static FromHSV(e,t,i){const s=new Te(0,0,0);return Te.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Te(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 Te.FromInts(t,i,s)}static FromArray(e,t=0){return new Te(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 Te(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Te(0,0,0);return Te.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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e.b*l+i.b*h+t.b*c+s.b*u;return new Te(d,f,p)}static Hermite1stDerivative(e,t,i,s,r){const n=Te.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b}static Red(){return new Te(1,0,0)}static Green(){return new Te(0,1,0)}static Blue(){return new Te(0,0,1)}static Black(){return new Te(0,0,0)}static get BlackReadOnly(){return Te._BlackReadOnly}static White(){return new Te(1,1,1)}static Purple(){return new Te(.5,0,.5)}static Magenta(){return new Te(1,0,1)}static Yellow(){return new Te(1,1,0)}static Gray(){return new Te(.5,.5,.5)}static Teal(){return new Te(0,1,1)}static Random(){return new Te(Math.random(),Math.random(),Math.random())}}Te._BlackReadOnly=Te.Black();class Ze{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return Ze.FromArrayToRef(e,t,this),this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ze(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Ze(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this}scale(e){return new Ze(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=ye.Clamp(this.r,e,t),i.g=ye.Clamp(this.g,e,t),i.b=ye.Clamp(this.b,e,t),i.a=ye.Clamp(this.a,e,t),this}multiply(e){return new Ze(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=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 Ze(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,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)}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"#"+ye.ToHex(t)+ye.ToHex(i)+ye.ToHex(s);const r=Math.round(this.a*255);return"#"+ye.ToHex(t)+ye.ToHex(i)+ye.ToHex(s)+ye.ToHex(r)}toLinearSpace(e=!1){const t=new Ze;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Uc(this.r),e.g=Uc(this.g),e.b=Uc(this.b)):(e.r=Vc(this.r),e.g=Vc(this.g),e.b=Vc(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ze;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Gc(this.r),e.g=Gc(this.g),e.b=Gc(this.b)):(e.r=kc(this.r),e.g=kc(this.g),e.b=kc(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Ze(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 Ze.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Ze(0,0,0,0);return Ze.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,a=r*n,l=2*a-3*n+1,h=-2*a+3*n,c=a-2*n+r,u=a-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,p=e.b*l+i.b*h+t.b*c+s.b*u,_=e.a*l+i.a*h+t.a*c+s.a*u;return new Ze(d,f,p,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ze;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=(a-r)*6*e.r+(3*a-4*r+1)*t.r+(-a+r)*6*i.r+(3*a-2*r)*s.r,n.g=(a-r)*6*e.g+(3*a-4*r+1)*t.g+(-a+r)*6*i.g+(3*a-2*r)*s.g,n.b=(a-r)*6*e.b+(3*a-4*r+1)*t.b+(-a+r)*6*i.b+(3*a-2*r)*s.b,n.a=(a-r)*6*e.a+(3*a-4*r+1)*t.a+(-a+r)*6*i.a+(3*a-2*r)*s.a}static FromColor3(e,t=1){return new Ze(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ze(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 Ze(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew Ze(0,0,0,0));j("BABYLON.Color3",Te);j("BABYLON.Color4",Ze);class Qi{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new he,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){}_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}}Qi._SerializeValueAsString=o=>typeof o=="number"?o.toString():typeof o=="boolean"?o?"true":"false":o instanceof Re?o.x+", "+o.y:o instanceof T?o.x+", "+o.y+", "+o.z:o instanceof Te?o.r+", "+o.g+", "+o.b:o instanceof Ze?o.r+", "+o.g+", "+o.b+", "+o.a:o;Qi._GetTargetProperty=o=>({name:"target",targetType:o._isMesh?"MeshProperties":o._isLight?"LightProperties":o._isCamera?"CameraProperties":o._isMaterial?"MaterialProperties":"SceneProperties",value:o._isScene?"Scene":o.name});j("BABYLON.Action",Qi);class _r{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 _r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new _r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new _r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new _r(e,t.x,t.y,null,i,s)}}class Cd{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 pr extends Cd{static get IsEqual(){return pr._IsEqual}static get IsDifferent(){return pr._IsDifferent}static get IsGreater(){return pr._IsGreater}static get IsLesser(){return pr._IsLesser}constructor(e,t,i,s,r=pr.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 pr.IsGreater:return this._effectiveTarget[this._property]>this.value;case pr.IsLesser:return this._effectiveTarget[this._property]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&&!G._CheckLimit(s,i))return;const r=G._FormatMessage(s),n=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...a);const l=`
${r}

`;G._AddLogEntry(l),G._GenerateLimitMessage(s,e)}static get LogCache(){return G._LogCache}static ClearLogCache(){G._LogCache="",G._LogLimitOutputs={},G.errorsCount=0}static set LogLevels(e){G.Log=G._LogDisabled,G.Warn=G._LogDisabled,G.Error=G._LogDisabled,[G.MessageLogLevel,G.WarningLogLevel,G.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];G[i.name]=G._LogEnabled.bind(G,t)}})}}G.NoneLogLevel=0;G.MessageLogLevel=1;G.WarningLogLevel=2;G.ErrorLogLevel=4;G.AllLogLevel=7;G.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";G._LogCache="";G._LogLimitOutputs={};G._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];G.errorsCount=0;G.Log=G._LogEnabled.bind(G,G.MessageLogLevel);G.Warn=G._LogEnabled.bind(G,G.WarningLogLevel);G.Error=G._LogEnabled.bind(G,G.ErrorLogLevel);class WN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class HN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class XN extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)}]},e)}}class YN extends Qi{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"&&G.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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)}]},e)}}class $N extends Qi{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:[Qi._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Qi._SerializeValueAsString(this.loop)||!1}]},e)}}class KN extends Qi{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:[Qi._GetTargetProperty(this._target)]},e)}}class QC extends Qi{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class qN extends Qi{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;e!o||o.getClassName&&o.getClassName()==="Mesh"?null:o.getClassName&&(o.getClassName()==="SubMesh"||o.getClassName()==="PhysicsBody")?o.clone(e):o.clone?o.clone():Array.isArray(o)?o.slice():t&&typeof o=="object"?Object.assign({},o):null;function QN(o){const e=[];do Object.getOwnPropertyNames(o).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(o=Object.getPrototypeOf(o));return e}class Ur{static DeepCopy(e,t,i,s,r=!1){const n=QN(e);for(const a of n){if(a[0]==="_"&&(!s||s.indexOf(a)===-1)||a.endsWith("Observable")||i&&i.indexOf(a)!==-1)continue;const l=e[a],h=typeof l;if(h!=="function")try{if(h==="object")if(l instanceof Uint8Array)t[a]=Uint8Array.from(l);else if(l instanceof Array){if(t[a]=[],l.length>0)if(typeof l[0]=="object")for(let c=0;c-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-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Ii.OnPickTrigger&&t.trigger<=Ii.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Ii.OnPickTrigger&&t.trigger<=Ii.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Ii.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(G.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Ii.Triggers[e.trigger]?Ii.Triggers[e.trigger]++:Ii.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),Ii.Triggers[e.trigger]-=1,Ii.Triggers[e.trigger]===0&&delete Ii.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const c=Ds("BABYLON."+l);return c&&new c(...h)},n=(l,h,c,u)=>{if(u===null){const _=parseFloat(h);return h==="true"||h==="false"?h==="true":isNaN(_)?h:_}const d=u.split("."),f=h.split(",");for(let _=0;_{if(l.detached)return;const f=[];let p=null,_=null;const g=l.combine&&l.combine.length>0;if(l.type===2?f.push(s):f.push(h),g){const E=[];for(let C=0;C0){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:Ii[c.name],parameter:d}}else h=Ii[c.name];for(let u=0;u(i=i.slice(1,i.length-1),wh._HandleParenthesisContent(i,t))):e=wh._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:wh.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=wh._SimplifyNegation(s[r].trim());const a=n.split("&&");if(a.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class ui{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ui.HasTags(e),e.addTags=t=>ui.AddTagsTo(e,t),e.removeTags=t=>ui.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ui.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){ui._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ui.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ui.HasTags(e))return;const i=t.split(" ");for(const s in i)ui._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?ui.HasTags(e):wh.Eval(t,i=>ui.HasTags(e)&&e._tags[i])}}const GS={};function xt(o,e=!1){if(!(e&&GS[o]))return GS[o]=!0,`${o} needs to be imported before as it contains a side-effect required by your code.`}const m_={},s_={},zS=function(o,e,t,i={}){const s=o();ui&&ui.HasTags(e)&&ui.AddTagsTo(s,ui.GetTags(e,!0));const r=Pv(s),n={};for(const a in r){const l=r[a],h=e[a],c=l.type;if(h!=null&&(a!=="uniqueId"||Xe.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[a]=h;break;case 1:i.cloneTexturesOnlyOnce&&n[h.uniqueId]?s[a]=n[h.uniqueId]:(s[a]=t||h.isRenderTarget?h:h.clone(),n[h.uniqueId]=s[a]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[a]=t?h:h.clone();break}}return s};function ew(o){const e=o.getClassName();return m_[e]||(m_[e]={}),m_[e]}function Pv(o){const e=o.getClassName();if(s_[e])return s_[e];s_[e]={};const t=s_[e];let i=o,s=e;for(;s;){const r=m_[s];for(const l in r)t[l]=r[l];let n,a=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){a=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(a)break;s=n.getClassName(),i=n}return t}function Fa(o,e){return(t,i)=>{const s=ew(t);s[i]||(s[i]={type:o,sourceName:e})}}function tw(o,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[o].apply(this))},enumerable:!0,configurable:!0})}}function Ce(o,e=null){return tw(o,e)}function D(o){return Fa(0,o)}function Jt(o){return Fa(1,o)}function ds(o){return Fa(2,o)}function jf(o){return Fa(3,o)}function rx(o){return Fa(4,o)}function kr(o){return Fa(5,o)}function Qf(o){return Fa(6,o)}function iw(o){return Fa(7,o)}function nx(o){return Fa(8,o)}function JC(o){return Fa(9,o)}function sw(o){return Fa(10,o)}function ax(o){return Fa(12,o)}function rw(o){return Fa(11,o)}class Xe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw xt("ImageProcessingConfiguration")};Xe._FresnelParametersParser=o=>{throw xt("FresnelParameters")};Xe._ColorCurvesParser=o=>{throw xt("ColorCurves")};Xe._TextureParser=(o,e,t)=>{throw xt("Texture")};function ch(o,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const a=_native[e];i?n=(...l)=>i(...l)?a(...l):s(...l):n=a}return o[e]=n,n(...r)}}ch.filter=function(o){return(e,t,i)=>ch(e,t,i,o)};var Mv;(function(o){o[o.NONE=0]="NONE",o[o.STEP=1]="STEP"})(Mv||(Mv={}));class qc{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new qc(this.name,this.from,this.to)}}function A(o,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(o,e,t,i);else for(var a=o.length-1;a>=0;a--)(n=o[a])&&(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}class nw{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new he,this._onClonedObservable=new he}}let Mi=class Dv{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 nw,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new he,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=k.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new he,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||ht.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(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew Dv(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n{throw xt("AnimationRange")};Mi._NodeConstructors={};A([D()],Mi.prototype,"name",void 0);A([D()],Mi.prototype,"id",void 0);A([D()],Mi.prototype,"uniqueId",void 0);A([D()],Mi.prototype,"state",void 0);A([D()],Mi.prototype,"metadata",void 0);class ya{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 ya(this.width*e,this.height*t)}clone(){return new ya(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 ya(0,0)}add(e){return new ya(this.width+e.width,this.height+e.height)}subtract(e){return new ya(this.width-e.width,this.height-e.height)}scale(e){return new ya(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 ya(s,r)}}function aw(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class Hs{constructor(){this._xhr=aw(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Hs.CustomRequestHeaders).length>0||Hs.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Hs.CustomRequestHeaders){const t=Hs.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Hs.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){Hs.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of Hs.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}return 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)}}Hs.CustomRequestHeaders={};Hs.CustomRequestModifiers=new Array;Hs.SkipRequestModificationForBabylonCDN=!0;const eb=Object.freeze(new Se(0,0,0,0)),tb=Object.freeze(T.Zero()),ib=Object.freeze(Re.Zero()),sb=Object.freeze(ya.Zero()),rb=Object.freeze(Te.Black()),nb=Object.freeze(new Ze(0,0,0,0)),_o={key:0,repeatCount:0,loopMode:2};class Ee{static _PrepareAnimation(e,t,i,s,r,n,a,l){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=Ee.ANIMATIONTYPE_FLOAT:r instanceof Se?h=Ee.ANIMATIONTYPE_QUATERNION:r instanceof T?h=Ee.ANIMATIONTYPE_VECTOR3:r instanceof Re?h=Ee.ANIMATIONTYPE_VECTOR2:r instanceof Te?h=Ee.ANIMATIONTYPE_COLOR3:r instanceof Ze?h=Ee.ANIMATIONTYPE_COLOR4:r instanceof ya&&(h=Ee.ANIMATIONTYPE_SIZE),h==null)return null;const c=new Ee(e,t,i,h,a),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 Ee(e+"Animation",e,i,t,Ee.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,a,l,h,c,u){const d=Ee._PrepareAnimation(e,i,s,r,n,a,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,a,l,h,c,u){const d=Ee._PrepareAnimation(e,s,r,n,a,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,a,l,h,c){const u=Ee._PrepareAnimation(e,i,s,r,n,a,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){var n,a;let l;typeof t=="object"?l=t:l={referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let h=e;if(l.cloneOriginalAnimation&&(h=e.clone(),h.name=l.clonedAnimationName||h.name),!h._keys.length)return h;const c=l.referenceFrame&&l.referenceFrame>=0?l.referenceFrame:0;let u=0;const d=h._keys[0];let f=h._keys.length-1;const p=h._keys[f],_={referenceValue:d.value,referencePosition:K.Vector3[0],referenceQuaternion:K.Quaternion[0],referenceScaling:K.Vector3[1],keyPosition:K.Vector3[2],keyQuaternion:K.Quaternion[1],keyScaling:K.Vector3[3]};let g=d.frame,v=p.frame;if(l.range){const S=h.getRange(l.range);S&&(g=S.from,v=S.to)}else g=(n=l.fromFrame)!==null&&n!==void 0?n:g,v=(a=l.toFrame)!==null&&a!==void 0?a:v;if(g!==d.frame&&(u=h.createKeyForFrame(g)),v!==p.frame&&(f=h.createKeyForFrame(v)),h._keys.length===1){const S=h._getKeyValue(h._keys[0]);_.referenceValue=S.clone?S.clone():S}else if(c<=d.frame){const S=h._getKeyValue(d.value);_.referenceValue=S.clone?S.clone():S}else if(c>=p.frame){const S=h._getKeyValue(p.value);_.referenceValue=S.clone?S.clone():S}else{_o.key=0;const S=h._interpolate(c,_o);_.referenceValue=S.clone?S.clone():S}h.dataType===Ee.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():h.dataType===Ee.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let E=Number.MAX_VALUE;const C=l.clipKeys?[]:null;for(let S=u;S<=f;S++){let b=h._keys[S];if(C&&(b={frame:b.frame,value:b.value.clone?b.value.clone():b.value,inTangent:b.inTangent,outTangent:b.outTangent,interpolation:b.interpolation,lockedTangent:b.lockedTangent},E===Number.MAX_VALUE&&(E=b.frame),b.frame-=E,C.push(b)),!(S&&h.dataType!==Ee.ANIMATIONTYPE_FLOAT&&b.value===d.value))switch(h.dataType){case Ee.ANIMATIONTYPE_MATRIX:b.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),k.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,b.value);break;case Ee.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(b.value,b.value);break;case Ee.ANIMATIONTYPE_VECTOR2:case Ee.ANIMATIONTYPE_VECTOR3:case Ee.ANIMATIONTYPE_COLOR3:case Ee.ANIMATIONTYPE_COLOR4:b.value.subtractToRef(_.referenceValue,b.value);break;case Ee.ANIMATIONTYPE_SIZE:b.value.width-=_.referenceValue.width,b.value.height-=_.referenceValue.height;break;default:b.value-=_.referenceValue}}return C&&h.setKeys(C,!0),h}static TransitionTo(e,t,i,s,r,n,a,l=null){if(a<=0)return i[e]=t,l&&l(),null;const h=r*(a/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?Ee.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ee._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const s in this._ranges)i&&(t+=", ",i=!1),t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;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;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,n=r.length;let a=t.key;for(;a>=0&&e=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>n-1)return i?void 0:this._getKeyValue(r[n-1].value);const l=r[a],h=r[a+1];if(i&&(e===l.frame||e===h.frame))return;const c=this._getKeyValue(l.value),u=this._getKeyValue(h.value);if(l.interpolation===Mv.STEP)return h.frame>e?c:u;const d=l.outTangent!==void 0&&h.inTangent!==void 0,f=h.frame-l.frame;let p=(e-l.frame)/f;const _=l.easingFunction||this.getEasingFunction();switch(_!==null&&(p=_.ease(p)),this.dataType){case Ee.ANIMATIONTYPE_FLOAT:{const g=d?this.floatInterpolateFunctionWithTangents(c,l.outTangent*f,u,h.inTangent*f,p):this.floatInterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((s=t.offsetValue)!==null&&s!==void 0?s:0)*t.repeatCount+g}break}case Ee.ANIMATIONTYPE_QUATERNION:{const g=d?this.quaternionInterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.quaternionInterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((t.offsetValue||eb).scale(t.repeatCount))}return g}case Ee.ANIMATIONTYPE_VECTOR3:{const g=d?this.vector3InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.vector3InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||tb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_VECTOR2:{const g=d?this.vector2InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.vector2InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||ib).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(c,u,p);case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(c,u,p).add((t.offsetValue||sb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_COLOR3:{const g=d?this.color3InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.color3InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||rb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_COLOR4:{const g=d?this.color4InterpolateFunctionWithTangents(c,l.outTangent.scale(f),u,h.inTangent.scale(f),p):this.color4InterpolateFunction(c,u,p);switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return g;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||nb).scale(t.repeatCount))}break}case Ee.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case Ee.ANIMATIONLOOPMODE_CYCLE:case Ee.ANIMATIONLOOPMODE_CONSTANT:case Ee.ANIMATIONLOOPMODE_YOYO:return Ee.AllowMatricesInterpolation?this.matrixInterpolateFunction(c,u,p,t.workValue):c;case Ee.ANIMATIONLOOPMODE_RELATIVE:case Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return c}break}}return 0}matrixInterpolateFunction(e,t,i,s){return Ee.AllowMatrixDecomposeForInterpolation?s?(k.DecomposeLerpToRef(e,t,i,s),s):k.DecomposeLerp(e,t,i):s?(k.LerpToRef(e,t,i,s),s):k.Lerp(e,t,i)}clone(){const e=new Ee(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){_o.key=0;const t=this._interpolate(e,_o,!0);if(!t)return this._keys[_o.key].frame===e?_o.key:_o.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(_o.key+1,0,i),_o.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(l=a.values[1]),a.values.length>=3&&(h=a.values[2]),a.values.length>=4&&(c=a.values[3]);break;case Ee.ANIMATIONTYPE_QUATERNION:if(r=Se.FromArray(a.values),a.values.length>=8){const d=Se.FromArray(a.values.slice(4,8));d.equals(Se.Zero())||(l=d)}if(a.values.length>=12){const d=Se.FromArray(a.values.slice(8,12));d.equals(Se.Zero())||(h=d)}a.values.length>=13&&(c=a.values[12]);break;case Ee.ANIMATIONTYPE_MATRIX:r=k.FromArray(a.values),a.values.length>=17&&(c=a.values[16]);break;case Ee.ANIMATIONTYPE_COLOR3:r=Te.FromArray(a.values),a.values[3]&&(l=Te.FromArray(a.values[3])),a.values[4]&&(h=Te.FromArray(a.values[4])),a.values[5]&&(c=a.values[5]);break;case Ee.ANIMATIONTYPE_COLOR4:r=Ze.FromArray(a.values),a.values[4]&&(l=Ze.FromArray(a.values[4])),a.values[5]&&(h=Ze.FromArray(a.values[5])),a.values[6]&&(c=Ze.FromArray(a.values[6]));break;case Ee.ANIMATIONTYPE_VECTOR3:default:r=T.FromArray(a.values),a.values[3]&&(l=T.FromArray(a.values[3])),a.values[4]&&(h=T.FromArray(a.values[4])),a.values[5]&&(c=a.values[5]);break}const u={};u.frame=a.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{const r=new Hs;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 a=[];for(const l of n)a.push(this.Parse(l));i(a)}else{const a=this.Parse(n);e&&(a.name=e),i(a)}}else s("Unable to load the animation")}),r.open("GET",t),r.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new Hs;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),a=[];for(const l of n.animations){const h=this.Parse(l);h.snippetId=e,a.push(h)}t(a)}else{const n=JSON.parse(r.animation),a=this.Parse(n);a.snippetId=e,t(a)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}Ee._UniqueIdGenerator=0;Ee.AllowMatricesInterpolation=!1;Ee.AllowMatrixDecomposeForInterpolation=!0;Ee.SnippetUrl="https://snippet.babylonjs.com";Ee.ANIMATIONTYPE_FLOAT=0;Ee.ANIMATIONTYPE_VECTOR3=1;Ee.ANIMATIONTYPE_QUATERNION=2;Ee.ANIMATIONTYPE_MATRIX=3;Ee.ANIMATIONTYPE_COLOR3=4;Ee.ANIMATIONTYPE_COLOR4=7;Ee.ANIMATIONTYPE_VECTOR2=5;Ee.ANIMATIONTYPE_SIZE=6;Ee.ANIMATIONLOOPMODE_RELATIVE=0;Ee.ANIMATIONLOOPMODE_CYCLE=1;Ee.ANIMATIONLOOPMODE_CONSTANT=2;Ee.ANIMATIONLOOPMODE_YOYO=4;Ee.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;Ee.CreateFromSnippetAsync=Ee.ParseFromSnippetAsync;j("BABYLON.Animation",Ee);Mi._AnimationRangeFactory=(o,e,t)=>new qc(o,e,t);class ow extends Qi{constructor(e,t,i,s,r=1e3,n,a,l){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new he,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=a,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=Ee.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Te)i=Ee.ANIMATIONTYPE_COLOR3;else if(this.value instanceof T)i=Ee.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof k)i=Ee.ANIMATIONTYPE_MATRIX;else if(this.value instanceof Se)i=Ee.ANIMATIONTYPE_QUATERNION;else{G.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const s=new Ee("InterpolateValueAction",this._property,100*(1e3/this.duration),i,Ee.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:[Qi._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Qi._SerializeValueAsString(this.value)},{name:"duration",value:Qi._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Qi._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}j("BABYLON.InterpolateValueAction",ow);class lw{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===Ee.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=k.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 a of this._target)this._preparePath(a,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-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let r=0;rthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(a.framePerSecond*r)/1e3+this._absoluteFrameOffset,f=0;if(s&&this._animationState.loopMode===Ee.ANIMATIONLOOPMODE_YOYO){const v=(d-t)/c;d=Math.abs(Math.sin(v*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&d>=c)h=!1,f=a._getKeyValue(this._maxValue);else if(!s&&t>=i&&d<=c)h=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ee.ANIMATIONLOOPMODE_CYCLE){const v=i.toString()+t.toString();if(!this._offsetsCache[v]){this._animationState.repeatCount=0,this._animationState.loopMode=Ee.ANIMATIONLOOPMODE_CYCLE;const E=a._interpolate(t,this._animationState),C=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case Ee.ANIMATIONTYPE_FLOAT:this._offsetsCache[v]=C-E;break;case Ee.ANIMATIONTYPE_QUATERNION:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_VECTOR3:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_VECTOR2:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_SIZE:this._offsetsCache[v]=C.subtract(E);break;case Ee.ANIMATIONTYPE_COLOR3:this._offsetsCache[v]=C.subtract(E);break}this._highLimitsCache[v]=C}f=this._highLimitsCache[v],u=this._offsetsCache[v]}if(u===void 0)switch(a.dataType){case Ee.ANIMATIONTYPE_FLOAT:u=0;break;case Ee.ANIMATIONTYPE_QUATERNION:u=eb;break;case Ee.ANIMATIONTYPE_VECTOR3:u=tb;break;case Ee.ANIMATIONTYPE_VECTOR2:u=ib;break;case Ee.ANIMATIONTYPE_SIZE:u=sb;break;case Ee.ANIMATIONTYPE_COLOR3:u=rb;break;case Ee.ANIMATIONTYPE_COLOR4:u=nb;break}let p;if(this._host&&this._host.syncRoot){const v=this._host.syncRoot,E=(v.masterFrame-v.fromFrame)/(v.toFrame-v.fromFrame);p=t+c*E}else d>0&&t>i||d<0&&t0&&this.currentFrame>p||r<0&&this.currentFrame0?0:a.getKeys().length-1}this._currentFrame=p,this._animationState.repeatCount=c===0?0:d/c>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const g=a._interpolate(p,this._animationState);if(this.setValue(g,n),_.length){for(let v=0;v<_.length;v++)if(c>0&&p>=_[v].frame&&_[v].frame>=t||c<0&&p<=_[v].frame&&_[v].frame<=t){const E=_[v];E.isDone||(E.onlyOnce&&(_.splice(v,1),v--),E.isDone=!0,E.action(p))}}return h||(this._stopped=!0),h}}function gr(){return typeof window<"u"}function ju(){return typeof navigator<"u"}function Zu(){return typeof document<"u"}function ox(o){let e="",t=o.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}class ar{static get Now(){return gr()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Ju{}Ju.FilesToLoad={};class hw{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 jc extends Error{}jc._setPrototypeOf=Object.setPrototypeOf||((o,e)=>(o.__proto__=e,o));const rh={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Ko extends jc{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",jc._setPrototypeOf(this,Ko.prototype)}}const ab=o=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,a,l,h,c=0;const u=ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):new Uint8Array(o);for(;c>2,a=(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(a)+e.charAt(l)+e.charAt(h);return t},ob=o=>atob(o),cw=o=>{const e=ob(o),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s{c+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),c}}class fw{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n{c=c.trim(),c!==""&&(i.push(c),c="")},n=u=>{sMs._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":Ms._Stack[s--];let h=0,c="";for(;h1){for(r();s!==-1&&Ms._OperatorPriority[a()]>=Ms._OperatorPriority[d];)i.push(l());n(d),h++}else c+=u;h++}for(r();s!==-1;)a()==="("?l():i.push(l());return Ms._InfixToPostfixCache.size>=Ms.InfixToPostfixCacheLimitSize&&Ms.ClearCache(),Ms._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Ms._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r;break}return i}}var is;(function(o){o[o.GLSL=0]="GLSL",o[o.WGSL=1]="WGSL"})(is||(is={}));const vw=/defined\s*?\((.+?)\)/g,av=/defined\s*?\[(.+?)\]/g,xw=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Tw=/__decl__/,WS=/light\{X\}.(\w*)/g,HS=/\{X\}/g,n_=[];class Ia{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===void 0)&&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 a=this._ProcessShaderConversion(n,t,s);i(a,n)})}static PreProcess(e,t,i,s){var r;!((r=t.processor)===null||r===void 0)&&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 a=this._ApplyPreProcessing(n,t,s);i(a,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 i;if(!((i=t.processor)===null||i===void 0)&&i.noPrecision)return e;const s=t.shouldUseHighPrecisionShader;return e.indexOf("precision highp float")===-1?s?e=`precision highp float; `+e:e=`precision mediump float; -`+e:s||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const i=/defined\((.+)\)/.exec(e);if(i&&i.length)return new r_(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 r_(e);const a=e.substring(0,n).trim(),l=e.substring(n+r.length).trim();return new pw(a,r,l)}static _BuildSubExpression(e){e=e.replace(_w,"defined[$1]");const t=Ms.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],a=i[i.length-2];i.length-=2;const l=r=="&&"?new fw:new dw;typeof n=="string"&&(n=n.replace(av,"defined($1)")),typeof a=="string"&&(a=a.replace(av,"defined($1)")),l.leftOperand=typeof a=="string"?this._ExtractOperation(a):a,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(av,"defined($1)")),typeof s=="string"?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new uw,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 r_(r):s==="#ifndef"?i.testExpression=new r_(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 ed;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=Ia._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const a=new nv;t.children.push(a);const l=this._BuildExpression(i,6);a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const a=new nv;t.children.push(a);const l=this._BuildExpression(i,7);a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}case"#if":{const a=new nv,l=this._BuildExpression(i,3);t.children.push(a),a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}}continue}}const s=new ed;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 ed,r=new cw;return r.lineIndex=-1,r.lines=e.split(` -`),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){var i;const s=e.defines,r={};for(const n of s){const l=n.replace("#define","").replace(";","").trim().split(" ");r[l[0]]=l.length>1?l[1]:""}return((i=e.processor)===null||i===void 0?void 0:i.shaderLanguage)===is.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",t._getGlobalDefines(r),r}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===is.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 s,r;let n=e;const a=t.defines,l=this._PreparePreProcessors(t,i);return!((s=t.processor)===null||s===void 0)&&s.preProcessor&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,l,t),!((r=t.processor)===null||r===void 0)&&r.postProcessor&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){n_.length=0;let s;for(;(s=mw.exec(e))!==null;)n_.push(s);let r=String(e),n=[e],a=!1;for(const l of n_){let h=l[1];if(h.indexOf("__decl__")!==-1&&(h=h.replace(gw,""),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;fC+"{X}")),c+=g.replace(zS,v.toString())+` -`}else t.supportsUniformBuffers||(c=c.replace(GS,(f,p)=>p+"{X}")),c=c.replace(zS,d)}const u=[];for(const d of n){const f=d.split(l[0]);for(let p=0;p=0||c.indexOf("#include <")>=0}else{const c=t.shadersRepository+"ShadersInclude/"+h+".fx";Ia._FileToolsLoadFile(c,u=>{t.includesShadersStore[h]=u,this._ProcessIncludes(n.join(""),t,i)});return}}n_.length=0,r=n.join(""),a?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw xt("FileTools")}}Ia._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class ne{static GetShadersRepository(e=is.GLSL){return e===is.GLSL?ne.ShadersRepository:ne.ShadersRepositoryWGSL}static GetShadersStore(e=is.GLSL){return e===is.GLSL?ne.ShadersStore:ne.ShadersStoreWGSL}static GetIncludesShadersStore(e=is.GLSL){return e===is.GLSL?ne.IncludesShadersStore:ne.IncludesShadersStoreWGSL}}ne.ShadersRepository="src/Shaders/";ne.ShadersStore={};ne.IncludesShadersStore={};ne.ShadersRepositoryWGSL="src/ShadersWGSL/";ne.ShadersStoreWGSL={};ne.IncludesShadersStoreWGSL={};class ji{static get ShadersRepository(){return ne.ShadersRepository}static set ShadersRepository(e){ne.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new he),this._onBindObservable}constructor(e,t,i,s=null,r,n=null,a=null,l=null,h=null,c,u="",d=is.GLSL){var f,p,_;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new he,this.onErrorObservable=new he,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u,t.attributes){const g=t;if(this._engine=i,this._attributesNames=g.attributes,this._uniformsNames=g.uniformsNames.concat(g.samplers),this._samplerList=g.samplers.slice(),this.defines=g.defines,this.onError=g.onError,this.onCompiled=g.onCompiled,this._fallbacks=g.fallbacks,this._indexParameters=g.indexParameters,this._transformFeedbackVaryings=g.transformFeedbackVaryings||null,this._multiTarget=!!g.multiTarget,this._shaderLanguage=(f=g.shaderLanguage)!==null&&f!==void 0?f:is.GLSL,g.uniformBuffersNames){this._uniformBuffersNamesList=g.uniformBuffersNames.slice();for(let v=0;v=","<=","<",">"];let r="",n=0;for(r of s)if(n=e.indexOf(r),n>-1)break;if(n===-1)return new r_(e);const a=e.substring(0,n).trim(),l=e.substring(n+r.length).trim();return new gw(a,r,l)}static _BuildSubExpression(e){e=e.replace(vw,"defined[$1]");const t=Ms.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],a=i[i.length-2];i.length-=2;const l=r=="&&"?new mw:new _w;typeof n=="string"&&(n=n.replace(av,"defined($1)")),typeof a=="string"&&(a=a.replace(av,"defined($1)")),l.leftOperand=typeof a=="string"?this._ExtractOperation(a):a,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(av,"defined($1)")),typeof s=="string"?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new pw,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 r_(r):s==="#ifndef"?i.testExpression=new r_(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 ed;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=Ia._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const a=new nv;t.children.push(a);const l=this._BuildExpression(i,6);a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const a=new nv;t.children.push(a);const l=this._BuildExpression(i,7);a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}case"#if":{const a=new nv,l=this._BuildExpression(i,3);t.children.push(a),a.children.push(l),this._MoveCursorWithinIf(e,a,l);break}}continue}}const s=new ed;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 ed,r=new fw;return r.lineIndex=-1,r.lines=e.split(` +`),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){var i;const s=e.defines,r={};for(const n of s){const l=n.replace("#define","").replace(";","").trim().split(" ");r[l[0]]=l.length>1?l[1]:""}return((i=e.processor)===null||i===void 0?void 0:i.shaderLanguage)===is.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",t._getGlobalDefines(r),r}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===is.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 s,r;let n=e;const a=t.defines,l=this._PreparePreProcessors(t,i);return!((s=t.processor)===null||s===void 0)&&s.preProcessor&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,l,t),!((r=t.processor)===null||r===void 0)&&r.postProcessor&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){n_.length=0;let s;for(;(s=xw.exec(e))!==null;)n_.push(s);let r=String(e),n=[e],a=!1;for(const l of n_){let h=l[1];if(h.indexOf("__decl__")!==-1&&(h=h.replace(Tw,""),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;fC+"{X}")),c+=g.replace(HS,v.toString())+` +`}else t.supportsUniformBuffers||(c=c.replace(WS,(f,p)=>p+"{X}")),c=c.replace(HS,d)}const u=[];for(const d of n){const f=d.split(l[0]);for(let p=0;p=0||c.indexOf("#include <")>=0}else{const c=t.shadersRepository+"ShadersInclude/"+h+".fx";Ia._FileToolsLoadFile(c,u=>{t.includesShadersStore[h]=u,this._ProcessIncludes(n.join(""),t,i)});return}}n_.length=0,r=n.join(""),a?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw xt("FileTools")}}Ia._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class ne{static GetShadersRepository(e=is.GLSL){return e===is.GLSL?ne.ShadersRepository:ne.ShadersRepositoryWGSL}static GetShadersStore(e=is.GLSL){return e===is.GLSL?ne.ShadersStore:ne.ShadersStoreWGSL}static GetIncludesShadersStore(e=is.GLSL){return e===is.GLSL?ne.IncludesShadersStore:ne.IncludesShadersStoreWGSL}}ne.ShadersRepository="src/Shaders/";ne.ShadersStore={};ne.IncludesShadersStore={};ne.ShadersRepositoryWGSL="src/ShadersWGSL/";ne.ShadersStoreWGSL={};ne.IncludesShadersStoreWGSL={};class ji{static get ShadersRepository(){return ne.ShadersRepository}static set ShadersRepository(e){ne.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new he),this._onBindObservable}constructor(e,t,i,s=null,r,n=null,a=null,l=null,h=null,c,u="",d=is.GLSL){var f,p,_;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new he,this.onErrorObservable=new he,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u,t.attributes){const g=t;if(this._engine=i,this._attributesNames=g.attributes,this._uniformsNames=g.uniformsNames.concat(g.samplers),this._samplerList=g.samplers.slice(),this.defines=g.defines,this.onError=g.onError,this.onCompiled=g.onCompiled,this._fallbacks=g.fallbacks,this._indexParameters=g.indexParameters,this._transformFeedbackVaryings=g.transformFeedbackVaryings||null,this._multiTarget=!!g.multiTarget,this._shaderLanguage=(f=g.shaderLanguage)!==null&&f!==void 0?f:is.GLSL,g.uniformBuffersNames){this._uniformBuffersNamesList=g.uniformBuffersNames.slice();for(let v=0;v{if(l[0]&&l[1]){a.isFragment=!0;const[c,u]=l;Ia.Process(u,a,(d,f)=>{this._fragmentSourceCodeBeforeMigration=f,this._processFinalCode&&(d=this._processFinalCode("fragment",d));const p=Ia.Finalize(c,d,a);a=null,this._useFinalCode(p.vertexCode,p.fragmentCode,r,t)},this._engine)}};this._loadShader(i,"Vertex","",c=>{Ia.Initialize(a),Ia.Process(c,a,(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===is.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+` `+e,this._fragmentSourceCode=(this._shaderLanguage===is.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 a=nx(e);s(a);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const a=window.atob(e.substr(7));s(a);return}const r=ne.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=ne.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getVertexShaderCode())!==null&&t!==void 0?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getFragmentShaderCode())!==null&&t!==void 0?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{const r=this.getEngine().scenes;if(r)for(let n=0;nthis._rebuildProgram(l,h,c,u);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,s,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let l=0;l{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 a=ox(e);s(a);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const a=window.atob(e.substr(7));s(a);return}const r=ne.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=ne.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getVertexShaderCode())!==null&&t!==void 0?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getFragmentShaderCode())!==null&&t!==void 0?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{const r=this.getEngine().scenes;if(r)for(let n=0;nthis._rebuildProgram(l,h,c,u);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,s,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let l=0;l=a&&(r=`Offending line [${a}] in ${i?"fragment":"vertex"} code: ${l[a-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,s,r;this._compilationError=e.message;const n=this._attributesNames,a=this._fallbacks;if(G.Error("Unable to compile effect:"),G.Error("Uniforms: "+this._uniformsNames.map(function(h){return" "+h})),G.Error("Attributes: "+n.map(function(h){return" "+h})),G.Error(`Defines: -`+this.defines),ji.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(G.Error("Vertex code:"),G.Error(u))),!((s=this._pipelineContext)===null||s===void 0)&&s._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((r=this._pipelineContext)===null||r===void 0?void 0:r._getFragmentShaderCode(),this._compilationError,!0),u&&(G.Error("Fragment code:"),G.Error(u))),h&&G.Error(h),c&&G.Error(c)}G.Error("Error: "+this._compilationError);const l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,G.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}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{r._swapAndDie(this,!1),this.isReady=i.isReady};i.isAsync?i.proxy.then(s):s(i.proxy);return}let t;switch(this.source){case Vt.Temp:break;case Vt.Url:t=this._engine.createTexture((e=this._originalUrl)!==null&&e!==void 0?e:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,i=>{i._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 Vt.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case Vt.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case Vt.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case Vt.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case Vt.Cube:t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case Vt.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case Vt.CubeRawRGBD:return;case Vt.CubePrefiltered:t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,i=>{i&&i._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),t._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;(i=this._hardwareTexture)===null||i===void 0||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const s=this._engine.getLoadedTexturesCache();let r=s.indexOf(this);r!==-1&&s.splice(r,1),r=s.indexOf(e),r===-1&&s.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Ti._Counter=0;class xw{constructor(){this.shaderLanguage=is.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 Tw=/(flat\s)?\s*varying\s*.*/;class lb{constructor(){this.shaderLanguage=is.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Tw.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; +`+this.defines),ji.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(G.Error("Vertex code:"),G.Error(u))),!((s=this._pipelineContext)===null||s===void 0)&&s._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((r=this._pipelineContext)===null||r===void 0?void 0:r._getFragmentShaderCode(),this._compilationError,!0),u&&(G.Error("Fragment code:"),G.Error(u))),h&&G.Error(h),c&&G.Error(c)}G.Error("Error: "+this._compilationError);const l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,G.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}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{r._swapAndDie(this,!1),this.isReady=i.isReady};i.isAsync?i.proxy.then(s):s(i.proxy);return}let t;switch(this.source){case Ut.Temp:break;case Ut.Url:t=this._engine.createTexture((e=this._originalUrl)!==null&&e!==void 0?e:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,i=>{i._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 Ut.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case Ut.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case Ut.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case Ut.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case Ut.Cube:t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case Ut.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case Ut.CubeRawRGBD:return;case Ut.CubePrefiltered:t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,i=>{i&&i._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),t._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;(i=this._hardwareTexture)===null||i===void 0||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const s=this._engine.getLoadedTexturesCache();let r=s.indexOf(this);r!==-1&&s.splice(r,1),r=s.indexOf(e),r===-1&&s.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Ti._Counter=0;class Sw{constructor(){this.shaderLanguage=is.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 Cw=/(flat\s)?\s*varying\s*.*/;class cb{constructor(){this.shaderLanguage=is.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Cw.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 Zh{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Zh._Counter++}}Zh._Counter=0;class Cd extends Zh{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Ew{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,a,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{n[d]=f});for(const d of h.getAttributes(this,a))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 a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}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.toArray())||(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 uu{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Or{static IsWrapper(e){return e.getPipelineContext===void 0}static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){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===void 0||s.reset())}dispose(){var e;(e=this.drawContext)===null||e===void 0||e.dispose()}}class hb{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===void 0||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;const i=!this.useStencilGlobalOnly&&!!(!((t=this.stencilMaterial)===null||t===void 0)&&t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?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 Sw{}class We{static get NpmPackage(){return"babylonjs@6.35.0"}static get Version(){return"6.35.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 ji.ShadersRepository}static set ShadersRepository(e){ji.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 We._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){var r,n,a,l,h,c,u,d,f,p,_;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 he,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new he,this.onContextRestoredObservable=new he,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new ab,this._stencilStateComposer=new hb,this._stencilState=new Cl,this._alphaState=new vw,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._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new he,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=ar.Now;let g=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,Dr.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=(r=i.deterministicLockstep)!==null&&r!==void 0?r:!1,i.lockstepMaxSteps=(n=i.lockstepMaxSteps)!==null&&n!==void 0?n:4,i.timeStep=(a=i.timeStep)!==null&&a!==void 0?a:1/60,i.audioEngine=(l=i.audioEngine)!==null&&l!==void 0?l:!0,i.stencil=(h=i.stencil)!==null&&h!==void 0?h:!0,this._audioContext=(u=(c=i.audioEngineOptions)===null||c===void 0?void 0:c.audioContext)!==null&&u!==void 0?u:null,this._audioDestination=(f=(d=i.audioEngineOptions)===null||d===void 0?void 0:d.audioDestination)!==null&&f!==void 0?f:null,this.premultipliedAlpha=(p=i.premultipliedAlpha)!==null&&p!==void 0?p:!0,this.useExactSrgbConversions=(_=i.useExactSrgbConversions)!==null&&_!==void 0?_:!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const v=gr()&&window.devicePixelRatio||1,E=i.limitDeviceRatio||v;if(this._hardwareScalingLevel=s?1/Math.min(E,v):1,this._lastDevicePixelRatio=v,!e)return;if(e.getContext){if(g=e,this._renderingCanvas=g,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const S=navigator.userAgent;for(const b of We.ExceptionList){const R=b.key,I=b.targets;if(new RegExp(R).test(S)){if(b.capture&&b.captureConstraint){const O=b.capture,L=b.captureConstraint,V=new RegExp(O).exec(S);if(V&&V.length>0&&parseInt(V[V.length-1])>=L)continue}for(const O of I)switch(O){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=S=>{S.preventDefault(),this._contextWasLost=!0,G.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},g.addEventListener("webglcontextlost",this._onContextLost,!1),g.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=g.getContext("webgl2",i)||g.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(!g)throw new Error("The provided canvas is null or undefined.");try{this._gl=g.getContext("webgl",i)||g.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 S=this._gl.getContextAttributes();S&&(i.stencil=S.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 S=0;S1?new lb:new xw,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const C=`Babylon.js v${We.Version}`;G.Log(C+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",C)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&Zu()&&"ontouchend"in document},this._checkForMobile(),gr()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),(t=this._rebuildComputeEffects)===null||t===void 0||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=n,G.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}ji.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuild();for(const e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||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,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._glVersion=this._gl.getParameter(this._gl.VERSION);const t=this._gl.getExtension("WEBGL_debug_renderer_info");if(t!=null&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),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=((e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!==null&&e!==void 0?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let i=0;i=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,gr()){const{cancelAnimationFrame:e}=this.getHostWindow()||window;if(typeof e=="function")return e(this._frameHandler)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return gr()?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 We.QueueNewFrame(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,s=!1){var r,n;const a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const c=(r=this._currentRenderTarget.texture)===null||r===void 0?void 0:r.format;if(c===8||c===9||c===10||c===11){const u=(n=this._currentRenderTarget.texture)===null||n===void 0?void 0:n.type;u===7||u===5?(We._TempClearColorUint32[0]=e.r*255,We._TempClearColorUint32[1]=e.g*255,We._TempClearColorUint32[2]=e.b*255,We._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,We._TempClearColorUint32),h=!1):(We._TempClearColorInt32[0]=e.r*255,We._TempClearColorInt32[1]=e.g*255,We._TempClearColorInt32[2]=e.b*255,We._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,We._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_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,a=e.y||0;this._cachedViewport=e,this._viewport(n*s,a*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=gr()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(gr()&&Zu())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,a=0){var l,h,c,u,d,f;const p=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(p._MSAAFramebuffer?p._MSAAFramebuffer:p._framebuffer);const _=this._gl;e.isMulti||(e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,(l=e.texture._hardwareTexture)===null||l===void 0?void 0:l.underlyingResource,n,a):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(h=e.texture._hardwareTexture)===null||h===void 0?void 0:h.underlyingResource,n):p._currentLOD!==n&&(_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,(c=e.texture._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,n),p._currentLOD=n));const g=e._depthStencilTexture;if(g){const v=e._depthStencilTextureWithStencil?_.DEPTH_STENCIL_ATTACHMENT:_.DEPTH_ATTACHMENT;e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,v,(u=g._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,n,a):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,v,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(d=g._hardwareTexture)===null||d===void 0?void 0:d.underlyingResource,n):_.framebufferTexture2D(_.FRAMEBUFFER,v,_.TEXTURE_2D,(f=g._hardwareTexture)===null||f===void 0?void 0:f.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,a=0){var l,h;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const c=!((h=(l=this.cullBackFaces)!==null&&l!==void 0?l:r)!==null&&h!==void 0)||h?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==c||i)&&(this._depthCullingState.cullFace=c),this.setZOffset(t),this.setZOffsetUnits(a);const u=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),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 s;const r=e;this._currentRenderTarget=null;const n=this._gl;if(r._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}n.bindFramebuffer(n.READ_FRAMEBUFFER,r._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,r._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}!((s=e.texture)===null||s===void 0)&&s.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,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 Cd(i);return this.bindArrayBuffer(s),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),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 Cd(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=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,a){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!==a&&(l.offset=a,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=r,l.stride=n,l.offset=a,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,a):this._gl.vertexAttribPointer(t,i,s,r,n,a))}_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=0){const a=s[r];let l=null;if(i&&(l=i[a]),l||(l=e[a]),!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 a=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,i[l],this._gl.FLOAT,!1,s,a)),a+=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{s[i[f]]=d}),this._uniforms=s;let u;for(u=0;u{n[d]=f});for(const d of h.getAttributes(this,a))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 a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}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.toArray())||(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 uu{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Or{static IsWrapper(e){return e.getPipelineContext===void 0}static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){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===void 0||s.reset())}dispose(){var e;(e=this.drawContext)===null||e===void 0||e.dispose()}}class ub{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===void 0||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;const i=!this.useStencilGlobalOnly&&!!(!((t=this.stencilMaterial)===null||t===void 0)&&t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?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 yw{}class We{static get NpmPackage(){return"babylonjs@6.35.0"}static get Version(){return"6.35.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 ji.ShadersRepository}static set ShadersRepository(e){ji.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 We._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){var r,n,a,l,h,c,u,d,f,p,_;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 he,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new he,this.onContextRestoredObservable=new he,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new lb,this._stencilStateComposer=new ub,this._stencilState=new Cl,this._alphaState=new Ew,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._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new he,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=ar.Now;let g=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,Dr.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=(r=i.deterministicLockstep)!==null&&r!==void 0?r:!1,i.lockstepMaxSteps=(n=i.lockstepMaxSteps)!==null&&n!==void 0?n:4,i.timeStep=(a=i.timeStep)!==null&&a!==void 0?a:1/60,i.audioEngine=(l=i.audioEngine)!==null&&l!==void 0?l:!0,i.stencil=(h=i.stencil)!==null&&h!==void 0?h:!0,this._audioContext=(u=(c=i.audioEngineOptions)===null||c===void 0?void 0:c.audioContext)!==null&&u!==void 0?u:null,this._audioDestination=(f=(d=i.audioEngineOptions)===null||d===void 0?void 0:d.audioDestination)!==null&&f!==void 0?f:null,this.premultipliedAlpha=(p=i.premultipliedAlpha)!==null&&p!==void 0?p:!0,this.useExactSrgbConversions=(_=i.useExactSrgbConversions)!==null&&_!==void 0?_:!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const v=gr()&&window.devicePixelRatio||1,E=i.limitDeviceRatio||v;if(this._hardwareScalingLevel=s?1/Math.min(E,v):1,this._lastDevicePixelRatio=v,!e)return;if(e.getContext){if(g=e,this._renderingCanvas=g,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const S=navigator.userAgent;for(const b of We.ExceptionList){const R=b.key,I=b.targets;if(new RegExp(R).test(S)){if(b.capture&&b.captureConstraint){const O=b.capture,L=b.captureConstraint,V=new RegExp(O).exec(S);if(V&&V.length>0&&parseInt(V[V.length-1])>=L)continue}for(const O of I)switch(O){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=S=>{S.preventDefault(),this._contextWasLost=!0,G.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},g.addEventListener("webglcontextlost",this._onContextLost,!1),g.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=g.getContext("webgl2",i)||g.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(!g)throw new Error("The provided canvas is null or undefined.");try{this._gl=g.getContext("webgl",i)||g.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 S=this._gl.getContextAttributes();S&&(i.stencil=S.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 S=0;S1?new cb:new Sw,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const C=`Babylon.js v${We.Version}`;G.Log(C+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",C)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&Zu()&&"ontouchend"in document},this._checkForMobile(),gr()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),(t=this._rebuildComputeEffects)===null||t===void 0||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=n,G.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}ji.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuild();for(const e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||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,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._glVersion=this._gl.getParameter(this._gl.VERSION);const t=this._gl.getExtension("WEBGL_debug_renderer_info");if(t!=null&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),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=((e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!==null&&e!==void 0?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let i=0;i=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,gr()){const{cancelAnimationFrame:e}=this.getHostWindow()||window;if(typeof e=="function")return e(this._frameHandler)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return gr()?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 We.QueueNewFrame(e,t)}runRenderLoop(e){this._activeRenderLoops.indexOf(e)===-1&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,s=!1){var r,n;const a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const c=(r=this._currentRenderTarget.texture)===null||r===void 0?void 0:r.format;if(c===8||c===9||c===10||c===11){const u=(n=this._currentRenderTarget.texture)===null||n===void 0?void 0:n.type;u===7||u===5?(We._TempClearColorUint32[0]=e.r*255,We._TempClearColorUint32[1]=e.g*255,We._TempClearColorUint32[2]=e.b*255,We._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,We._TempClearColorUint32),h=!1):(We._TempClearColorInt32[0]=e.r*255,We._TempClearColorInt32[1]=e.g*255,We._TempClearColorInt32[2]=e.b*255,We._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,We._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_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,a=e.y||0;this._cachedViewport=e,this._viewport(n*s,a*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=gr()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(gr()&&Zu())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,a=0){var l,h,c,u,d,f;const p=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(p._MSAAFramebuffer?p._MSAAFramebuffer:p._framebuffer);const _=this._gl;e.isMulti||(e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,(l=e.texture._hardwareTexture)===null||l===void 0?void 0:l.underlyingResource,n,a):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(h=e.texture._hardwareTexture)===null||h===void 0?void 0:h.underlyingResource,n):p._currentLOD!==n&&(_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,(c=e.texture._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,n),p._currentLOD=n));const g=e._depthStencilTexture;if(g){const v=e._depthStencilTextureWithStencil?_.DEPTH_STENCIL_ATTACHMENT:_.DEPTH_ATTACHMENT;e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,v,(u=g._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,n,a):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,v,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,(d=g._hardwareTexture)===null||d===void 0?void 0:d.underlyingResource,n):_.framebufferTexture2D(_.FRAMEBUFFER,v,_.TEXTURE_2D,(f=g._hardwareTexture)===null||f===void 0?void 0:f.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,a=0){var l,h;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const c=!((h=(l=this.cullBackFaces)!==null&&l!==void 0?l:r)!==null&&h!==void 0)||h?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==c||i)&&(this._depthCullingState.cullFace=c),this.setZOffset(t),this.setZOffsetUnits(a);const u=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),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 s;const r=e;this._currentRenderTarget=null;const n=this._gl;if(r._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}n.bindFramebuffer(n.READ_FRAMEBUFFER,r._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,r._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}!((s=e.texture)===null||s===void 0)&&s.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,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 bd(i);return this.bindArrayBuffer(s),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),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 bd(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=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,a){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!==a&&(l.offset=a,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=r,l.stride=n,l.offset=a,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,a):this._gl.vertexAttribPointer(t,i,s,r,n,a))}_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=0){const a=s[r];let l=null;if(i&&(l=i[a]),l||(l=e[a]),!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 a=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,i[l],this._gl.FLOAT,!1,s,a)),a+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?`#version 300 es #define WEBGL2 -`:"",l=this._compileShader(t,"vertex",s,a),h=this._compileShader(i,"fragment",s,a);return this._createShaderProgram(e,l,h,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new Ew;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 a=t.getProgramInfoLog(r);if(a)throw e.programLinkError=a,new Error(a)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const 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,a,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=a}_isRenderingStateCompiled(e){const t=e;return this._isDisposed||t._isDisposed?!1:this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)?(this._finalizePipelineContext(t),!0):!1}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),a===1&&!this._caps.textureFloat&&(a=0,G.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=this._gl,p=new Ti(this,s),_=e.width||e,g=e.height||e,v=e.layers||0,E=this._getSamplingParameters(l,n),C=v!==0?f.TEXTURE_2D_ARRAY:f.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(a,h,c),b=this._getInternalFormat(h),R=this._getWebGLTextureType(a);return this._bindTextureDirectly(C,p),v!==0?(p.is2DArray=!0,f.texImage3D(C,0,S,_,g,v,0,b,R,null)):f.texImage2D(C,0,S,_,g,0,b,R,null),f.texParameteri(C,f.TEXTURE_MAG_FILTER,E.mag),f.texParameteri(C,f.TEXTURE_MIN_FILTER,E.min),f.texParameteri(C,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(C,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(C),this._bindTextureDirectly(C,null),p._useSRGBBuffer=c,p.baseWidth=_,p.baseHeight=g,p.width=_,p.height=g,p.depth=v,p.isReady=!0,p.samples=u,p.generateMipMaps=n,p.samplingMode=l,p.type=a,p.format=h,p.label=d,this._internalTexturesCache.push(p),p}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,a=null,l,h,c=null,u=null,d=null,f=null,p,_,g){e=e||"";const v=e.substr(0,5)==="data:",E=e.substr(0,5)==="blob:",C=v&&e.indexOf(";base64,")!==-1,S=u||new Ti(this,Vt.Url);S!==u&&(S.label=e.substring(0,60));const b=e;this._transformTextureUrl&&!C&&!u&&!c&&(e=this._transformTextureUrl(e)),b!==e&&(S._originalUrl=b);const R=e.lastIndexOf(".");let I=f||(R>-1?e.substring(R).toLowerCase():""),N=null;I.indexOf("?")>-1&&(I=I.split("?")[0]);for(const V of We._TextureLoaders)if(V.canLoad(I,p)){N=V;break}s&&s.addPendingData(S),S.url=e,S.generateMipMaps=!t,S.samplingMode=r,S.invertY=i,S._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(S._buffer=c);let L=null;n&&!u&&(L=S.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(S);const B=(V,Z)=>{s&&s.removePendingData(S),e===b?(L&&S.onLoadedObservable.remove(L),ht.UseFallbackTexture&&this._createTextureBase(ht.FallbackTexture,t,S.invertY,s,r,null,a,l,h,c,S),V=(V||"Unknown error")+(ht.UseFallbackTexture?" - Fallback texture was used":""),S.onErrorObservable.notifyObservers({message:V,exception:Z}),a&&a(V,Z)):(G.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,S.invertY,s,r,n,a,l,h,c,S,d,f,p,_,g))};if(N){const V=Z=>{N.loadData(Z,S,(ue,oe,me,le,ae,ce)=>{ce?B("TextureLoader failed to load data"):l(S,I,s,{width:ue,height:oe},S.invertY,!me,le,()=>(ae(),!1),r)},_)};c?c instanceof ArrayBuffer?V(new Uint8Array(c)):ArrayBuffer.isView(c)?V(c):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,Z=>V(new Uint8Array(Z)),void 0,s?s.offlineProvider:void 0,!0,(Z,ue)=>{B("Unable to load "+(Z&&Z.responseURL,ue))})}else{const V=Z=>{E&&!this._doNotHandleContextLost&&(S._buffer=Z),l(S,I,s,Z,S.invertY,t,!1,h,r)};!v||C?c&&(typeof c.decoding=="string"||c.close)?V(c):We._FileToolsLoadImage(e,V,B,s?s.offlineProvider:null,p,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?We._FileToolsLoadImage(c,V,B,s?s.offlineProvider:null,p,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&V(c)}return S}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,s,r,n,a,this._prepareWebGLTexture.bind(this),(g,v,E,C,S,b)=>{const R=this._gl,I=E.width===g&&E.height===v,N=this._getTexImageParametersForCreateTexture(c,C,S._useSRGBBuffer);if(I)return R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,E),!1;const O=this._caps.maxTextureSize;if(E.width>O||E.height>O||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=v,this._workingContext.drawImage(E,0,0,E.width,E.height,0,0,g,v),R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,this._workingCanvas),S.width=g,S.height=v),!1;{const L=new Ti(this,Vt.Temp);this._bindTextureDirectly(R.TEXTURE_2D,L,!0),R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,E),this._rescaleTexture(L,S,s,N.format,()=>{this._releaseTexture(L),this._bindTextureDirectly(R.TEXTURE_2D,S,!0),b()})}return!0},l,h,c,u,d,f,_)}_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 xt("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,a,l=null,h=0,c=0,u=!1){throw xt("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,l=null){throw xt("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,a,l,h=null,c=0){throw xt("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,l,h=null,c=0){throw xt("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const a=t.width||t,l=t.height||t,h=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,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,a=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,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=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=a.TEXTURE_2D;e.isCube&&(u=a.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),p=n?e.width:Math.pow(2,Math.max(d-s,0)),_=n?e.height:Math.pow(2,Math.max(f-s,0));a.texImage2D(u,s,c,p,_,0,h,l,t)}updateTextureData(e,t,i,s,r,n,a=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,p=c.TEXTURE_2D;e.isCube&&(p=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,f=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),c.texSubImage2D(p,l,i,s,r,n,d,u,t),h&&this._gl.generateMipmap(p),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 a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,l,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?We.GetExponentOfTwo(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?We.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,a,h)})&&this._prepareWebGLTextureContinuation(e,i,n,a,h)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let a=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,a,a,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,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,a,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture((t=e._hardwareTexture)===null||t===void 0?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);i!==-1&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s-1;if(i&&l&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw G.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(n=(r=t==null?void 0:t._hardwareTexture)===null||r===void 0?void 0:r.underlyingResource)!==null&&n!==void 0?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return l&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const h=t.getInternalTexture();h&&(h._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const l=this._getTextureTarget(n);if(a&&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=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===void 0||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},gr()&&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,ji.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===void 0||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 a=t.RGBA,l=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,a,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 a=We._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),a}static _FileToolsLoadFile(e,t,i,s,r,n){throw xt("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);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=We.CeilingPOT(e),i=We.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=We.FloorPOT(e);break;case 2:s=We.NearestPOT(e);break;case 3:default:s=We.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(gr()){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:Zu()?document:null}}We._TempClearColorUint32=new Uint32Array(4);We._TempClearColorInt32=new Int32Array(4);We.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"]}];We._TextureLoaders=[];We.CollisionsEpsilon=.001;We._IsSupported=null;We._HasMajorPerformanceCaveat=null;class Qc{static SetImmediate(e){gr()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const cb=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class b_ extends Ko{constructor(e,t){super(e,sh.LoadFileError),this.name="LoadFileError",jc._setPrototypeOf(this,b_.prototype),t instanceof Hs?this.request=t:this.file=t}}class y_ extends Ko{constructor(e,t){super(e,sh.RequestFileError),this.request=t,this.name="RequestFileError",jc._setPrototypeOf(this,y_.prototype)}}class ax extends Ko{constructor(e,t){super(e,sh.ReadFileError),this.file=t,this.name="ReadFileError",jc._setPrototypeOf(this,ax.prototype)}}const sr={DefaultRetryStrategy:aw.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:o=>o,ScriptBaseUrl:"",ScriptPreprocessUrl:o=>o},ub=o=>(o=o.replace(/#/gm,"%23"),o),ox=(o,e)=>{if(!(o&&o.indexOf("data:")===0)&&sr.CorsBehavior)if(typeof sr.CorsBehavior=="string"||sr.CorsBehavior instanceof String)e.crossOrigin=sr.CorsBehavior;else{const t=sr.CorsBehavior(o);t&&(e.crossOrigin=t)}},Zf=(o,e,t,i,s="",r)=>{const n=ht.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(n!=null&&n._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;o instanceof ArrayBuffer||ArrayBuffer.isView(o)?typeof Blob<"u"&&typeof URL<"u"?(a=URL.createObjectURL(new Blob([o],{type:s})),l=!0):a=`data:${s};base64,`+rb(o):o instanceof Blob?(a=URL.createObjectURL(o),l=!0):(a=ub(o),a=sr.PreprocessUrl(o));const h=b=>{if(t){const R=a||o.toString();t(`Error while trying to load image: ${R.indexOf("http")===0||R.length<=128?R:R.slice(0,128)+"..."}`,b)}};if(n!=null&&n._features.forceBitmapOverHTMLImageElement)return ch(a,b=>{n.createImageBitmap(new Blob([b],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then(R=>{e(R),l&&URL.revokeObjectURL(a)}).catch(R=>{t&&t("Error while trying to load image: "+o,R)})},void 0,i||void 0,!0,(b,R)=>{h(R)}),null;const c=new Image;ox(a,c);const u=[],d=()=>{u.forEach(b=>{b.target.addEventListener(b.name,b.handler)})},f=()=>{u.forEach(b=>{b.target.removeEventListener(b.name,b.handler)}),u.length=0},p=()=>{f(),e(c),l&&c.src&&URL.revokeObjectURL(c.src)},_=b=>{f(),h(b),l&&c.src&&URL.revokeObjectURL(c.src)},g=b=>{if(b.blockedURI!==c.src)return;f();const R=new Error(`CSP violation of policy ${b.effectiveDirective} ${b.blockedURI}. Current policy is ${b.originalPolicy}`);ht.UseFallbackTexture=!1,h(R),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:p}),u.push({target:c,name:"error",handler:_}),u.push({target:document,name:"securitypolicyviolation",handler:g}),d();const v=a.substring(0,5)==="blob:",E=a.substring(0,5)==="data:",C=()=>{v||E||!Hs.IsCustomRequestAvailable?c.src=a:ch(a,(b,R,I)=>{const N=!s&&I?I:s,O=new Blob([b],{type:N}),L=URL.createObjectURL(O);l=!0,c.src=L},void 0,i||void 0,!0,(b,R)=>{h(R)})},S=()=>{i&&i.loadImage(a,c)};if(!v&&!E&&i&&i.enableTexturesOffline)i.open(S,C);else{if(a.indexOf("file:")!==-1){const b=decodeURIComponent(a.substring(5).toLowerCase());if(Ju.FilesToLoad[b]&&typeof URL<"u"){try{let R;try{R=URL.createObjectURL(Ju.FilesToLoad[b])}catch{R=URL.createObjectURL(Ju.FilesToLoad[b])}c.src=R,l=!0}catch{c.src=""}return c}}C()}return c},bd=(o,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new he,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new ax(`Unable to read ${o.name}`,o))}),r.onload=a=>{e(a.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(o):r.readAsText(o),n},ch=(o,e,t,i,s,r,n)=>{if(o.name)return bd(o,e,t,s,r?c=>{r(void 0,c)}:void 0);const a=o;if(a.indexOf("file:")!==-1){let c=decodeURIComponent(a.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=Ju.FilesToLoad[c];if(u)return bd(u,e,t,s,r?d=>r(void 0,new b_(d.message,d.file)):void 0)}const{match:l,type:h}=Cw(a);if(l){const c={onCompleteObservable:new he,abort:()=>()=>{}};try{const u=s?cx(a):fb(a);e(u,void 0,h)}catch(u){r?r(void 0,u):G.Error(u.message||"Failed to parse the Data URL")}return Qc.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return lx(a,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new b_(c.message,c.request))}:void 0,n)},lx=(o,e,t,i,s,r,n)=>{o=ub(o),o=sr.PreprocessUrl(o);const a=sr.BaseUrl+o;let l=!1;const h={onCompleteObservable:new he,abort:()=>l=!0},c=()=>{let u=new Hs,d=null,f;const p=()=>{u&&(t&&u.removeEventListener("progress",t),f&&u.removeEventListener("readystatechange",f),u.removeEventListener("loadend",_))};let _=()=>{p(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,f=null,_=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{l=!0,_&&_(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const g=E=>{const C=E.message||"Unknown error";r&&u?r(new y_(C,u)):G.Error(C)},v=E=>{if(u){if(u.open("GET",a),n)try{n(u)}catch(C){g(C);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),_&&u.addEventListener("loadend",_),f=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(f&&u.removeEventListener("readystatechange",f),u.status>=200&&u.status<300||u.status===0&&(!gr()||db())){try{e&&e(s?u.response:u.responseText,u)}catch(b){g(b)}return}const C=sr.DefaultRetryStrategy;if(C){const b=C(a,u,E);if(b!==-1){p(),u=new Hs,d=setTimeout(()=>v(E+1),b);return}}const S=new y_("Error status: "+u.status+" "+u.statusText+" - Unable to load "+a,u);r&&r(S)}},u.addEventListener("readystatechange",f),u.send()}};v(0)};if(i&&i.enableSceneOffline){const u=f=>{f&&f.status>400?r&&r(f):c()},d=()=>{i&&i.loadFile(sr.BaseUrl+o,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},db=()=>typeof location<"u"&&location.protocol==="file:",hx=o=>cb.test(o),Cw=o=>{const e=cb.exec(o);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function cx(o){return ow(o.split(",")[1])}const fb=o=>nb(o.split(",")[1]),bw=()=>{We._FileToolsLoadImage=Zf,We._FileToolsLoadFile=ch,Ia._FileToolsLoadFile=ch};bw();let $u;const yw=(o,e,t,i,s,r,n,a,l,h)=>{$u={DecodeBase64UrlToBinary:o,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty($u,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty($u,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty($u,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty($u,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};yw(cx,fb,sr,hx,db,ch,Zf,bd,lx,ox);class td{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Ds(e);if(t)return t;G.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{const e=Math.random()*16|0;return(o==="x"?e:e&3|8).toString(16)})}class fe{static get BaseUrl(){return sr.BaseUrl}static set BaseUrl(e){sr.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("://"){ch(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(fe.ScriptBaseUrl&&e.startsWith(fe._DefaultCdnUrl)){const i=fe.ScriptBaseUrl[fe.ScriptBaseUrl.length-1]==="/"?fe.ScriptBaseUrl.substring(0,fe.ScriptBaseUrl.length-1):fe.ScriptBaseUrl;e=e.replace(fe._DefaultCdnUrl,i)}return e=fe.ScriptPreprocessUrl(e),t&&(e=fe.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=fe.GetBabylonScriptURL(e),fe.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=fe.GetBabylonScriptURL(e),fe.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(a){i==null||i(`Unable to load script '${e}' in worker`,a)}return}else if(!gr()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=a=>{i&&i(`Unable to load script '${e}'`,a)},r.appendChild(n)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,r)=>{i(r||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new he,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 bd(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){Ur.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const l=atob(this.toDataURL(n,a).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;ut(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"}fe.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&&fe.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(fe._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(a=>{const l=new FileReader;l.readAsDataURL(a),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,a){throw xt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,l,h=!1,c=!1,u=!0,d){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,l=!1,h=!1,c=!0,u){throw xt("ScreenshotTools")}static RandomId(){return du()}static IsBase64(e){return hx(e)}static DecodeBase64(e){return cx(e)}static get errorsCount(){return G.errorsCount}static Log(e){G.Log(e)}static Warn(e){G.Warn(e)}static Error(e){G.Error(e)}static get LogCache(){return G.LogCache}static ClearLogCache(){G.ClearLogCache()}static set LogLevels(e){G.LogLevels=e}static set PerformanceLogLevel(e){if((e&fe.PerformanceUserMarkLogLevel)===fe.PerformanceUserMarkLogLevel){fe.StartPerformanceCounter=fe._StartUserMark,fe.EndPerformanceCounter=fe._EndUserMark;return}if((e&fe.PerformanceConsoleLogLevel)===fe.PerformanceConsoleLogLevel){fe.StartPerformanceCounter=fe._StartPerformanceConsole,fe.EndPerformanceCounter=fe._EndPerformanceConsole;return}fe.StartPerformanceCounter=fe._StartPerformanceCounterDisabled,fe.EndPerformanceCounter=fe._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!fe._Performance){if(!gr())return;fe._Performance=window.performance}!t||!fe._Performance.mark||fe._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!fe._Performance.mark||(fe._Performance.mark(e+"-End"),fe._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(fe._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(fe._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ar.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 ju()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}fe.UseCustomRequestHeaders=!1;fe.CustomRequestHeaders=Hs.CustomRequestHeaders;fe.GetDOMTextContent=nx;fe._DefaultCdnUrl="https://cdn.babylonjs.com";fe.GetAbsoluteUrl=typeof document=="object"?o=>{const e=document.createElement("a");return e.href=o,e.href}:typeof URL=="function"&&typeof location=="object"?o=>new URL(o,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};fe.NoneLogLevel=G.NoneLogLevel;fe.MessageLogLevel=G.MessageLogLevel;fe.WarningLogLevel=G.WarningLogLevel;fe.ErrorLogLevel=G.ErrorLogLevel;fe.AllLogLevel=G.AllLogLevel;fe.IsWindowObjectExist=gr;fe.PerformanceNoneLogLevel=0;fe.PerformanceUserMarkLogLevel=1;fe.PerformanceConsoleLogLevel=2;fe.StartPerformanceCounter=fe._StartPerformanceCounterDisabled;fe.EndPerformanceCounter=fe._EndPerformanceCounterDisabled;class eo{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{r&&r()?a.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(h),r&&r()){a.breakLoop();break}}a.executeNext()},n)},s)}}ht.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 qs{constructor(e){this.length=0,this.data=new Array(e),this._id=qs._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}qs._GlobalId=0;class Yl extends qs{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;tthis.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],s=e(t,i);if(s)return s}return null}}class Wn{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,s,r,n;const a=(s=(i=(t=this._externalProperties)===null||t===void 0?void 0:t[e])===null||i===void 0?void 0:i.type)!==null&&s!==void 0?s:typeof this[e],l=(n=(r=this._externalProperties)===null||r===void 0?void 0:r[e])===null||n===void 0?void 0:n.default;switch(a){case"number":this[e]=l??0;break;case"string":this[e]=l??"";break;default:this[e]=l??!1;break}}toString(){let e="";for(let t=0;t{s(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),a===1&&!this._caps.textureFloat&&(a=0,G.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=this._gl,p=new Ti(this,s),_=e.width||e,g=e.height||e,v=e.layers||0,E=this._getSamplingParameters(l,n),C=v!==0?f.TEXTURE_2D_ARRAY:f.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(a,h,c),b=this._getInternalFormat(h),R=this._getWebGLTextureType(a);return this._bindTextureDirectly(C,p),v!==0?(p.is2DArray=!0,f.texImage3D(C,0,S,_,g,v,0,b,R,null)):f.texImage2D(C,0,S,_,g,0,b,R,null),f.texParameteri(C,f.TEXTURE_MAG_FILTER,E.mag),f.texParameteri(C,f.TEXTURE_MIN_FILTER,E.min),f.texParameteri(C,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(C,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(C),this._bindTextureDirectly(C,null),p._useSRGBBuffer=c,p.baseWidth=_,p.baseHeight=g,p.width=_,p.height=g,p.depth=v,p.isReady=!0,p.samples=u,p.generateMipMaps=n,p.samplingMode=l,p.type=a,p.format=h,p.label=d,this._internalTexturesCache.push(p),p}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,a=null,l,h,c=null,u=null,d=null,f=null,p,_,g){e=e||"";const v=e.substr(0,5)==="data:",E=e.substr(0,5)==="blob:",C=v&&e.indexOf(";base64,")!==-1,S=u||new Ti(this,Ut.Url);S!==u&&(S.label=e.substring(0,60));const b=e;this._transformTextureUrl&&!C&&!u&&!c&&(e=this._transformTextureUrl(e)),b!==e&&(S._originalUrl=b);const R=e.lastIndexOf(".");let I=f||(R>-1?e.substring(R).toLowerCase():""),N=null;I.indexOf("?")>-1&&(I=I.split("?")[0]);for(const V of We._TextureLoaders)if(V.canLoad(I,p)){N=V;break}s&&s.addPendingData(S),S.url=e,S.generateMipMaps=!t,S.samplingMode=r,S.invertY=i,S._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(S._buffer=c);let L=null;n&&!u&&(L=S.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(S);const B=(V,Z)=>{s&&s.removePendingData(S),e===b?(L&&S.onLoadedObservable.remove(L),ht.UseFallbackTexture&&this._createTextureBase(ht.FallbackTexture,t,S.invertY,s,r,null,a,l,h,c,S),V=(V||"Unknown error")+(ht.UseFallbackTexture?" - Fallback texture was used":""),S.onErrorObservable.notifyObservers({message:V,exception:Z}),a&&a(V,Z)):(G.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,S.invertY,s,r,n,a,l,h,c,S,d,f,p,_,g))};if(N){const V=Z=>{N.loadData(Z,S,(ue,oe,me,le,ae,ce)=>{ce?B("TextureLoader failed to load data"):l(S,I,s,{width:ue,height:oe},S.invertY,!me,le,()=>(ae(),!1),r)},_)};c?c instanceof ArrayBuffer?V(new Uint8Array(c)):ArrayBuffer.isView(c)?V(c):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,Z=>V(new Uint8Array(Z)),void 0,s?s.offlineProvider:void 0,!0,(Z,ue)=>{B("Unable to load "+(Z&&Z.responseURL,ue))})}else{const V=Z=>{E&&!this._doNotHandleContextLost&&(S._buffer=Z),l(S,I,s,Z,S.invertY,t,!1,h,r)};!v||C?c&&(typeof c.decoding=="string"||c.close)?V(c):We._FileToolsLoadImage(e,V,B,s?s.offlineProvider:null,p,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?We._FileToolsLoadImage(c,V,B,s?s.offlineProvider:null,p,S.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&V(c)}return S}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,s,r,n,a,this._prepareWebGLTexture.bind(this),(g,v,E,C,S,b)=>{const R=this._gl,I=E.width===g&&E.height===v,N=this._getTexImageParametersForCreateTexture(c,C,S._useSRGBBuffer);if(I)return R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,E),!1;const O=this._caps.maxTextureSize;if(E.width>O||E.height>O||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=g,this._workingCanvas.height=v,this._workingContext.drawImage(E,0,0,E.width,E.height,0,0,g,v),R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,this._workingCanvas),S.width=g,S.height=v),!1;{const L=new Ti(this,Ut.Temp);this._bindTextureDirectly(R.TEXTURE_2D,L,!0),R.texImage2D(R.TEXTURE_2D,0,N.internalFormat,N.format,N.type,E),this._rescaleTexture(L,S,s,N.format,()=>{this._releaseTexture(L),this._bindTextureDirectly(R.TEXTURE_2D,S,!0),b()})}return!0},l,h,c,u,d,f,_)}_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 xt("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,a,l=null,h=0,c=0,u=!1){throw xt("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,l=null){throw xt("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,a,l,h=null,c=0){throw xt("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,l,h=null,c=0){throw xt("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const a=t.width||t,l=t.height||t,h=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,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,a=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,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=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=a.TEXTURE_2D;e.isCube&&(u=a.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),p=n?e.width:Math.pow(2,Math.max(d-s,0)),_=n?e.height:Math.pow(2,Math.max(f-s,0));a.texImage2D(u,s,c,p,_,0,h,l,t)}updateTextureData(e,t,i,s,r,n,a=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,p=c.TEXTURE_2D;e.isCube&&(p=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,f=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),c.texSubImage2D(p,l,i,s,r,n,d,u,t),h&&this._gl.generateMipmap(p),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 a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,l,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?We.GetExponentOfTwo(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?We.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,a,h)})&&this._prepareWebGLTextureContinuation(e,i,n,a,h)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let a=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,a,a,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,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,a,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture((t=e._hardwareTexture)===null||t===void 0?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);i!==-1&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s-1;if(i&&l&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw G.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(n=(r=t==null?void 0:t._hardwareTexture)===null||r===void 0?void 0:r.underlyingResource)!==null&&n!==void 0?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return l&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const h=t.getInternalTexture();h&&(h._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const l=this._getTextureTarget(n);if(a&&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=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===void 0||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},gr()&&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,ji.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===void 0||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 a=t.RGBA,l=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,a,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 a=We._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(l=>{this._activeRequests.splice(this._activeRequests.indexOf(l),1)}),a}static _FileToolsLoadFile(e,t,i,s,r,n){throw xt("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);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=We.CeilingPOT(e),i=We.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=We.FloorPOT(e);break;case 2:s=We.NearestPOT(e);break;case 3:default:s=We.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(gr()){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:Zu()?document:null}}We._TempClearColorUint32=new Uint32Array(4);We._TempClearColorInt32=new Int32Array(4);We.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"]}];We._TextureLoaders=[];We.CollisionsEpsilon=.001;We._IsSupported=null;We._HasMajorPerformanceCaveat=null;class Qc{static SetImmediate(e){gr()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const db=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class b_ extends Ko{constructor(e,t){super(e,rh.LoadFileError),this.name="LoadFileError",jc._setPrototypeOf(this,b_.prototype),t instanceof Hs?this.request=t:this.file=t}}class y_ extends Ko{constructor(e,t){super(e,rh.RequestFileError),this.request=t,this.name="RequestFileError",jc._setPrototypeOf(this,y_.prototype)}}class lx extends Ko{constructor(e,t){super(e,rh.ReadFileError),this.file=t,this.name="ReadFileError",jc._setPrototypeOf(this,lx.prototype)}}const sr={DefaultRetryStrategy:hw.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:o=>o,ScriptBaseUrl:"",ScriptPreprocessUrl:o=>o},fb=o=>(o=o.replace(/#/gm,"%23"),o),hx=(o,e)=>{if(!(o&&o.indexOf("data:")===0)&&sr.CorsBehavior)if(typeof sr.CorsBehavior=="string"||sr.CorsBehavior instanceof String)e.crossOrigin=sr.CorsBehavior;else{const t=sr.CorsBehavior(o);t&&(e.crossOrigin=t)}},Zf=(o,e,t,i,s="",r)=>{const n=ht.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(n!=null&&n._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;o instanceof ArrayBuffer||ArrayBuffer.isView(o)?typeof Blob<"u"&&typeof URL<"u"?(a=URL.createObjectURL(new Blob([o],{type:s})),l=!0):a=`data:${s};base64,`+ab(o):o instanceof Blob?(a=URL.createObjectURL(o),l=!0):(a=fb(o),a=sr.PreprocessUrl(o));const h=b=>{if(t){const R=a||o.toString();t(`Error while trying to load image: ${R.indexOf("http")===0||R.length<=128?R:R.slice(0,128)+"..."}`,b)}};if(n!=null&&n._features.forceBitmapOverHTMLImageElement)return uh(a,b=>{n.createImageBitmap(new Blob([b],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then(R=>{e(R),l&&URL.revokeObjectURL(a)}).catch(R=>{t&&t("Error while trying to load image: "+o,R)})},void 0,i||void 0,!0,(b,R)=>{h(R)}),null;const c=new Image;hx(a,c);const u=[],d=()=>{u.forEach(b=>{b.target.addEventListener(b.name,b.handler)})},f=()=>{u.forEach(b=>{b.target.removeEventListener(b.name,b.handler)}),u.length=0},p=()=>{f(),e(c),l&&c.src&&URL.revokeObjectURL(c.src)},_=b=>{f(),h(b),l&&c.src&&URL.revokeObjectURL(c.src)},g=b=>{if(b.blockedURI!==c.src)return;f();const R=new Error(`CSP violation of policy ${b.effectiveDirective} ${b.blockedURI}. Current policy is ${b.originalPolicy}`);ht.UseFallbackTexture=!1,h(R),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:p}),u.push({target:c,name:"error",handler:_}),u.push({target:document,name:"securitypolicyviolation",handler:g}),d();const v=a.substring(0,5)==="blob:",E=a.substring(0,5)==="data:",C=()=>{v||E||!Hs.IsCustomRequestAvailable?c.src=a:uh(a,(b,R,I)=>{const N=!s&&I?I:s,O=new Blob([b],{type:N}),L=URL.createObjectURL(O);l=!0,c.src=L},void 0,i||void 0,!0,(b,R)=>{h(R)})},S=()=>{i&&i.loadImage(a,c)};if(!v&&!E&&i&&i.enableTexturesOffline)i.open(S,C);else{if(a.indexOf("file:")!==-1){const b=decodeURIComponent(a.substring(5).toLowerCase());if(Ju.FilesToLoad[b]&&typeof URL<"u"){try{let R;try{R=URL.createObjectURL(Ju.FilesToLoad[b])}catch{R=URL.createObjectURL(Ju.FilesToLoad[b])}c.src=R,l=!0}catch{c.src=""}return c}}C()}return c},yd=(o,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new he,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new lx(`Unable to read ${o.name}`,o))}),r.onload=a=>{e(a.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(o):r.readAsText(o),n},uh=(o,e,t,i,s,r,n)=>{if(o.name)return yd(o,e,t,s,r?c=>{r(void 0,c)}:void 0);const a=o;if(a.indexOf("file:")!==-1){let c=decodeURIComponent(a.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=Ju.FilesToLoad[c];if(u)return yd(u,e,t,s,r?d=>r(void 0,new b_(d.message,d.file)):void 0)}const{match:l,type:h}=Aw(a);if(l){const c={onCompleteObservable:new he,abort:()=>()=>{}};try{const u=s?dx(a):_b(a);e(u,void 0,h)}catch(u){r?r(void 0,u):G.Error(u.message||"Failed to parse the Data URL")}return Qc.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return cx(a,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new b_(c.message,c.request))}:void 0,n)},cx=(o,e,t,i,s,r,n)=>{o=fb(o),o=sr.PreprocessUrl(o);const a=sr.BaseUrl+o;let l=!1;const h={onCompleteObservable:new he,abort:()=>l=!0},c=()=>{let u=new Hs,d=null,f;const p=()=>{u&&(t&&u.removeEventListener("progress",t),f&&u.removeEventListener("readystatechange",f),u.removeEventListener("loadend",_))};let _=()=>{p(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,f=null,_=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{l=!0,_&&_(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const g=E=>{const C=E.message||"Unknown error";r&&u?r(new y_(C,u)):G.Error(C)},v=E=>{if(u){if(u.open("GET",a),n)try{n(u)}catch(C){g(C);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),_&&u.addEventListener("loadend",_),f=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(f&&u.removeEventListener("readystatechange",f),u.status>=200&&u.status<300||u.status===0&&(!gr()||pb())){try{e&&e(s?u.response:u.responseText,u)}catch(b){g(b)}return}const C=sr.DefaultRetryStrategy;if(C){const b=C(a,u,E);if(b!==-1){p(),u=new Hs,d=setTimeout(()=>v(E+1),b);return}}const S=new y_("Error status: "+u.status+" "+u.statusText+" - Unable to load "+a,u);r&&r(S)}},u.addEventListener("readystatechange",f),u.send()}};v(0)};if(i&&i.enableSceneOffline){const u=f=>{f&&f.status>400?r&&r(f):c()},d=()=>{i&&i.loadFile(sr.BaseUrl+o,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},pb=()=>typeof location<"u"&&location.protocol==="file:",ux=o=>db.test(o),Aw=o=>{const e=db.exec(o);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function dx(o){return cw(o.split(",")[1])}const _b=o=>ob(o.split(",")[1]),Rw=()=>{We._FileToolsLoadImage=Zf,We._FileToolsLoadFile=uh,Ia._FileToolsLoadFile=uh};Rw();let $u;const Iw=(o,e,t,i,s,r,n,a,l,h)=>{$u={DecodeBase64UrlToBinary:o,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty($u,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty($u,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty($u,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty($u,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};Iw(dx,_b,sr,ux,pb,uh,Zf,yd,cx,hx);class td{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Ds(e);if(t)return t;G.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{const e=Math.random()*16|0;return(o==="x"?e:e&3|8).toString(16)})}class fe{static get BaseUrl(){return sr.BaseUrl}static set BaseUrl(e){sr.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("://"){uh(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(fe.ScriptBaseUrl&&e.startsWith(fe._DefaultCdnUrl)){const i=fe.ScriptBaseUrl[fe.ScriptBaseUrl.length-1]==="/"?fe.ScriptBaseUrl.substring(0,fe.ScriptBaseUrl.length-1):fe.ScriptBaseUrl;e=e.replace(fe._DefaultCdnUrl,i)}return e=fe.ScriptPreprocessUrl(e),t&&(e=fe.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=fe.GetBabylonScriptURL(e),fe.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=fe.GetBabylonScriptURL(e),fe.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(a){i==null||i(`Unable to load script '${e}' in worker`,a)}return}else if(!gr()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=a=>{i&&i(`Unable to load script '${e}'`,a)},r.appendChild(n)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,r)=>{i(r||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new he,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 yd(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){Ur.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const l=atob(this.toDataURL(n,a).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;ut(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"}fe.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&&fe.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(fe._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(a=>{const l=new FileReader;l.readAsDataURL(a),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,a){throw xt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,l,h=!1,c=!1,u=!0,d){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,l=!1,h=!1,c=!0,u){throw xt("ScreenshotTools")}static RandomId(){return du()}static IsBase64(e){return ux(e)}static DecodeBase64(e){return dx(e)}static get errorsCount(){return G.errorsCount}static Log(e){G.Log(e)}static Warn(e){G.Warn(e)}static Error(e){G.Error(e)}static get LogCache(){return G.LogCache}static ClearLogCache(){G.ClearLogCache()}static set LogLevels(e){G.LogLevels=e}static set PerformanceLogLevel(e){if((e&fe.PerformanceUserMarkLogLevel)===fe.PerformanceUserMarkLogLevel){fe.StartPerformanceCounter=fe._StartUserMark,fe.EndPerformanceCounter=fe._EndUserMark;return}if((e&fe.PerformanceConsoleLogLevel)===fe.PerformanceConsoleLogLevel){fe.StartPerformanceCounter=fe._StartPerformanceConsole,fe.EndPerformanceCounter=fe._EndPerformanceConsole;return}fe.StartPerformanceCounter=fe._StartPerformanceCounterDisabled,fe.EndPerformanceCounter=fe._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!fe._Performance){if(!gr())return;fe._Performance=window.performance}!t||!fe._Performance.mark||fe._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!fe._Performance.mark||(fe._Performance.mark(e+"-End"),fe._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(fe._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(fe._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ar.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 ju()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}fe.UseCustomRequestHeaders=!1;fe.CustomRequestHeaders=Hs.CustomRequestHeaders;fe.GetDOMTextContent=ox;fe._DefaultCdnUrl="https://cdn.babylonjs.com";fe.GetAbsoluteUrl=typeof document=="object"?o=>{const e=document.createElement("a");return e.href=o,e.href}:typeof URL=="function"&&typeof location=="object"?o=>new URL(o,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};fe.NoneLogLevel=G.NoneLogLevel;fe.MessageLogLevel=G.MessageLogLevel;fe.WarningLogLevel=G.WarningLogLevel;fe.ErrorLogLevel=G.ErrorLogLevel;fe.AllLogLevel=G.AllLogLevel;fe.IsWindowObjectExist=gr;fe.PerformanceNoneLogLevel=0;fe.PerformanceUserMarkLogLevel=1;fe.PerformanceConsoleLogLevel=2;fe.StartPerformanceCounter=fe._StartPerformanceCounterDisabled;fe.EndPerformanceCounter=fe._EndPerformanceCounterDisabled;class eo{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{r&&r()?a.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(h),r&&r()){a.breakLoop();break}}a.executeNext()},n)},s)}}ht.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 qs{constructor(e){this.length=0,this.data=new Array(e),this._id=qs._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}qs._GlobalId=0;class $l extends qs{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;tthis.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],s=e(t,i);if(s)return s}return null}}class Wn{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,s,r,n;const a=(s=(i=(t=this._externalProperties)===null||t===void 0?void 0:t[e])===null||i===void 0?void 0:i.type)!==null&&s!==void 0?s:typeof this[e],l=(n=(r=this._externalProperties)===null||r===void 0?void 0:r[e])===null||n===void 0?void 0:n.default;switch(a){case"number":this[e]=l??0;break;case"string":this[e]=l??"";break;default:this[e]=l??!1;break}}toString(){let e="";for(let t=0;tnew Es,this)}serialize(){return Xe.Serialize(this)}static Parse(e){return Xe.Parse(()=>new Es,e,null,null)}}A([D()],Es.prototype,"_globalHue",void 0);A([D()],Es.prototype,"_globalDensity",void 0);A([D()],Es.prototype,"_globalSaturation",void 0);A([D()],Es.prototype,"_globalExposure",void 0);A([D()],Es.prototype,"_highlightsHue",void 0);A([D()],Es.prototype,"_highlightsDensity",void 0);A([D()],Es.prototype,"_highlightsSaturation",void 0);A([D()],Es.prototype,"_highlightsExposure",void 0);A([D()],Es.prototype,"_midtonesHue",void 0);A([D()],Es.prototype,"_midtonesDensity",void 0);A([D()],Es.prototype,"_midtonesSaturation",void 0);A([D()],Es.prototype,"_midtonesExposure",void 0);Xe._ColorCurvesParser=Es.Parse;class Aw extends Wn{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 jt{constructor(){this.colorCurves=new Es,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=jt.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ze(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=jt.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new he}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Es.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}switch(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===jt._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case jt.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&&Es.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),a=n*r;const l=Math.sqrt(a*n);a=fe.Mix(a,l,this.vignetteStretch),n=fe.Mix(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return Xe.Clone(()=>new jt,this)}serialize(){return Xe.Serialize(this)}static Parse(e){const t=Xe.Parse(()=>new jt,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}}jt.TONEMAPPING_STANDARD=0;jt.TONEMAPPING_ACES=1;jt._VIGNETTEMODE_MULTIPLY=0;jt._VIGNETTEMODE_OPAQUE=1;A([JN()],jt.prototype,"colorCurves",void 0);A([D()],jt.prototype,"_colorCurvesEnabled",void 0);A([Jt("colorGradingTexture")],jt.prototype,"_colorGradingTexture",void 0);A([D()],jt.prototype,"_colorGradingEnabled",void 0);A([D()],jt.prototype,"_colorGradingWithGreenDepth",void 0);A([D()],jt.prototype,"_colorGradingBGR",void 0);A([D()],jt.prototype,"_exposure",void 0);A([D()],jt.prototype,"_toneMappingEnabled",void 0);A([D()],jt.prototype,"_toneMappingType",void 0);A([D()],jt.prototype,"_contrast",void 0);A([D()],jt.prototype,"vignetteStretch",void 0);A([D()],jt.prototype,"vignetteCenterX",void 0);A([D()],jt.prototype,"vignetteCenterY",void 0);A([D()],jt.prototype,"vignetteWeight",void 0);A([sx()],jt.prototype,"vignetteColor",void 0);A([D()],jt.prototype,"vignetteCameraFov",void 0);A([D()],jt.prototype,"_vignetteBlendMode",void 0);A([D()],jt.prototype,"_vignetteEnabled",void 0);A([D()],jt.prototype,"_ditheringEnabled",void 0);A([D()],jt.prototype,"_ditheringIntensity",void 0);A([D()],jt.prototype,"_skipFinalColorClamp",void 0);A([D()],jt.prototype,"_applyByPostProcess",void 0);A([D()],jt.prototype,"_isEnabled",void 0);Xe._ImageProcessingConfigurationParser=jt.Parse;We.prototype.createUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new Cd(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};We.prototype.createDynamicUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new Cd(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};We.prototype.updateUniformBuffer=function(o,e,t,i){this.bindUniformBuffer(o),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)};We.prototype.bindUniformBuffer=function(o){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,o?o.underlyingResource:null)};We.prototype.bindUniformBufferBase=function(o,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,o?o.underlyingResource:null)};We.prototype.bindUniformBlock=function(o,e,t){const i=o.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class it{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;r0){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;r1&&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&&(it._UpdatedUbosInFrame[this._name]||(it._UpdatedUbosInFrame[this._name]=0),it._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(s===void 0){if(this._buffer){G.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;ru[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),p=new Float32Array(e.buffer,u,c);return f.set(p),f}const d=u%4;return d&&(u=Math.max(0,u-d)),new Float32Array(e.buffer,u,c)}}return l?e.slice():e}}P._Counter=0;P.BYTE=5120;P.UNSIGNED_BYTE=5121;P.SHORT=5122;P.UNSIGNED_SHORT=5123;P.INT=5124;P.UNSIGNED_INT=5125;P.FLOAT=5126;P.PositionKind="position";P.NormalKind="normal";P.TangentKind="tangent";P.UVKind="uv";P.UV2Kind="uv2";P.UV3Kind="uv3";P.UV4Kind="uv4";P.UV5Kind="uv5";P.UV6Kind="uv6";P.ColorKind="color";P.ColorInstanceKind="instanceColor";P.MatricesIndicesKind="matricesIndices";P.MatricesWeightsKind="matricesWeights";P.MatricesIndicesExtraKind="matricesIndicesExtra";P.MatricesWeightsExtraKind="matricesWeightsExtra";class Vr{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(P.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const r=K.Vector3[0],n=K.Vector3[1],a=K.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(P.NormalKind);let c=i?T.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?T.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?T.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),d=d.scale(1-this.bu-this.bv),s=new T(c.x+u.x+d.x,c.y+u.y+d.y,c.z+u.z+d.z)}else{const h=this.pickedMesh.getVerticesData(P.PositionKind),c=i?T.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?T.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?T.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]),f=c.subtract(u),p=d.subtract(u);s=T.Cross(f,p)}const l=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(K.Matrix[0].copyFrom(u),u=K.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(K.Matrix[1]),u=K.Matrix[1]),T.TransformNormalToRef(c,u,c)};if(e&&l(this.pickedMesh,s),this.ray){const h=K.Vector3[0].copyFrom(s);e||l(this.pickedMesh,h),T.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=P.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=Re.FromArray(i,t[this.faceId*3]*2),r=Re.FromArray(i,t[this.faceId*3+1]*2),n=Re.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 Re(s.x+r.x+n.x,s.y+r.y+n.y)}}class A_{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[P.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[P.PositionKind]=new P(this._scene.getEngine(),e,P.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[P.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,r=0,n=!1){var a;const l=this._scene.getEngine();for(let h=0;hh!=null),s.length===0||!this._scene.postProcessesEnabled))return;const l=this._scene.getEngine();for(let h=0,c=s.length;ht._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._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=Ot.LeftClick&&i<=Ot.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=fu.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Ot.MouseWheelX:a.deltaX=s;break;case Ot.MouseWheelY:a.deltaY=s;break;case Ot.MouseWheelZ:a.deltaZ=s;break}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),l=r.pollInput(e,t,Ot.Horizontal),h=r.pollInput(e,t,Ot.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,R_.DeltaHorizontal),a.movementY=r.pollInput(e,t,R_.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=mt.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(mt.Keyboard),s=i&&t.pollInput(mt.Keyboard,0,18)===1,r=i&&t.pollInput(mt.Keyboard,0,17)===1,n=i&&(t.pollInput(mt.Keyboard,0,91)===1||t.pollInput(mt.Keyboard,0,92)===1||t.pollInput(mt.Keyboard,0,93)===1),a=i&&t.pollInput(mt.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class Pw{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,a)=>{const l=Oh.CreateDeviceEvent(s,r,n,a,this);i(s,r,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===mt.Mouse||e===mt.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const qS=255,jS=Object.keys(Ot).length/2;class Mw{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=fe.IsSafari(),this._usingMacOS=ju()&&/(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=ju()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=ju()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=fe.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 ${mt[e]}`;e>=mt.DualShock&&e<=mt.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${mt[e]} in slot ${t}`;return i===Ot.Move&&fe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this===null||this===void 0?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const s=+i,r=t[s];if(r)for(let n=0;n{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(mt.Keyboard,0,qS));const t=this._inputs[mt.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(mt.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(mt.Keyboard,0,qS));const t=this._inputs[mt.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=Oh.CreateDeviceEvent(mt.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(mt.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(mt.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[mt.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let r=s===mt.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===mt.Touch&&r===-1){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId,this._onDeviceConnected(s,r);else{fe.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 a=i;a.inputIndex=Ot.Move,n[Ot.Horizontal]=i.clientX,n[Ot.Vertical]=i.clientY,s===mt.Touch&&n[Ot.LeftClick]===0&&(n[Ot.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,a),!this._usingSafari&&i.button!==-1&&(a.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,a))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===mt.Mouse?0:i.pointerId;if(s===mt.Touch){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId;else{fe.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===mt.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=n[Ot.Horizontal],l=n[Ot.Vertical];if(s===mt.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[Ot.Horizontal]=i.clientX,n[Ot.Vertical]=i.clientY,n[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,r,h),(a!==i.clientX||l!==i.clientY)&&(h.inputIndex=Ot.Move,this._onInputChanged(s,r,h))}},this._pointerUpEvent=i=>{var s,r,n,a,l;const h=this._getPointerType(i),c=h===mt.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(h===mt.Touch){if(c===-1)return;this._activeTouchIds[c]=-1}const u=(s=this._inputs[h])===null||s===void 0?void 0:s[c];if(u&&u[i.button+2]!==0){const d=u[Ot.Horizontal],f=u[Ot.Vertical];u[Ot.Horizontal]=i.clientX,u[Ot.Vertical]=i.clientY,u[i.button+2]=0;const p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(p.inputIndex=Ot.Move,this._onInputChanged(h,c,p)),p.inputIndex=i.button+2,h===mt.Mouse&&this._mouseId>=0&&(!((n=(r=this._elementToAttachTo).hasPointerCapture)===null||n===void 0)&&n.call(r,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&(!((l=(a=this._elementToAttachTo).hasPointerCapture)===null||l===void 0)&&l.call(a,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(h,c,p),h===mt.Touch&&this._onDeviceDisconnected(h,c)}},this._pointerCancelEvent=i=>{var s,r,n,a;if(i.pointerType==="mouse"){const l=this._inputs[mt.Mouse][0];this._mouseId>=0&&(!((r=(s=this._elementToAttachTo).hasPointerCapture)===null||r===void 0)&&r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Ot.LeftClick;h<=Ot.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Oh.CreateDeviceEvent(mt.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(mt.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;!((a=(n=this._elementToAttachTo).hasPointerCapture)===null||a===void 0)&&a.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[mt.Touch][l][Ot.LeftClick]=0;const h=Oh.CreateDeviceEvent(mt.Touch,l,Ot.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(mt.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(mt.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,a;if(this.isDeviceAvailable(mt.Mouse)){const l=this._inputs[mt.Mouse][0];this._mouseId>=0&&(!((s=(i=this._elementToAttachTo).hasPointerCapture)===null||s===void 0)&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Ot.LeftClick;h<=Ot.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Oh.CreateDeviceEvent(mt.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(mt.Mouse,0,c)}}if(this.isDeviceAvailable(mt.Touch)){const l=this._inputs[mt.Touch];for(let h=0;h{const s=mt.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,jS));const n=this._inputs[s][r];if(n){n[Ot.MouseWheelX]=i.deltaX||0,n[Ot.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[Ot.MouseWheelZ]=i.deltaZ||0;const a=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[Ot.MouseWheelX]!==0&&(a.inputIndex=Ot.MouseWheelX,this._onInputChanged(s,r,a)),n[Ot.MouseWheelY]!==0&&(a.inputIndex=Ot.MouseWheelY,this._onInputChanged(s,r,a)),n[Ot.MouseWheelZ]!==0&&(a.inputIndex=Ot.MouseWheelZ,this._onInputChanged(s,r,a))}},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(mt.Mouse)){const i=this._inputs[mt.Mouse][0];i[Ot.MouseWheelX]=0,i[Ot.MouseWheelY]=0,i[Ot.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?mt.DualSense:mt.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?mt.Xbox:e.indexOf("057e")!==-1?mt.Switch:mt.Generic}_getPointerType(e){let t=mt.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=mt.Touch),t}}class QS{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new he,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Dw{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let a=0;a{const a=this._registeredManagers.indexOf(n);a>-1&&this._registeredManagers.splice(a,1)};const t=Object.keys(mt).length/2;this._devices=new Array(t);const i=(n,a)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][a]||(this._devices[n][a]=a);for(const l of this._registeredManagers){const h=new QS(this._deviceInputSystem,n,a);l._addDevice(h)}},s=(n,a)=>{var l;!((l=this._devices[n])===null||l===void 0)&&l[a]&&delete this._devices[n][a];for(const h of this._registeredManagers)h._removeDevice(n,a)},r=(n,a,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(n,a,l)};typeof _native<"u"?this._deviceInputSystem=new Pw(i,s,r):this._deviceInputSystem=new Mw(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Ow{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(mt).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Dw(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new he(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new he,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,s;const r=(i=this._devices[e])===null||i===void 0?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(r),!((s=this._devices[e])===null||s===void 0)&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])===null||s===void 0?void 0:s[t])===null||r===void 0||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case mt.Keyboard:case mt.Mouse:this._firstDevice[e]=0;break;case mt.Touch:case mt.DualSense:case mt.DualShock:case mt.Xbox:case mt.Switch:case mt.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=Ot.MouseWheelX&&t.inputIndex<=Ot.MouseWheelZ?rt.POINTERWHEEL:rt.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let a;e?(a=new Ja(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Ja(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,k.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 Iw(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const r=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Ot.Move,!this._checkPrePointerObservable(e,i,rt.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,rt.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,_r.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,_r.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(4,_r.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(3,_r.CreateNew(e.pickedMesh,t,e));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const a=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);a!=null&&a.pickedMesh&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>Vs.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,_r.CreateNew(a.pickedMesh,t)))},Vs.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=rt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Ja(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Ja(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=Ot.Move;const r=new ZS;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,rt.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=rt.POINTERPICK,a=new Ja(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(a,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,_r.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,_r.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,_r.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,_r.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Ja(rt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,rt.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,rt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=rt.POINTERTAP:i.doubleClick&&(n=rt.POINTERDOUBLETAP),n){const a=new Ja(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(a,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Ow(n),this._initActionManager=a=>{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);this._currentPickResult=l,l&&(a=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return a},this._delayedSimpleClick=(a,l,h)=>{if((Date.now()-this._previousStartingPointerTime>Vs.DoubleClickDelay&&!this._doubleClickOccured||a!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[a])){const c=this._delayedClicks[a].evt,u=rt.POINTERTAP,d=new Ja(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(d,u),this._delayedClicks[a]=null}},this._initClickEvent=(a,l,h,c)=>{var u,d;const f=new ZS;this._currentPickResult=null;let p=null,_=a.hasSpecificMask(rt.POINTERPICK)||l.hasSpecificMask(rt.POINTERPICK)||a.hasSpecificMask(rt.POINTERTAP)||l.hasSpecificMask(rt.POINTERTAP)||a.hasSpecificMask(rt.POINTERDOUBLETAP)||l.hasSpecificMask(rt.POINTERDOUBLETAP);!_&&aa&&(p=this._initActionManager(p,f),p&&(_=p.hasPickTriggers));let g=!1;if(_){const v=h.button;if(f.hasSwiped=this._isPointerSwiping(),!f.hasSwiped){let E=!Vs.ExclusiveDoubleClickMode;if(E||(E=!a.hasSpecificMask(rt.POINTERDOUBLETAP)&&!l.hasSpecificMask(rt.POINTERDOUBLETAP),E&&!aa.HasSpecificTrigger(6)&&(p=this._initActionManager(p,f),p&&(E=!p.hasSpecificTrigger(6)))),E)(Date.now()-this._previousStartingPointerTime>Vs.DoubleClickDelay||v!==this._previousButtonPressed)&&(f.singleClick=!0,c(f,this._currentPickResult),g=!0);else{const S={evt:h,clickInfo:f,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,v,f,c),Vs.DoubleClickDelay)};this._delayedClicks[v]=S}let C=a.hasSpecificMask(rt.POINTERDOUBLETAP)||l.hasSpecificMask(rt.POINTERDOUBLETAP);!C&&aa.HasSpecificTrigger(6)&&(p=this._initActionManager(p,f),p&&(C=p.hasSpecificTrigger(6))),C&&(v===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(a),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Vs.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Vs.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,a,a.inputIndex>=Ot.MouseWheelX&&a.inputIndex<=Ot.MouseWheelZ?rt.POINTERWHEEL:rt.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new Vr,a);return}r.pointerMovePredicate||(r.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0));const l=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(a):null;this._processPointerMove(l,a)},this._onPointerDown=a=>{var l;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Vs.ExclusiveDoubleClickMode){for(let c=0;cc.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let h;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?h=new Vr:h=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers),this._processPointerDown(h,a)},this._onPointerUp=a=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(a),r.preventDefaultOnPointerUp&&s&&(a.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,a,(l,h)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,a,rt.POINTERUP)){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(rt.POINTERTAP)&&this._checkPrePointerObservable(null,a,rt.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(rt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,a,rt.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[a.pointerId]){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(aa&&aa.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,a,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=a=>{const l=uh.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const h=new WS(l,a);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Nv(l,a);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(14,_r.CreateNewFromScene(r,a))},this._onKeyUp=a=>{const l=uh.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const h=new WS(l,a);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Nv(l,a);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(15,_r.CreateNewFromScene(r,a))},this._deviceSourceManager.onDeviceConnectedObservable.add(a=>{a.deviceType===mt.Mouse?a.onInputChangedObservable.add(l=>{l.inputIndex===Ot.LeftClick||l.inputIndex===Ot.MiddleClick||l.inputIndex===Ot.RightClick||l.inputIndex===Ot.BrowserBack||l.inputIndex===Ot.BrowserForward?t&&a.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&a.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===Ot.Move?this._onPointerMove(l):(l.inputIndex===Ot.MouseWheelX||l.inputIndex===Ot.MouseWheelY||l.inputIndex===Ot.MouseWheelZ)&&this._onPointerMove(l))}):a.deviceType===mt.Touch?a.onInputChangedObservable.add(l=>{l.inputIndex===Ot.LeftClick&&(t&&a.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&a.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===Ot.Move&&this._onPointerMove(l)}):a.deviceType===mt.Keyboard&&a.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,_r.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,_r.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]}}Vs.DragMovementThreshold=10;Vs.LongPressDelay=500;Vs.DoubleClickDelay=300;Vs.ExclusiveDoubleClickMode=!1;class Pa{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){Pa.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Pa.Enabled&&(this._startMonitoringTime=ar.Now)}endMonitoring(e=!0){if(!Pa.Enabled)return;e&&this.fetchNewFrame();const t=ar.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=ar.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Pa.Enabled=!0;class An{constructor(e,t,i,s){this.normal=new T(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new An(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=An._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,l=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],c=s*i[8]+r*i[9]+n*i[10]+a*i[11],u=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new An(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,a=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=r*h-n*l,u=n*a-s*h,d=s*l-r*a,f=Math.sqrt(c*c+u*u+d*d);let p;return f!==0?p=1/f:p=0,this.normal.x=c*p,this.normal.y=u*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return T.Dot(this.normal,e)<=t}signedDistanceTo(e){return T.Dot(e,this.normal)+this.d}static FromArray(e){return new An(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new An(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new An(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 T.Dot(i,t)+s}}An._TmpMatrix=k.Identity();class Aa{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new An(0,0,0,0));return Aa.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){Aa.GetNearPlaneToRef(e,t[0]),Aa.GetFarPlaneToRef(e,t[1]),Aa.GetLeftPlaneToRef(e,t[2]),Aa.GetRightPlaneToRef(e,t[3]),Aa.GetTopPlaneToRef(e,t[4]),Aa.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 Jf{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Jf._UniqueIdCounter=1;class Bi{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Bi.FALLOFF_DEFAULT=0;Bi.FALLOFF_PHYSICAL=1;Bi.FALLOFF_GLTF=2;Bi.FALLOFF_STANDARD=3;Bi.LIGHTMAP_DEFAULT=0;Bi.LIGHTMAP_SPECULAR=1;Bi.LIGHTMAP_SHADOWSONLY=2;Bi.INTENSITYMODE_AUTOMATIC=0;Bi.INTENSITYMODE_LUMINOUSPOWER=1;Bi.INTENSITYMODE_LUMINOUSINTENSITY=2;Bi.INTENSITYMODE_ILLUMINANCE=3;Bi.INTENSITYMODE_LUMINANCE=4;Bi.LIGHTTYPEID_POINTLIGHT=0;Bi.LIGHTTYPEID_DIRECTIONALLIGHT=1;Bi.LIGHTTYPEID_SPOTLIGHT=2;Bi.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Nw{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Xo;(function(o){o[o.BackwardCompatible=0]="BackwardCompatible",o[o.Intermediate=1]="Intermediate",o[o.Aggressive=2]="Aggressive"})(Xo||(Xo={}));class Qe extends ks{static DefaultMaterialFactory(e){throw xt("StandardMaterial")}static CollisionCoordinatorFactory(){throw xt("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 Xo.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Xo.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Xo.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 Vs.DragMovementThreshold}static set DragMovementThreshold(e){Vs.DragMovementThreshold=e}static get LongPressDelay(){return Vs.LongPressDelay}static set LongPressDelay(e){Vs.LongPressDelay=e}static get DoubleClickDelay(){return Vs.DoubleClickDelay}static set DoubleClickDelay(e){Vs.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Vs.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Vs.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 K.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,K.Vector4[0].x,K.Vector4[0].y,K.Vector4[0].z):e.setVector4(t,K.Vector4[0])),K.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=$C(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Qe.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Qe.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Vs(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ze(.2,.2,.3,1),this.ambientColor=new Te(0,0,0),this.environmentIntensity=1,this._performancePriority=Xo.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new he,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 he,this._onDisposeObserver=null,this.onBeforeRenderObservable=new he,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new he,this.onAfterRenderCameraObservable=new he,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new he,this.onAfterAnimationsObservable=new he,this.onBeforeDrawPhaseObservable=new he,this.onAfterDrawPhaseObservable=new he,this.onReadyObservable=new he,this.onBeforeCameraRenderObservable=new he,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new he,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new he,this.onAfterActiveMeshesEvaluationObservable=new he,this.onBeforeParticlesRenderingObservable=new he,this.onAfterParticlesRenderingObservable=new he,this.onDataLoadedObservable=new he,this.onNewCameraAddedObservable=new he,this.onCameraRemovedObservable=new he,this.onNewLightAddedObservable=new he,this.onLightRemovedObservable=new he,this.onNewGeometryAddedObservable=new he,this.onGeometryRemovedObservable=new he,this.onNewTransformNodeAddedObservable=new he,this.onTransformNodeRemovedObservable=new he,this.onNewMeshAddedObservable=new he,this.onMeshRemovedObservable=new he,this.onNewSkeletonAddedObservable=new he,this.onSkeletonRemovedObservable=new he,this.onNewMaterialAddedObservable=new he,this.onNewMultiMaterialAddedObservable=new he,this.onMaterialRemovedObservable=new he,this.onMultiMaterialRemovedObservable=new he,this.onNewTextureAddedObservable=new he,this.onTextureRemovedObservable=new he,this.onBeforeRenderTargetsRenderObservable=new he,this.onAfterRenderTargetsRenderObservable=new he,this.onBeforeStepObservable=new he,this.onAfterStepObservable=new he,this.onActiveCameraChanged=new he,this.onActiveCamerasChanged=new he,this.onBeforeRenderingGroupObservable=new he,this.onAfterRenderingGroupObservable=new he,this.onMeshImportedObservable=new he,this.onAnimationFileImportedObservable=new he,this._registeredForLateAnimationBindings=new Yl(256),this._pointerPickingConfiguration=new Nw,this.onPrePointerObservable=new he,this.onPointerObservable=new he,this.onPreKeyboardObservable=new he,this.onKeyboardObservable=new he,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Qe.FOGMODE_NONE,this.fogColor=new Te(.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 T(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Yl(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Pa,this._activeIndices=new Pa,this._activeParticles=new Pa,this._activeBones=new Pa,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 qs(256),this._processedMaterials=new qs(256),this._renderTargets=new Yl(256),this._materialsRenderTargets=new Yl(256),this._activeParticleSystems=new qs(256),this._activeSkeletons=new Yl(32),this._softwareSkinnedMeshes=new Yl(32),this._activeAnimatables=new Array,this._transformMatrix=k.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Fs.Create(),this._beforeClearStage=Fs.Create(),this._beforeRenderTargetClearStage=Fs.Create(),this._gatherRenderTargetsStage=Fs.Create(),this._gatherActiveCameraRenderTargetsStage=Fs.Create(),this._isReadyForMeshStage=Fs.Create(),this._beforeEvaluateActiveMeshStage=Fs.Create(),this._evaluateSubMeshStage=Fs.Create(),this._preActiveMeshStage=Fs.Create(),this._cameraDrawRenderTargetStage=Fs.Create(),this._beforeCameraDrawStage=Fs.Create(),this._beforeRenderTargetDrawStage=Fs.Create(),this._beforeRenderingGroupDrawStage=Fs.Create(),this._beforeRenderingMeshStage=Fs.Create(),this._afterRenderingMeshStage=Fs.Create(),this._afterRenderingGroupDrawStage=Fs.Create(),this._afterCameraDrawStage=Fs.Create(),this._afterCameraPostProcessStage=Fs.Create(),this._afterRenderTargetDrawStage=Fs.Create(),this._afterRenderTargetPostProcessStage=Fs.Create(),this._afterRenderStage=Fs.Create(),this._pointerMoveStage=Fs.Create(),this._pointerDownStage=Fs.Create(),this._pointerUpStage=Fs.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=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||ht.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(ht._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Fr(this),A_&&(this.postProcessManager=new A_(this)),gr()&&this.attachControl(),this._createUbo(),jt&&(this._imageProcessingConfiguration=new jt),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 t,i,s;if(this._isDisposed)return!1;let r;const n=this.getEngine(),a=n.currentRenderPassId;n.currentRenderPassId=(i=(t=this.activeCamera)===null||t===void 0?void 0:t.renderPassId)!==null&&i!==void 0?i:a;let l=!0;for(this._pendingData.length>0&&(l=!1),(s=this.prePassRenderer)===null||s===void 0||s.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&l&&(l=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r0;for(const d of this._isReadyForMeshStage)d.action(h,c)||(l=!1);if(!e)continue;const u=h.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const d of h.subMeshes){const f=d.getMaterial();f&&f.hasRenderTargetTextures&&f.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(f)===-1&&(this._processedMaterials.push(f),this._materialsRenderTargets.concatWithNoDuplicate(f.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(r=0;r0)for(const h of this.activeCameras)h.isReady(!0)||(l=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(l=!1));for(const h of this.particleSystems)h.isReady()||(l=!1);if(this.layers)for(const h of this.layers)h.isReady()||(l=!1);return n.areAllEffectsReady()||(l=!1),n.currentRenderPassId=a,l}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=ar.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?Aa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Aa.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 it(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 Jf.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(i=>{this.addMesh(i)}))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return i!==-1&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(s=>{this.removeMesh(s)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const 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=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;ne.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((e=this.activeCamera)===null||e===void 0||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const s=this._activeMeshes.length;for(let r=0;r0&&r.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(r),this.activeCamera._activeMeshes.push(r),n!==r&&n._activate(this._renderId,!1);for(const a of this._preActiveMeshStage)a.action(r);r._activate(this._renderId,!1)&&(r.isAnInstance?r._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=r):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(r,n)),r._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const h of this._gatherActiveCameraRenderTargetsStage)h.action(this._renderTargets);let l=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){fe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let h=0;h0),this._renderId++}for(const h of this._cameraDrawRenderTargetStage)l=h.action(this.activeCamera)||l;this._intermediateRendering=!1}this._engine.currentRenderPassId=(n=(r=(s=e.outputRenderTarget)===null||s===void 0?void 0:s.renderPassId)!==null&&r!==void 0?r:e.renderPassId)!==null&&n!==void 0?n:0,l&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const h of this._beforeCameraDrawStage)h.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),a.snapshotRendering&&a.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const h of this._afterCameraDrawStage)h.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const h=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,h)}for(const h of this._afterCameraPostProcessStage)h.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(s.trigger===13&&s._executeCurrent(_r.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(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Qe.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Qe.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let l=0;l0),this._intermediateRendering=!0;for(let l=0;l0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r=a==null?void 0:a.renderPassId)!==null&&r!==void 0?r:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const l of this._beforeClearStage)l.action();this._clearFrameBuffer(this.activeCamera);for(const l of this._gatherRenderTargetsStage)l.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let l=0;l0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const l of this._afterRenderStage)l.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let l=0;l{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){G.Error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;rr.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),ht._LastCreatedScene===this&&(this._engine.scenes.length>0?ht._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:ht._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!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const r=s.getBoundingInfo(),n=r.boundingBox.minimumWorld,a=r.boundingBox.maximumWorld;T.CheckExtends(n,t,i),T.CheckExtends(a,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw xt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw xt("Ray")}createPickingRayInCameraSpace(e,t,i){throw xt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw xt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const a=xt("Ray",!0);return a&&G.Warn(a),new Vr}pickWithBoundingInfo(e,t,i,s,r){const n=xt("Ray",!0);return n&&G.Warn(n),new Vr}pickWithRay(e,t,i,s){throw xt("Ray")}multiPick(e,t,i,s,r){throw xt("Ray")}multiPickWithRay(e,t,i){throw xt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const r in e){const n=e[r];ui&&ui.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,a){const l=ch(e,t,i,s?this.offlineProvider:void 0,r,n,a);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,a)=>{this._loadFile(e,l=>{n(l)},t,i,s,(l,h)=>{a(h)},r)})}_requestFile(e,t,i,s,r,n,a){const l=lx(e,t,i,s?this.offlineProvider:void 0,r,n,a);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,a)=>{this._requestFile(e,l=>{n(l)},t,i,s,l=>{a(l)},r)})}_readFile(e,t,i,s,r){const n=bd(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(a=>{this._activeRequests.splice(this._activeRequests.indexOf(a),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw xt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Qe.FOGMODE_NONE=0;Qe.FOGMODE_EXP=1;Qe.FOGMODE_EXP2=2;Qe.FOGMODE_LINEAR=3;Qe.MinDeltaTime=1;Qe.MaxDeltaTime=1e3;var _i;(function(o){o[o.LOCAL=0]="LOCAL",o[o.WORLD=1]="WORLD",o[o.BONE=2]="BONE"})(_i||(_i={}));class an{}an.X=new T(1,0,0);an.Y=new T(0,1,0);an.Z=new T(0,0,1);var wh;(function(o){o[o.X=0]="X",o[o.Y=1]="Y",o[o.Z=2]="Z"})(wh||(wh={}));class rs extends Mi{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,a=null){var l;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=(l=s==null?void 0:s.clone())!==null&&l!==void 0?l:k.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new k,this._absoluteBindMatrix=new k,this._absoluteInverseBindMatrix=new k,this._finalMatrix=new k,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(){var e;if(this._linkedTransformNode){const t=K.Vector3[0],i=K.Quaternion[0],s=K.Vector3[1];this.getRestMatrix().decompose(t,i,s),this._linkedTransformNode.position.copyFrom(s),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!==null&&e!==void 0?e:Se.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=T.Zero(),this._localRotation=Se.Zero(),this._localPosition=T.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,k.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-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{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let n=r.length-1;n>=0;n--){const a=r[n];e&&a.animation.name!=e||t&&!t(a.target)||(a.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{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;s0)return;this._animationTimeLast=o}this.deltaTime=this.useConstantAnimationDeltaTime?16:(o-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=o;const e=this._activeAnimatables;if(e.length===0)return;this._animationTime+=this.deltaTime;const t=this._animationTime;for(let i=0;io.playOrder-e.playOrder)};Qe.prototype.beginWeightedAnimation=function(o,e,t,i=1,s,r=1,n,a,l,h,c=!1){const u=this.beginAnimation(o,e,t,s,r,n,a,!1,l,h,c);return u.weight=i,u};Qe.prototype.beginAnimation=function(o,e,t,i,s=1,r,n,a=!0,l,h,c=!1){e>t&&s>0&&(s*=-1),a&&this.stopAnimation(o,void 0,l),n||(n=new _b(this,o,e,t,i,s,r,void 0,h,c));const u=l?l(o):!0;if(o.animations&&u&&n.appendAnimations(o,o.animations),o.getAnimatables){const d=o.getAnimatables();for(let f=0;fi&&r>0)r*=-1;else if(i>t&&r<0){const c=i;i=t,t=c}return new _b(this,o,t,i,s,r,n,e,a,l)};Qe.prototype.beginDirectHierarchyAnimation=function(o,e,t,i,s,r,n,a,l,h=!1){const c=o.getDescendants(e),u=[];u.push(this.beginDirectAnimation(o,t,i,s,r,n,a,l,h));for(const d of c)u.push(this.beginDirectAnimation(d,t,i,s,r,n,a,l,h));return u};Qe.prototype.getAnimatableByTarget=function(o){for(let e=0;e0?l:-l,s),f.scaleAndAddToRef(l,t)}s.normalize()}for(let u=0;u0)s.copyFrom(i);else if(o.animations.length===1){if(Se.SlerpToRef(i,t.currentValue,Math.min(1,o.totalWeight),s),o.totalAdditiveWeight===0)return s}else if(o.animations.length>1){let r=1,n,a;if(o.totalWeight<1){const h=1-o.totalWeight;n=[],a=[],n.push(i),a.push(h)}else{if(o.animations.length===2&&(Se.SlerpToRef(o.animations[0].currentValue,o.animations[1].currentValue,o.animations[1].weight/o.totalWeight,e),o.totalAdditiveWeight===0))return e;n=[],a=[],r=o.totalWeight}for(let h=0;h=n&&g.frame<=a&&(i?(E=g.value.clone(),d?(v=E.getTranslation(),E.setTranslation(v.scaleInPlace(f))):p&&s?(v=E.getTranslation(),E.setTranslation(v.multiplyInPlace(s))):E=g.value):E=g.value,_.push({frame:g.frame+t,value:E}));return this.animations[0].createRange(e,n+t,a+t),!0};var zc;(function(o){o[o.CW=0]="CW",o[o.CCW=1]="CCW"})(zc||(zc={}));class ko{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 ko(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new ko(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=ye.Clamp(s,-1,1);const r=Math.acos(s);return new ko(r)}static FromRadians(e){return new ko(e)}static FromDegrees(e){return new ko(e*Math.PI/180)}}class ww{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,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new Re((r*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*r)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=ko.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=ko.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=ko.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?zc.CW:zc.CCW,this.angle=ko.FromDegrees(this.orientation===zc.CW?l-c:c-l)}}class Q_{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Re(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new Re(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],a=new Re(e,t),l=new Re(i,s),h=new ww(n,a,l);let c=h.angle.radians()/r;h.orientation===zc.CW&&(c*=-1);let u=h.startAngle.radians()+c;for(let d=0;d(1-l)*(1-l)*h+2*l*(1-l)*c+l*l*u,a=this._points[this._points.length-1];for(let l=0;l<=r;l++){const h=l/r,c=n(h,a.x,e,i),u=n(h,a.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,r,n,a=36){if(this.closed)return this;const l=(c,u,d,f,p)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*d+3*c*c*(1-c)*f+c*c*c*p,h=this._points[this._points.length-1];for(let c=0;c<=a;c++){const u=c/a,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;rNumber.EPSILON){if(h<0&&(n=this._points[r],l=-l,a=this._points[s],h=-h),e.ya.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(a.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=a.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return Re.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=h){const c=l.normalize(),u=t-i;return new Re(n.x+c.x*u,n.y+c.y*u)}i=h}return Re.Zero()}static StartingAt(e,t){return new Q_(e,t)}}class yd{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:T.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:k.Identity()};for(let r=0;rt){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),a=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(r++,l.push(s)),l.push(...i.slice(r,a)),(t!==1||e===1)&&l.push(n),new yd(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;st+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;ye.WithinEpsilon(Math.abs(e.y)/s,1,$t)?ye.WithinEpsilon(Math.abs(e.x)/s,1,$t)?ye.WithinEpsilon(Math.abs(e.z)/s,1,$t)?r=T.Zero():r=new T(0,0,1):r=new T(1,0,0):r=new T(0,-1,0),i=T.Cross(e,r)}else i=T.Cross(e,t),T.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 a=e*this.length();for(let l=1;la){const u=(n-a)/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=k.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(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=Se.RotationQuaternionFromAxis(s,r,i),c=Se.RotationQuaternionFromAxis(a,l,n);Se.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Lo{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(a,l,h,c)=>(1-a)*(1-a)*l+2*a*(1-a)*h+a*a*c;for(let a=0;a<=s;a++)r.push(new T(n(a/s,e.x,t.x,i.x),n(a/s,e.y,t.y,i.y),n(a/s,e.z,t.z,i.z)));return new Lo(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],a=(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 T(a(l/r,e.x,t.x,i.x,s.x),a(l/r,e.y,t.y,i.y,s.y),a(l/r,e.z,t.z,i.z,s.z)));return new Lo(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],a=1/r;for(let l=0;l<=r;l++)n.push(T.Hermite(e,t,i,s,l*a));return new Lo(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const a=e.length;for(let l=0;l=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}ln.EASINGMODE_EASEIN=0;ln.EASINGMODE_EASEOUT=1;ln.EASINGMODE_EASEINOUT=2;class Fw extends ln{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Lw extends ln{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 Bw extends ln{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 Vw extends ln{easeInCore(e){return e*e}}class mb extends ln{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Uw{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class ml{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let t=0;tn&&(n=l.to);const a=new ml(e[0].name+"_merged",e[0]._scene,s);for(const l of e){i&&l.normalize(r,n);for(const h of l.targetedAnimations)a.addTargetedAnimation(h.animation,h.target);t&&l.dispose()}return a}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new he,this.onAnimationLoopObservable=new he,this.onAnimationGroupLoopObservable=new he,this.onAnimationGroupEndObservable=new he,this.onAnimationGroupPauseObservable=new he,this.onAnimationGroupPlayObservable=new he,this.metadata=null,this._animationLoopFlags=[],this._scene=t||ht.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Uw;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-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;ie){const l={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,l)}if(a.frame{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.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(l)},this._processLoop(l,a,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;e0&&(this._scene._activeAnimatables[t++]=s)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-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 ml(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_[0].frame&&(h=_[0].frame),c<_[_.length-1].frame&&(c=_[_.length-1].frame)}a._from=h,a._to=c}return a}static ClipKeys(e,t,i,s,r){const n=e.clone(s||e.name);return ml.ClipKeysInPlace(n,t,i,r)}static ClipKeysInPlace(e,t,i,s){return ml.ClipInPlace(e,t,i,s,!1)}static ClipFrames(e,t,i,s,r){const n=e.clone(s||e.name);return ml.ClipFramesInPlace(n,t,i,r)}static ClipFramesInPlace(e,t,i,s){return ml.ClipInPlace(e,t,i,s,!0)}static ClipInPlace(e,t,i,s,r=!1){let n=Number.MAX_VALUE,a=-Number.MAX_VALUE;const l=e.targetedAnimations;for(let h=0;h=t&&_<=i||r&&g.frame>=t&&g.frame<=i){const v={frame:g.frame,value:g.value.clone?g.value.clone():g.value,inTangent:g.inTangent,outTangent:g.outTangent,interpolation:g.interpolation,lockedTangent:g.lockedTangent};p===Number.MAX_VALUE&&(p=v.frame),v.frame-=p,f.push(v)}}if(f.length===0){l.splice(h,1),h--;continue}n>f[0].frame&&(n=f[0].frame),a{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function kw(o=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>o?(e=r,setTimeout(()=>{I_(t,i,s)},0)):I_(t,i,s)}}function gb(o,e,t,i,s){const r=()=>{let n;const a=l=>{l.done?t(l.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(o,a,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function ux(o,e){let t;return gb(o,I_,i=>t=i,i=>{throw i},e),t}function vb(o,e,t){return new Promise((i,s)=>{gb(o,e,i,s,t)})}function Gw(o,e){return(...t)=>ux(o(...t),e)}class Na{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Na(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 Na(this.x,this.y,this.width,this.height)}}class et extends Mi{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,s;let r=0,n=0;if(this.mode===et.PERSPECTIVE_CAMERA)this.fovMode===et.FOVMODE_VERTICAL_FIXED?(n=this.minZ*2*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*n):(r=this.minZ*2*Math.tan(this.fov/2),n=r/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;r=((e=this.orthoRight)!==null&&e!==void 0?e:a)-((t=this.orthoLeft)!==null&&t!==void 0?t:-a),n=((i=this.orthoTop)!==null&&i!==void 0?i:l)-((s=this.orthoBottom)!==null&&s!==void 0?s:-l)}return r*n}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}constructor(e,t,i,s=!0){super(e,i),this._position=T.Zero(),this._upVector=T.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=et.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Na(0,0,1,1),this.layerMask=268435455,this.fovMode=et.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=et.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new he,this.onProjectionMatrixChangedObservable=new he,this.onAfterCheckInputsObservable=new he,this.onRestoreStateObservable=new he,this.isRigCamera=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new k,this._postProcesses=new Array,this._activeMeshes=new qs(256),this._globalPosition=T.Zero(),this._computedViewMatrix=k.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=k.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Se.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-1?(G.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 k.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const b=this.getEngine(),R=this.getScene(),I=b.useReverseDepthBuffer;if(this.mode===et.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=b.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let N;R.useRightHandedSystem?N=k.PerspectiveFovRHToRef:N=k.PerspectiveFovLHToRef,N(this.fov,b.getAspectRatio(this),I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===et.FOVMODE_VERTICAL_FIXED,b.isNDCHalfZRange,this.projectionPlaneTilt,I)}else{const N=b.getRenderWidth()/2,O=b.getRenderHeight()/2;R.useRightHandedSystem?this.oblique?k.ObliqueOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-N,(i=this.orthoRight)!==null&&i!==void 0?i:N,(s=this.orthoBottom)!==null&&s!==void 0?s:-O,(r=this.orthoTop)!==null&&r!==void 0?r:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):k.OrthoOffCenterRHToRef((n=this.orthoLeft)!==null&&n!==void 0?n:-N,(a=this.orthoRight)!==null&&a!==void 0?a:N,(l=this.orthoBottom)!==null&&l!==void 0?l:-O,(h=this.orthoTop)!==null&&h!==void 0?h:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange):this.oblique?k.ObliqueOffCenterLHToRef((c=this.orthoLeft)!==null&&c!==void 0?c:-N,(u=this.orthoRight)!==null&&u!==void 0?u:N,(d=this.orthoBottom)!==null&&d!==void 0?d:-O,(f=this.orthoTop)!==null&&f!==void 0?f:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):k.OrthoOffCenterLHToRef((p=this.orthoLeft)!==null&&p!==void 0?p:-N,(_=this.orthoRight)!==null&&_!==void 0?_:N,(g=this.orthoBottom)!==null&&g!==void 0?g:-O,(v=this.orthoTop)!==null&&v!==void 0?v:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(E=this.oblique)===null||E===void 0?void 0:E.angle,this._cache.obliqueLength=(C=this.oblique)===null||C===void 0?void 0:C.length,this._cache.obliqueOffset=(S=this.oblique)===null||S===void 0?void 0:S.offset,this._cache.renderWidth=b.getRenderWidth(),this._cache.renderHeight=b.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?T.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Aa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Aa.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 xt("Ray")}getForwardRayToRef(e,t=100,i,s){throw xt("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!==et.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=fe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==et.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 k.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=fe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eet._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=et.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Xe.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=T.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(T.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(T.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{throw xt("UniversalCamera")};et.PERSPECTIVE_CAMERA=0;et.ORTHOGRAPHIC_CAMERA=1;et.FOVMODE_VERTICAL_FIXED=0;et.FOVMODE_HORIZONTAL_FIXED=1;et.RIG_MODE_NONE=0;et.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;et.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;et.RIG_MODE_STEREOSCOPIC_INTERLACED=14;et.RIG_MODE_VR=20;et.RIG_MODE_CUSTOM=22;et.ForceAttachControlToAlwaysPreventDefault=!1;A([kr("position")],et.prototype,"_position",void 0);A([kr("upVector")],et.prototype,"_upVector",void 0);A([D()],et.prototype,"orthoLeft",null);A([D()],et.prototype,"orthoRight",null);A([D()],et.prototype,"orthoBottom",null);A([D()],et.prototype,"orthoTop",null);A([D()],et.prototype,"fov",void 0);A([D()],et.prototype,"projectionPlaneTilt",void 0);A([D()],et.prototype,"minZ",void 0);A([D()],et.prototype,"maxZ",void 0);A([D()],et.prototype,"inertia",void 0);A([D()],et.prototype,"mode",null);A([D()],et.prototype,"layerMask",void 0);A([D()],et.prototype,"fovMode",void 0);A([D()],et.prototype,"cameraRigMode",void 0);A([D()],et.prototype,"interaxialDistance",void 0);A([D()],et.prototype,"isStereoscopicSideBySide",void 0);class wv{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Eo{constructor(e,t,i){this.vectors=js.BuildArray(8,T.Zero),this.center=T.Zero(),this.centerWorld=T.Zero(),this.extendSize=T.Zero(),this.extendSizeWorld=T.Zero(),this.directions=js.BuildArray(3,T.Zero),this.vectorsWorld=js.BuildArray(8,T.Zero),this.minimumWorld=T.Zero(),this.maximumWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,l,h),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(a,l,h),c[2].copyFromFloats(a,r,n),c[3].copyFromFloats(s,l,n),c[4].copyFromFloats(s,r,h),c[5].copyFromFloats(a,l,n),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||k.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Eo._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),a=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(a,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 a=0;a<8;++a)r[a].copyFrom(n[a]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let a=0;a<8;++a){const l=r[a];T.TransformCoordinatesToRef(n[a],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}T.FromArrayToRef(e.m,0,s[0]),T.FromArrayToRef(e.m,4,s[1]),T.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Eo.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Eo.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,a=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,f=-$t;return!(a-cc-s||l-uu-r||h-dd-n)}intersectsSphere(e){return Eo.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,l=s.x,h=s.y,c=s.z,u=e.x,d=e.y,f=e.z,p=t.x,_=t.y,g=t.z;return!(lp||h_||cg)}dispose(){var e,t;(e=this._drawWrapperFront)===null||e===void 0||e.dispose(),(t=this._drawWrapperBack)===null||t===void 0||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Eo._TmpVector3[0];return T.ClampToRef(i,e,t,r),T.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}}Eo._TmpVector3=js.BuildArray(3,T.Zero);class Rl{constructor(e,t,i){this.center=T.Zero(),this.centerWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=T.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||k.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Rl._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{T.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Rl._TmpVector3[0];T.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=T.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=T.Dot(e.centerWorld,o),s=Math.abs(T.Dot(e.directions[0],o))*e.extendSize.x,r=Math.abs(T.Dot(e.directions[1],o))*e.extendSize.y,n=Math.abs(T.Dot(e.directions[2],o))*e.extendSize.z,a=s+r+n;t.min=i-a,t.max=i+a},Vn=(o,e,t)=>(e0(o,e,ov),e0(o,t,lv),!(ov.min>lv.max||lv.min>ov.max));class ha{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Eo(e,t,i),this.boundingSphere=new Rl(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=ha._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=ha._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=T.Minimize(this.minimum,e),i=T.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=K.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=K.Vector3[0];return T.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),T.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,ha._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(!Rl.Intersects(this.boundingSphere,e.boundingSphere)||!Eo.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!Vn(i.directions[0],i,s)||!Vn(i.directions[1],i,s)||!Vn(i.directions[2],i,s)||!Vn(s.directions[0],i,s)||!Vn(s.directions[1],i,s)||!Vn(s.directions[2],i,s)||!Vn(T.Cross(i.directions[0],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[0],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[0],s.directions[2]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[2]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[2]),i,s))}}ha._TmpVector3=js.BuildArray(2,T.Zero);class Z_{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a!Array.isArray(o)&&!Array.isArray(e))],Z_,"extractMinAndMaxIndexed",null);A([hh.filter((...[o])=>!Array.isArray(o))],Z_,"extractMinAndMax",null);function zw(o,e,t,i,s=null){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Z_.extractMinAndMaxIndexed(o,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 Ad(o,e,t,i=null,s){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),Z_.extractMinAndMax(o,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 on{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())===null||e===void 0?void 0:e.defines}set materialDefines(e){var t;const i=(t=this._mainDrawWrapperOverride)!==null&&t!==void 0?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Or(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])===null||i===void 0||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())===null||e===void 0?void 0:e.effect)!==null&&t!==void 0?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!==null&&e!==void 0?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,a,l=!0){return new on(e,t,i,s,r,n,a,l)}constructor(e,t,i,s,r,n,a,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=a||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){var t;const i=(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!==null&&t!==void 0?t:this._renderingMesh.material;if(i){if(this._isMultiMaterial(i)){const s=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return i}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(P.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=zw(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ha(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let s=this.indexStart;sl&&(l=d)}return new on(e,a,l-a+1,t,i,s,r,n)}}class g_{}class De{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Gw(this._applyToCoroutine.bind(this)),this.uniqueId=De._UniqueIDGenerator,De._UniqueIDGenerator++}set(e,t){switch(e.length||G.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case P.PositionKind:this.positions=e;break;case P.NormalKind:this.normals=e;break;case P.TangentKind:this.tangents=e;break;case P.UVKind:this.uvs=e;break;case P.UV2Kind:this.uvs2=e;break;case P.UV3Kind:this.uvs3=e;break;case P.UV4Kind:this.uvs4=e;break;case P.UV5Kind:this.uvs5=e;break;case P.UV6Kind:this.uvs6=e;break;case P.ColorKind:this.colors=e;break;case P.MatricesIndicesKind:this.matricesIndices=e;break;case P.MatricesWeightsKind:this.matricesWeights=e;break;case P.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case P.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(P.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(P.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(P.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(P.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(P.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(P.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(P.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(P.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(P.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(P.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(P.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(P.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(P.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 on(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(P.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(P.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(P.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(P.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(P.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(P.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(P.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(P.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(P.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(P.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(P.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(P.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(P.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=K.Vector3[0],n=K.Vector3[1];for(let a=i;a({vertexData:a})):[{vertexData:e}];return ux(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,a=!1){var l,h,c,u;this._validate();let d=t.map(v=>v.vertexData),f=this;if(a)for(const v of d)v&&(v._validate(),!this.normals&&v.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&v.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&v.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&v.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&v.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&v.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&v.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&v.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&v.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&v.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&v.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&v.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&v.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const v of d)if(v){if(a)this.normals&&!v.normals&&(v.normals=new Float32Array(v.positions.length)),this.tangents&&!v.tangents&&(v.tangents=new Float32Array(v.positions.length/3*4)),this.uvs&&!v.uvs&&(v.uvs=new Float32Array(v.positions.length/3*2)),this.uvs2&&!v.uvs2&&(v.uvs2=new Float32Array(v.positions.length/3*2)),this.uvs3&&!v.uvs3&&(v.uvs3=new Float32Array(v.positions.length/3*2)),this.uvs4&&!v.uvs4&&(v.uvs4=new Float32Array(v.positions.length/3*2)),this.uvs5&&!v.uvs5&&(v.uvs5=new Float32Array(v.positions.length/3*2)),this.uvs6&&!v.uvs6&&(v.uvs6=new Float32Array(v.positions.length/3*2)),this.colors&&!v.colors&&(v.colors=new Float32Array(v.positions.length/3*4),v.colors.fill(1)),this.matricesIndices&&!v.matricesIndices&&(v.matricesIndices=new Float32Array(v.positions.length/3*4)),this.matricesWeights&&!v.matricesWeights&&(v.matricesWeights=new Float32Array(v.positions.length/3*4)),this.matricesIndicesExtra&&!v.matricesIndicesExtra&&(v.matricesIndicesExtra=new Float32Array(v.positions.length/3*4)),this.matricesWeightsExtra&&!v.matricesWeightsExtra&&(v.matricesWeightsExtra=new Float32Array(v.positions.length/3*4));else if(v._validate(),!this.normals!=!v.normals||!this.tangents!=!v.tangents||!this.uvs!=!v.uvs||!this.uvs2!=!v.uvs2||!this.uvs3!=!v.uvs3||!this.uvs4!=!v.uvs4||!this.uvs5!=!v.uvs5||!this.uvs6!=!v.uvs6||!this.colors!=!v.colors||!this.matricesIndices!=!v.matricesIndices||!this.matricesWeights!=!v.matricesWeights||!this.matricesIndicesExtra!=!v.matricesIndicesExtra||!this.matricesWeightsExtra!=!v.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let v=0,E=0,C=0;const S=[];let b=null;const R=[];for(const N of this.splitBasedOnMaterialID())R.push({vertexData:N,transform:e});for(const N of t)if(N.vertexData)for(const O of N.vertexData.splitBasedOnMaterialID())R.push({vertexData:O,transform:N.transform});R.sort((N,O)=>{const L=N.vertexData.materialInfos?N.vertexData.materialInfos[0].materialIndex:0,B=O.vertexData.materialInfos?O.vertexData.materialInfos[0].materialIndex:0;return L>B?1:L===B?0:-1});for(const N of R){const O=N.vertexData;if(O.materialInfos?v=O.materialInfos[0].materialIndex:v=0,b&&b.materialIndex===v)b.indexCount+=O.indices.length,b.verticesCount+=O.positions.length/3;else{const L=new g_;L.materialIndex=v,L.indexStart=E,L.indexCount=O.indices.length,L.verticesStart=C,L.verticesCount=O.positions.length/3,S.push(L),b=L}E+=O.indices.length,C+=O.positions.length/3}const I=R.splice(0,1)[0];f=I.vertexData,e=I.transform,d=R.map(N=>N.vertexData),t=R,this.materialInfos=S}const p=d.reduce((v,E)=>{var C,S;return v+((S=(C=E.indices)===null||C===void 0?void 0:C.length)!==null&&S!==void 0?S:0)},(h=(l=f.indices)===null||l===void 0?void 0:l.length)!==null&&h!==void 0?h:0);let g=r||d.some(v=>v.indices===f.indices)?(c=f.indices)===null||c===void 0?void 0:c.slice():f.indices;if(p>0){let v=(u=g==null?void 0:g.length)!==null&&u!==void 0?u:0;if(g||(g=new Array(p)),g.length!==p){if(Array.isArray(g))g.length=p;else{const C=i||g instanceof Uint32Array?new Uint32Array(p):new Uint16Array(p);C.set(g),g=C}e&&e.determinant()<0&&De._FlipFaces(g,0,v)}let E=f.positions?f.positions.length/3:0;for(const{vertexData:C,transform:S}of t)if(C.indices){for(let b=0;b[v.vertexData.positions,v.transform])),s&&(yield),f.normals&&(this.normals=De._MergeElement(P.NormalKind,f.normals,e,t.map(v=>[v.vertexData.normals,v.transform])),s&&(yield)),f.tangents&&(this.tangents=De._MergeElement(P.TangentKind,f.tangents,e,t.map(v=>[v.vertexData.tangents,v.transform])),s&&(yield)),f.uvs&&(this.uvs=De._MergeElement(P.UVKind,f.uvs,e,t.map(v=>[v.vertexData.uvs,v.transform])),s&&(yield)),f.uvs2&&(this.uvs2=De._MergeElement(P.UV2Kind,f.uvs2,e,t.map(v=>[v.vertexData.uvs2,v.transform])),s&&(yield)),f.uvs3&&(this.uvs3=De._MergeElement(P.UV3Kind,f.uvs3,e,t.map(v=>[v.vertexData.uvs3,v.transform])),s&&(yield)),f.uvs4&&(this.uvs4=De._MergeElement(P.UV4Kind,f.uvs4,e,t.map(v=>[v.vertexData.uvs4,v.transform])),s&&(yield)),f.uvs5&&(this.uvs5=De._MergeElement(P.UV5Kind,f.uvs5,e,t.map(v=>[v.vertexData.uvs5,v.transform])),s&&(yield)),f.uvs6&&(this.uvs6=De._MergeElement(P.UV6Kind,f.uvs6,e,t.map(v=>[v.vertexData.uvs6,v.transform])),s&&(yield)),f.colors&&(this.colors=De._MergeElement(P.ColorKind,f.colors,e,t.map(v=>[v.vertexData.colors,v.transform])),s&&(yield)),f.matricesIndices&&(this.matricesIndices=De._MergeElement(P.MatricesIndicesKind,f.matricesIndices,e,t.map(v=>[v.vertexData.matricesIndices,v.transform])),s&&(yield)),f.matricesWeights&&(this.matricesWeights=De._MergeElement(P.MatricesWeightsKind,f.matricesWeights,e,t.map(v=>[v.vertexData.matricesWeights,v.transform])),s&&(yield)),f.matricesIndicesExtra&&(this.matricesIndicesExtra=De._MergeElement(P.MatricesIndicesExtraKind,f.matricesIndicesExtra,e,t.map(v=>[v.vertexData.matricesIndicesExtra,v.transform])),s&&(yield)),f.matricesWeightsExtra&&(this.matricesWeightsExtra=De._MergeElement(P.MatricesWeightsExtraKind,f.matricesWeightsExtra,e,t.map(v=>[v.vertexData.matricesWeightsExtra,v.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),a=e===P.PositionKind?De._TransformVector3Coordinates:e===P.NormalKind?De._TransformVector3Normals:e===P.TangentKind?De._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(n);l.set(t),i&&a(l,i,0,t.length);let h=t.length;for(const[c,u]of r)l.set(c,h),u&&a(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(n);for(let c=0;c{const n=P.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(P.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(P.NormalKind,this.normals),this.tangents&&i(P.TangentKind,this.tangents),this.uvs&&i(P.UVKind,this.uvs),this.uvs2&&i(P.UV2Kind,this.uvs2),this.uvs3&&i(P.UV3Kind,this.uvs3),this.uvs4&&i(P.UV4Kind,this.uvs4),this.uvs5&&i(P.UV5Kind,this.uvs5),this.uvs6&&i(P.UV6Kind,this.uvs6),this.colors&&i(P.ColorKind,this.colors),this.matricesIndices&&i(P.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(P.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(P.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(P.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return De.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)),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 De._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return De._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new De;return e.isVerticesDataPresent(P.PositionKind)&&(s.positions=e.getVerticesData(P.PositionKind,t,i)),e.isVerticesDataPresent(P.NormalKind)&&(s.normals=e.getVerticesData(P.NormalKind,t,i)),e.isVerticesDataPresent(P.TangentKind)&&(s.tangents=e.getVerticesData(P.TangentKind,t,i)),e.isVerticesDataPresent(P.UVKind)&&(s.uvs=e.getVerticesData(P.UVKind,t,i)),e.isVerticesDataPresent(P.UV2Kind)&&(s.uvs2=e.getVerticesData(P.UV2Kind,t,i)),e.isVerticesDataPresent(P.UV3Kind)&&(s.uvs3=e.getVerticesData(P.UV3Kind,t,i)),e.isVerticesDataPresent(P.UV4Kind)&&(s.uvs4=e.getVerticesData(P.UV4Kind,t,i)),e.isVerticesDataPresent(P.UV5Kind)&&(s.uvs5=e.getVerticesData(P.UV5Kind,t,i)),e.isVerticesDataPresent(P.UV6Kind)&&(s.uvs6=e.getVerticesData(P.UV6Kind,t,i)),e.isVerticesDataPresent(P.ColorKind)&&(s.colors=e.getVerticesData(P.ColorKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(P.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(P.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(P.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(P.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw xt("ribbonBuilder")}static CreateBox(e){throw xt("boxBuilder")}static CreateTiledBox(e){throw xt("tiledBoxBuilder")}static CreateTiledPlane(e){throw xt("tiledPlaneBuilder")}static CreateSphere(e){throw xt("sphereBuilder")}static CreateCylinder(e){throw xt("cylinderBuilder")}static CreateTorus(e){throw xt("torusBuilder")}static CreateLineSystem(e){throw xt("linesBuilder")}static CreateDashedLines(e){throw xt("linesBuilder")}static CreateGround(e){throw xt("groundBuilder")}static CreateTiledGround(e){throw xt("groundBuilder")}static CreateGroundFromHeightMap(e){throw xt("groundBuilder")}static CreatePlane(e){throw xt("planeBuilder")}static CreateDisc(e){throw xt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,a){throw xt("polygonBuilder")}static CreateIcoSphere(e){throw xt("icoSphereBuilder")}static CreatePolyhedron(e){throw xt("polyhedronBuilder")}static CreateCapsule(e={orientation:T.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw xt("capsuleBuilder")}static CreateTorusKnot(e){throw xt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,a=0,l=0,h=0,c=0,u=0,d=0,f=0,p=0,_=0,g=0,v=0,E=0,C=0,S=0,b=0,R=0,I=0,N=0,O=!1,L=!1,B=!1,V=!1,Z=1,ue=0,oe=null;s&&(O=!!s.facetNormals,L=!!s.facetPositions,B=!!s.facetPartitioning,Z=s.useRightHandedSystem===!0?-1:1,ue=s.ratio||0,V=!!s.depthSort,oe=s.distanceTo,V&&oe===void 0&&(oe=T.Zero()));let me=0,le=0,ae=0,ce=0;for(B&&s&&s.bbSize&&(me=s.subDiv.X*ue/s.bbSize.x,le=s.subDiv.Y*ue/s.bbSize.y,ae=s.subDiv.Z*ue/s.bbSize.z,ce=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(o))],De,"_TransformVector3Coordinates",null);A([hh.filter((...[o])=>!Array.isArray(o))],De,"_TransformVector3Normals",null);A([hh.filter((...[o])=>!Array.isArray(o))],De,"_TransformVector4Normals",null);A([hh.filter((...[o])=>!Array.isArray(o))],De,"_FlipFaces",null);class nr{static get ForceFullSceneLoadingForIncremental(){return nr._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nr._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nr._ShowLoadingScreen}static set ShowLoadingScreen(e){nr._ShowLoadingScreen=e}static get loggingLevel(){return nr._LoggingLevel}static set loggingLevel(e){nr._LoggingLevel=e}static get CleanBoneMatrixWeights(){return nr._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nr._CleanBoneMatrixWeights=e}}nr._ForceFullSceneLoadingForIncremental=!1;nr._ShowLoadingScreen=!0;nr._CleanBoneMatrixWeights=!1;nr._LoggingLevel=0;class pi{}pi.UseOpenGLOrientationForUV=!1;class sn{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 sn(sn.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||ht.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;e65535);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)),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(P.PositionKind),!e))return;this._extend=Ad(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===P.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let n=0;n0){for(let s=0;s0){for(let s=0;s0){for(let s=0;s-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new De;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const a=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(P.PositionKind,a,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const a=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(P.NormalKind,a,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const a=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(P.TangentKind,a,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const a=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(P.ColorKind,a,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesKind,l,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,l,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const a=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(P.MatricesWeightsKind,a,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const a=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(a,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const a=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(P.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let a=0;a>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(sn._CleanMatricesWeights(e,t),t.setVerticesData(P.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(P.MatricesIndicesKind),n=t.getVerticesData(P.MatricesIndicesExtraKind),a=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=a.length;for(let u=0;uh-1)&&(f=h-1),d>.001){const p=1/d;for(let _=0;_<4;_++)a[u+_]*=p;if(l)for(let _=0;_<4;_++)l[u+_]*=p}else f>=4?(l[u+f-4]=1-d,n[u+f-4]=s):(a[u+f]=1-d,r[u+f]=s)}t.setVerticesData(P.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new sn(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ui&&ui.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new ha(T.FromArray(e.boundingBoxMinimum),T.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(P.UVKind),e.hasUVs2&&s._delayInfo.push(P.UV2Kind),e.hasUVs3&&s._delayInfo.push(P.UV3Kind),e.hasUVs4&&s._delayInfo.push(P.UV4Kind),e.hasUVs5&&s._delayInfo.push(P.UV5Kind),e.hasUVs6&&s._delayInfo.push(P.UV6Kind),e.hasColors&&s._delayInfo.push(P.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(P.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(P.MatricesWeightsKind),s._delayLoadingFunction=De.ImportVertexData):De.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Ww{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Hw(e)}sampleFrame(e=ar.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 Hw{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}}We.prototype.setAlphaConstants=function(o,e,t,i){this._alphaState.setAlphaBlendConstants(o,e,t,i)};We.prototype.setAlphaMode=function(o,e=!1){if(this._alphaMode===o){if(!e){const t=o===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(o){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=o===0),this._alphaMode=o};We.prototype.getAlphaMode=function(){return this._alphaMode};We.prototype.setAlphaEquation=function(o){if(this._alphaEquation!==o){switch(o){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=o}};We.prototype.getAlphaEquation=function(){return this._alphaEquation};function Fv(o,e,t=!1,i){switch(o){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}We.prototype._readTexturePixelsSync=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,l=0,h=0){var c,u;const d=this._gl;if(!d)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const p=d.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),i>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+i,(c=o._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,(u=o._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,s);let f=o.type!==void 0?this._getWebGLTextureType(o.type):d.UNSIGNED_BYTE;if(a)r||(r=Fv(o.type,4*e*t));else switch(f){case d.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),f=d.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),f=d.FLOAT;break}return n&&this.flushFramebuffer(),d.readPixels(l,h,e,t,d.RGBA,f,r),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),r};We.prototype._readTexturePixels=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(o,e,t,i,s,r,n,a,l,h))};We.prototype.updateDynamicIndexBuffer=function(o,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(o);let i;o.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()};We.prototype.updateDynamicVertexBuffer=function(o,e,t,i){this.bindArrayBuffer(o),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 re extends We{static get NpmPackage(){return We.NpmPackage}static get Version(){return We.Version}static get Instances(){return ht.Instances}static get LastCreatedEngine(){return ht.LastCreatedEngine}static get LastCreatedScene(){return ht.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{this.createImageBitmap(n,t).then(a=>{s(a)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const r=this.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{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(),!re.audioEngine&&this._creationOptions.audioEngine&&re.AudioEngineFactory&&(re.audioEngine=re.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Zu()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&re._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=re.OfflineProviderFactory!==void 0,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;(e=this._onPointerLockChange)===null||e===void 0||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((s,r)=>{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,a)=>{r(a)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){var s;let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s=r==null?void 0:r.texture)!==null&&s!==void 0?s:null,i)}setTextureFromPostProcessOutput(e,t,i){var s,r;this._bindTexture(e,(r=(s=t==null?void 0:t._outputTexture)===null||s===void 0?void 0:s.texture)!==null&&r!==void 0?r:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&re._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&re._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&re._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){re._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;s1&&r){const a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=a}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(i=>{i._outputTexture===e&&(i._outputTexture=null)}),t.cameras.forEach(i=>{i._postProcesses.forEach(s=>{s&&s._outputTexture===e&&(s._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++re._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new uu(e,this._gl),a=new Ti(this,Vt.Unknown,!0);return a._hardwareTexture=n,a.baseWidth=s,a.baseHeight=r,a.width=s,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,s,l,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){G.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 Cd(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise((r,n)=>{const a=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){n();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(a,i);return}r()};a()})}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,a.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,a),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();ht.Instances.length===1&&re.audioEngine&&(re.audioEngine.dispose(),re.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)),Zu()&&(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=ht.Instances.indexOf(this);t>=0&&ht.Instances.splice(t,1),re.Instances.length||ht.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(!gr())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!gr())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=re.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}}}re.ALPHA_DISABLE=0;re.ALPHA_ADD=1;re.ALPHA_COMBINE=2;re.ALPHA_SUBTRACT=3;re.ALPHA_MULTIPLY=4;re.ALPHA_MAXIMIZED=5;re.ALPHA_ONEONE=6;re.ALPHA_PREMULTIPLIED=7;re.ALPHA_PREMULTIPLIED_PORTERDUFF=8;re.ALPHA_INTERPOLATE=9;re.ALPHA_SCREENMODE=10;re.DELAYLOADSTATE_NONE=0;re.DELAYLOADSTATE_LOADED=1;re.DELAYLOADSTATE_LOADING=2;re.DELAYLOADSTATE_NOTLOADED=4;re.NEVER=512;re.ALWAYS=519;re.LESS=513;re.EQUAL=514;re.LEQUAL=515;re.GREATER=516;re.GEQUAL=518;re.NOTEQUAL=517;re.KEEP=7680;re.REPLACE=7681;re.INCR=7682;re.DECR=7683;re.INVERT=5386;re.INCR_WRAP=34055;re.DECR_WRAP=34056;re.TEXTURE_CLAMP_ADDRESSMODE=0;re.TEXTURE_WRAP_ADDRESSMODE=1;re.TEXTURE_MIRROR_ADDRESSMODE=2;re.TEXTUREFORMAT_ALPHA=0;re.TEXTUREFORMAT_LUMINANCE=1;re.TEXTUREFORMAT_LUMINANCE_ALPHA=2;re.TEXTUREFORMAT_RGB=4;re.TEXTUREFORMAT_RGBA=5;re.TEXTUREFORMAT_RED=6;re.TEXTUREFORMAT_R=6;re.TEXTUREFORMAT_RG=7;re.TEXTUREFORMAT_RED_INTEGER=8;re.TEXTUREFORMAT_R_INTEGER=8;re.TEXTUREFORMAT_RG_INTEGER=9;re.TEXTUREFORMAT_RGB_INTEGER=10;re.TEXTUREFORMAT_RGBA_INTEGER=11;re.TEXTURETYPE_UNSIGNED_BYTE=0;re.TEXTURETYPE_UNSIGNED_INT=0;re.TEXTURETYPE_FLOAT=1;re.TEXTURETYPE_HALF_FLOAT=2;re.TEXTURETYPE_BYTE=3;re.TEXTURETYPE_SHORT=4;re.TEXTURETYPE_UNSIGNED_SHORT=5;re.TEXTURETYPE_INT=6;re.TEXTURETYPE_UNSIGNED_INTEGER=7;re.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;re.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;re.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;re.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;re.TEXTURETYPE_UNSIGNED_INT_24_8=12;re.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;re.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;re.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;re.TEXTURE_NEAREST_SAMPLINGMODE=1;re.TEXTURE_BILINEAR_SAMPLINGMODE=2;re.TEXTURE_TRILINEAR_SAMPLINGMODE=3;re.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;re.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;re.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;re.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;re.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;re.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;re.TEXTURE_NEAREST_LINEAR=7;re.TEXTURE_NEAREST_NEAREST=1;re.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;re.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;re.TEXTURE_LINEAR_LINEAR=2;re.TEXTURE_LINEAR_NEAREST=12;re.TEXTURE_EXPLICIT_MODE=0;re.TEXTURE_SPHERICAL_MODE=1;re.TEXTURE_PLANAR_MODE=2;re.TEXTURE_CUBIC_MODE=3;re.TEXTURE_PROJECTION_MODE=4;re.TEXTURE_SKYBOX_MODE=5;re.TEXTURE_INVCUBIC_MODE=6;re.TEXTURE_EQUIRECTANGULAR_MODE=7;re.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;re.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;re.SCALEMODE_FLOOR=1;re.SCALEMODE_NEAREST=2;re.SCALEMODE_CEILING=3;re._RescalePostProcessFactory=null;re._RenderPassIdCounter=0;const Xw=k.Compose(T.One(),Se.FromEulerAngles(0,Math.PI,0),T.Zero());class It extends Mi{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&It.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!==It.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 T(0,0,1),this._up=new T(0,1,0),this._right=new T(1,0,0),this._position=T.Zero(),this._rotation=T.Zero(),this._rotationQuaternion=null,this._scaling=T.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=It.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=k.Zero(),this._usePivotMatrix=!1,this._absolutePosition=T.Zero(),this._absoluteScaling=T.Zero(),this._absoluteRotationQuaternion=Se.Identity(),this._pivotMatrix=k.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new he,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 T.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return T.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return T.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=k.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==It.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=k.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||Se.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=K.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),T.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=T.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=K.Matrix[0];return this._localMatrix.invertToRef(e),T.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=T.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=_i.LOCAL){const n=It._LookAtVectorCache,a=r===_i.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===_i.WORLD&&this.parent)if(this.rotationQuaternion){const l=K.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=K.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=K.Quaternion[0];Se.FromEulerVectorToRef(this.rotation,l);const h=K.Matrix[0];l.toRotationMatrix(h);const c=K.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=T.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return T.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?Se.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=_i.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==_i.WORLD){const s=K.Matrix[0];i.invertToRef(s),e=T.TransformCoordinates(e,s)}return this.setPivotMatrix(k.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=T.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=T.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),T.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=K.Quaternion[0],r=K.Vector3[0],n=K.Vector3[1],a=K.Matrix[1];k.IdentityToRef(a);const l=K.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=It._TmpRotation,Se.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),k.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(a),l.multiplyToRef(a,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(k.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===_i.LOCAL)s=Se.RotationAxisToRef(e,t,It._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=this.parent.getWorldMatrix(),n=K.Matrix[0];r.invertToRef(n),e=T.TransformNormal(e,n),r.determinant()<0&&(t*=-1)}s=Se.RotationAxisToRef(e,t,It._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Se.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=K.Vector3[0],r=K.Vector3[1],n=K.Vector3[2],a=K.Quaternion[0],l=K.Matrix[0],h=K.Matrix[1],c=K.Matrix[2],u=K.Matrix[3];return e.subtractToRef(this.position,s),k.TranslationToRef(s.x,s.y,s.z,l),k.TranslationToRef(-s.x,-s.y,-s.z,h),k.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===_i.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=K.Quaternion[1],Se.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=K.Quaternion[0];return Se.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!==It.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=It._TmpScaling;let a=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new T(h.m[12],h.m[13],h.m[14]);a=It._TmpTranslation,a.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Se.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=It._TmpRotation,Se.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=K.Matrix[1];k.ScalingToRef(n.x,n.y,n.z,h);const c=K.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,K.Matrix[4]),K.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else k.ComposeToRef(n,l,a,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(),K.Matrix[7])}else K.Matrix[7].copyFrom(r.getWorldMatrix());const h=K.Vector3[5],c=K.Vector3[6],u=K.Quaternion[0];K.Matrix[7].decompose(c,u,h),k.ScalingToRef(c.x,c.y,c.z,K.Matrix[7]),K.Matrix[7].setTranslation(h),It.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(K.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const h=this.parent;h.getSkeleton().prepare(),this._localMatrix.multiplyToRef(h.getFinalMatrix(),K.Matrix[6]),K.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=K.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),K.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&K.Matrix[1].multiplyToRef(Xw,K.Matrix[1]),K.Matrix[1].setTranslationFromFloats(0,0,0),K.Matrix[1].invertToRef(K.Matrix[0]),(this.billboardMode&It.BILLBOARDMODE_ALL)!==It.BILLBOARDMODE_ALL){K.Matrix[0].decompose(void 0,K.Quaternion[0],void 0);const c=K.Vector3[1];K.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&It.BILLBOARDMODE_X)!==It.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&It.BILLBOARDMODE_Y)!==It.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&It.BILLBOARDMODE_Z)!==It.BILLBOARDMODE_Z&&(c.z=0),k.RotationYawPitchRollToRef(c.y,c.x,c.z,K.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(K.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(K.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=K.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(K.Matrix[1]);const u=K.Vector3[1];T.TransformCoordinatesToRef(c,K.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),p=-Math.atan2(u.y,f);if(Se.RotationYawPitchRollToRef(d,p,0,K.Quaternion[0]),(this.billboardMode&It.BILLBOARDMODE_ALL)!==It.BILLBOARDMODE_ALL){const _=K.Vector3[1];K.Quaternion[0].toEulerAnglesToRef(_),(this.billboardMode&It.BILLBOARDMODE_X)!==It.BILLBOARDMODE_X&&(_.x=0),(this.billboardMode&It.BILLBOARDMODE_Y)!==It.BILLBOARDMODE_Y&&(_.y=0),(this.billboardMode&It.BILLBOARDMODE_Z)!==It.BILLBOARDMODE_Z&&(_.z=0),k.RotationYawPitchRollToRef(_.y,_.x,_.z,K.Matrix[0])}else k.FromQuaternionToRef(K.Quaternion[0],K.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(K.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(K.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=k.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew It(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;nnew It(e.name,t),e,t,i);return e.localMatrix?s.setPreTransformMatrix(k.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(k.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof It),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),l=Math.max(a.x,a.y,a.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)}}It.BILLBOARDMODE_NONE=0;It.BILLBOARDMODE_X=1;It.BILLBOARDMODE_Y=2;It.BILLBOARDMODE_Z=4;It.BILLBOARDMODE_ALL=7;It.BILLBOARDMODE_USE_POSITION=128;It.BillboardUseParentOrientation=!1;It._TmpRotation=Se.Zero();It._TmpScaling=T.Zero();It._TmpTranslation=T.Zero();It._LookAtVectorCache=new T(0,0,0);It._RotationAxisCache=new Se;A([kr("position")],It.prototype,"_position",void 0);A([kr("rotation")],It.prototype,"_rotation",void 0);A([ew("rotationQuaternion")],It.prototype,"_rotationQuaternion",void 0);A([kr("scaling")],It.prototype,"_scaling",void 0);A([D("billboardMode")],It.prototype,"_billboardMode",void 0);A([D()],It.prototype,"scalingDeterminant",void 0);A([D("infiniteDistance")],It.prototype,"_infiniteDistance",void 0);A([D()],It.prototype,"ignoreNonUniformScaling",void 0);A([D()],It.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Yw{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new T(0,0,0),this._diffPositionForCollisions=new T(0,0,0),this._collisionResponse=!0}}class $w{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=T.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Kw{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new $w,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 Yw,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class hi extends It{static get BILLBOARDMODE_NONE(){return It.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return It.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return It.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return It.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return It.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return It.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)===null||t===void 0?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Kw,this._waitingMaterialId=null,this.cullingStrategy=hi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new he,this.onCollisionPositionChangeObservable=new he,this.onMaterialChangedObservable=new he,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=Te.Red(),this.outlineWidth=.02,this.overlayColor=Te.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 T(.5,1,.5),this.ellipsoidOffset=new T(0,0,0),this.edgesWidth=1,this.edgesColor=new Ze(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 he,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>re.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 it(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Xo.Aggressive:this.doNotSyncBoundingInfo=!0;case Xo.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!==It.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes)for(const t of this.subMeshes)t._rebuild()}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!==null&&e!==void 0?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new ha(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(P.MatricesIndicesKind)&&this.isVerticesDataPresent(P.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===It.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 k;(this.rotationQuaternion?this.rotationQuaternion:Se.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=T.Zero(),a=this.definedFacingForward?-1:1;return T.TransformCoordinatesFromFloatsToRef(e*a,t,i*a,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new T(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=Ad(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ha(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i4,l=a?this.getVerticesData(P.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(P.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=K.Vector3[0],d=K.Matrix[0],f=K.Matrix[1];let p=0;for(let _=0;_0&&(k.FromFloat32ArrayToRefScaled(c,Math.floor(r[p+g]*16),v,f),d.addToSelf(f));if(a)for(g=0;g<4;g++)v=h[p+g],v>0&&(k.FromFloat32ArrayToRefScaled(c,Math.floor(l[p+g]*16),v,f),d.addToSelf(f));s===P.NormalKind?T.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],d,u):T.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],d,u),u.toArray(i,_),s===P.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,P.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,P.PositionKind)}_getPositionData(e,t){var i;let s=this.getVerticesData(P.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),s&&(e&&this.skeleton||t&&this.morphTargetManager)){if(s=s.slice(),this._generatePointsArray(),this._positions){const r=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(r.length);for(let n=0;n1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var s;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const r=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let a=r;a1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=K.Matrix[0],i=K.Matrix[1];return k.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const a=new Vr,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 a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:T.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let p=!1;for(let _=0;_1&&!n&&!g.canIntersects(e))continue;const v=g.intersects(e,this._positions,this.getIndices(),t,i);if(v&&(t||!u||v.distancea!==this&&a.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let l=a.includedOnlyMeshes.indexOf(this);l!==-1&&a.includedOnlyMeshes.splice(l,1),l=a.excludedMeshes.indexOf(this),l!==-1&&a.excludedMeshes.splice(l,1);const h=a.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 a=this._parentContainer.meshes.indexOf(this);a>-1&&this._parentContainer.meshes.splice(a,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){a=!0;break}a?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(a,l){return l.sqDistance-a.sqDistance},!e.facetDepthSortFrom){const a=this.getScene().activeCamera;e.facetDepthSortFrom=a?a.position:T.Zero()}e.depthSortedFacets=[];for(let a=0;a$t?r.maximum.x-r.minimum.x:$t,e.bbSize.y=r.maximum.y-r.minimum.y>$t?r.maximum.y-r.minimum.y:$t,e.bbSize.z=r.maximum.z-r.minimum.z>$t?r.maximum.z-r.minimum.z:$t;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),T.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&De.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const a=e.depthSortedIndices.length/3|0;for(let l=0;lr.subDiv.max||a<0||a>r.subDiv.max||l<0||l>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),l=K.Matrix[5];a.invertToRef(l);const h=K.Vector3[8];T.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&T.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,l=0,h=0,c=0,u=0,d=0,f=0,p=0,_=0;const g=this.getFacetLocalPositions(),v=this.getFacetLocalNormals(),E=this.getFacetsAtLocalCoordinates(e,t,i);if(!E)return null;let C=Number.MAX_VALUE,S=C,b,R,I;for(let N=0;N=0||r&&!n&&u<=0)&&(u=R.x*I.x+R.y*I.y+R.z*I.z,d=-(R.x*e+R.y*t+R.z*i-u)/(R.x*R.x+R.y*R.y+R.z*R.z),f=e+R.x*d,p=t+R.y*d,_=i+R.z*d,l=f-e,h=p-t,c=_-i,S=l*l+h*h+c*c,Se.emitter===this)}}hi.OCCLUSION_TYPE_NONE=0;hi.OCCLUSION_TYPE_OPTIMISTIC=1;hi.OCCLUSION_TYPE_STRICT=2;hi.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;hi.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;hi.CULLINGSTRATEGY_STANDARD=0;hi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;hi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;hi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;j("BABYLON.AbstractMesh",hi);function Ao(o){o.indexOf("vClipPlane")===-1&&o.push("vClipPlane"),o.indexOf("vClipPlane2")===-1&&o.push("vClipPlane2"),o.indexOf("vClipPlane3")===-1&&o.push("vClipPlane3"),o.indexOf("vClipPlane4")===-1&&o.push("vClipPlane4"),o.indexOf("vClipPlane5")===-1&&o.push("vClipPlane5"),o.indexOf("vClipPlane6")===-1&&o.push("vClipPlane6")}function vh(o,e,t){var i,s,r,n,a,l;const h=!!((i=o.clipPlane)!==null&&i!==void 0?i:e.clipPlane),c=!!((s=o.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),u=!!((r=o.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),d=!!((n=o.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),f=!!((a=o.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),p=!!((l=o.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);h&&t.push("#define CLIPPLANE"),c&&t.push("#define CLIPPLANE2"),u&&t.push("#define CLIPPLANE3"),d&&t.push("#define CLIPPLANE4"),f&&t.push("#define CLIPPLANE5"),p&&t.push("#define CLIPPLANE6")}function qw(o,e,t){var i,s,r,n,a,l;let h=!1;const c=!!((i=o.clipPlane)!==null&&i!==void 0?i:e.clipPlane),u=!!((s=o.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),d=!!((r=o.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),f=!!((n=o.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),p=!!((a=o.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),_=!!((l=o.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);return t.CLIPPLANE!==c&&(t.CLIPPLANE=c,h=!0),t.CLIPPLANE2!==u&&(t.CLIPPLANE2=u,h=!0),t.CLIPPLANE3!==d&&(t.CLIPPLANE3=d,h=!0),t.CLIPPLANE4!==f&&(t.CLIPPLANE4=f,h=!0),t.CLIPPLANE5!==p&&(t.CLIPPLANE5=p,h=!0),t.CLIPPLANE6!==_&&(t.CLIPPLANE6=_,h=!0),h}function so(o,e,t){var i,s,r,n,a,l;let h=(i=e.clipPlane)!==null&&i!==void 0?i:t.clipPlane;Cc(o,"vClipPlane",h),h=(s=e.clipPlane2)!==null&&s!==void 0?s:t.clipPlane2,Cc(o,"vClipPlane2",h),h=(r=e.clipPlane3)!==null&&r!==void 0?r:t.clipPlane3,Cc(o,"vClipPlane3",h),h=(n=e.clipPlane4)!==null&&n!==void 0?n:t.clipPlane4,Cc(o,"vClipPlane4",h),h=(a=e.clipPlane5)!==null&&a!==void 0?a:t.clipPlane5,Cc(o,"vClipPlane5",h),h=(l=e.clipPlane6)!==null&&l!==void 0?l:t.clipPlane6,Cc(o,"vClipPlane6",h)}function Cc(o,e,t){t&&o.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}class Me{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==Qe.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,s,r,n,a,l=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=r&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=l)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===et.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===et.PERSPECTIVE_CAMERA?1:0;(s^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=n===1,t.CAMERA_PERSPECTIVE=a===1,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,s,r,n=null,a=!1){let l=Me.PrepareDefinesForCamera(e,s);n!==!1&&(l=qw(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,l=!0),s.INSTANCES!==r&&(s.INSTANCES=r,l=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,l=!0),l&&s.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=t.BONETEXTURE!==void 0;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=i?!1:void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const r=s.excludedSkinnedMesh.indexOf(e)===-1;t.BONES_VELOCITY_ENABLED=r}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE!==void 0&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!(i&&i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,s,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(P.NormalKind),t._needNormals&&e.isVerticesDataPresent(P.TangentKind)&&(t.TANGENT=!0);for(let l=1;l<=6;++l)t["UV"+l]=t._needUVs?e.isVerticesDataPresent(`uv${l===1?"":l}`):!1;if(i){const l=e.useVertexColors&&e.isVerticesDataPresent(P.ColorKind);t.VERTEXCOLOR=l,t.VERTEXALPHA=e.hasVertexAlpha&&l&&n}return e.isVerticesDataPresent(P.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=e.activeCamera.outputRenderTarget!==null&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(s!==t.ORDER_INDEPENDENT_TRANSPARENCY||r!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let n=0;n0&&(a.shadowEnabled=!0,h.prepareDefines(r,s))}}i.lightmapMode!=Bi.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Bi.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}static PrepareDefinesForLights(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const l={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(const c of t.lightSources)if(this.PrepareDefinesForLight(e,t,c,a,i,s,l),a++,a===r)break}i.SPECULARTERM=l.specularEnabled,i.SHADOWS=l.shadowEnabled;for(let c=a;c0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&ht.LastCreatedEngine){const r=ht.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&i.NORMAL,l=n&&n.supportsTangents&&i.TANGENT,h=n&&n.supportsUVs&&i.UV1;for(let c=0;cr&&G.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push(P.MatricesIndicesKind),e.push(P.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(P.MatricesIndicesExtraKind),e.push(P.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(P.ColorInstanceKind)}static PushAttributesForInstances(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}static BindLights(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let a=0;a-1){const r=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",r),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const r=s.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),Me._CopyBonesTransformationMatrices(r,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;!e||!i||t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const s=i.activeCamera;s.mode===et.ORTHOGRAPHIC_CAMERA&&G.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}}}Me._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0};Me._TempFogColor=Te.Black();class Nl{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){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([D()],Nl.prototype,"func",null);A([D()],Nl.prototype,"funcRef",null);A([D()],Nl.prototype,"funcMask",null);A([D()],Nl.prototype,"opStencilFail",null);A([D()],Nl.prototype,"opDepthFail",null);A([D()],Nl.prototype,"opStencilDepthPass",null);A([D()],Nl.prototype,"mask",null);A([D()],Nl.prototype,"enabled",null);var Lr;(function(o){o[o.Created=1]="Created",o[o.Disposed=2]="Disposed",o[o.GetDefineNames=4]="GetDefineNames",o[o.PrepareUniformBuffer=8]="PrepareUniformBuffer",o[o.IsReadyForSubMesh=16]="IsReadyForSubMesh",o[o.PrepareDefines=32]="PrepareDefines",o[o.BindForSubMesh=64]="BindForSubMesh",o[o.PrepareEffect=128]="PrepareEffect",o[o.GetAnimatables=256]="GetAnimatables",o[o.GetActiveTextures=512]="GetActiveTextures",o[o.HasTexture=1024]="HasTexture",o[o.FillRenderTargetTextures=2048]="FillRenderTargetTextures",o[o.HasRenderTargetTextures=4096]="HasRenderTargetTextures",o[o.HardBindForSubMesh=8192]="HardBindForSubMesh"})(Lr||(Lr={}));class Ie{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(Ie.MiscDirtyFlag+Ie.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Ie.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Ie.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 he),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 he),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new he),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Ie.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(Ie.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Ie.WireFrameFillMode:case Ie.LineListDrawMode:case Ie.LineLoopDrawMode:case Ie.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Ie.WireFrameFillMode:Ie.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Ie.PointFillMode:case Ie.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Ie.PointFillMode:Ie.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Ie.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&G.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 he,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 Nl,this._useUBO=!1,this._fillMode=Ie.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||ht.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||fe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Or(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Ie.ClockWiseSideOrientation:this.sideOrientation=Ie.CounterClockWiseSideOrientation,this._uniformBuffer=new it(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ie.OnEventObservable.notifyObservers(this,Lr.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===Ie.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ie.MATERIAL_OPAQUE||this._transparencyMode===Ie.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const s of i.subMeshes)s.getMaterial()===this&&s.effect&&(s.effect._wasPreviouslyReady=!1,s.effect._wasPreviouslyUsingInstances=null,s.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(Ie.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===Ie.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(Lr.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i.effect;s&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Me.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}if(this.disableColorWrite){const i=this._scene.getEngine();this._cachedColorWriteState=i.getColorWrite(),i.setColorWrite(!1)}if(this.depthFunction!==0){const i=this._scene.getEngine();this._cachedDepthFunctionState=i.getDepthFunction()||0,i.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Lr.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Lr.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Lr.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ie._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const r=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new An(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const d=new on(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=a,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,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||(Ie._DirtyCallbackArray.length=0,e&Ie.TextureDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._TextureDirtyCallBack),e&Ie.LightDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._LightsDirtyCallBack),e&Ie.FresnelDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._FresnelDirtyCallBack),e&Ie.AttributesDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._AttributeDirtyCallBack),e&Ie.MiscDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._MiscDirtyCallBack),e&Ie.PrePassDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._PrePassDirtyCallBack),Ie._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ie._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(Ie._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ie._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ie._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ie._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ie._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ie._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ie._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ie._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ie._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ie._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Xo.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(Lr.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=Xe.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 G.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=fe.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,s){var r;if(e.plugins)for(const n in e.plugins){const a=e.plugins[n];let l=(r=t.pluginManager)===null||r===void 0?void 0:r.getPlugin(a.name);if(!l){const h=fe.Instantiate("BABYLON."+n);h&&(l=new h(t))}l==null||l.parse(a,i,s)}}}Ie.TriangleFillMode=0;Ie.WireFrameFillMode=1;Ie.PointFillMode=2;Ie.PointListDrawMode=3;Ie.LineListDrawMode=4;Ie.LineLoopDrawMode=5;Ie.LineStripDrawMode=6;Ie.TriangleStripDrawMode=7;Ie.TriangleFanDrawMode=8;Ie.ClockWiseSideOrientation=0;Ie.CounterClockWiseSideOrientation=1;Ie.TextureDirtyFlag=1;Ie.LightDirtyFlag=2;Ie.FresnelDirtyFlag=4;Ie.AttributesDirtyFlag=8;Ie.MiscDirtyFlag=16;Ie.PrePassDirtyFlag=32;Ie.AllDirtyFlag=63;Ie.MATERIAL_OPAQUE=0;Ie.MATERIAL_ALPHATEST=1;Ie.MATERIAL_ALPHABLEND=2;Ie.MATERIAL_ALPHATESTANDBLEND=3;Ie.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Ie.MATERIAL_NORMALBLENDMETHOD_RNM=1;Ie.OnEventObservable=new he;Ie._AllDirtyCallBack=o=>o.markAllAsDirty();Ie._ImageProcessingDirtyCallBack=o=>o.markAsImageProcessingDirty();Ie._TextureDirtyCallBack=o=>o.markAsTexturesDirty();Ie._FresnelDirtyCallBack=o=>o.markAsFresnelDirty();Ie._MiscDirtyCallBack=o=>o.markAsMiscDirty();Ie._PrePassDirtyCallBack=o=>o.markAsPrePassDirty();Ie._LightsDirtyCallBack=o=>o.markAsLightDirty();Ie._AttributeDirtyCallBack=o=>o.markAsAttributesDirty();Ie._FresnelAndMiscDirtyCallBack=o=>{Ie._FresnelDirtyCallBack(o),Ie._MiscDirtyCallBack(o)};Ie._TextureAndMiscDirtyCallBack=o=>{Ie._TextureDirtyCallBack(o),Ie._MiscDirtyCallBack(o)};Ie._DirtyCallbackArray=[];Ie._RunDirtyCallBacks=o=>{for(const e of Ie._DirtyCallbackArray)e(o)};A([D()],Ie.prototype,"id",void 0);A([D()],Ie.prototype,"uniqueId",void 0);A([D()],Ie.prototype,"name",void 0);A([D()],Ie.prototype,"metadata",void 0);A([D()],Ie.prototype,"checkReadyOnEveryCall",void 0);A([D()],Ie.prototype,"checkReadyOnlyOnce",void 0);A([D()],Ie.prototype,"state",void 0);A([D("alpha")],Ie.prototype,"_alpha",void 0);A([D("backFaceCulling")],Ie.prototype,"_backFaceCulling",void 0);A([D("cullBackFaces")],Ie.prototype,"_cullBackFaces",void 0);A([D()],Ie.prototype,"sideOrientation",void 0);A([D("alphaMode")],Ie.prototype,"_alphaMode",void 0);A([D()],Ie.prototype,"_needDepthPrePass",void 0);A([D()],Ie.prototype,"disableDepthWrite",void 0);A([D()],Ie.prototype,"disableColorWrite",void 0);A([D()],Ie.prototype,"forceDepthWrite",void 0);A([D()],Ie.prototype,"depthFunction",void 0);A([D()],Ie.prototype,"separateCullingPass",void 0);A([D("fogEnabled")],Ie.prototype,"_fogEnabled",void 0);A([D()],Ie.prototype,"pointSize",void 0);A([D()],Ie.prototype,"zOffset",void 0);A([D()],Ie.prototype,"zOffsetUnits",void 0);A([D()],Ie.prototype,"pointsCloud",null);A([D()],Ie.prototype,"fillMode",null);A([D()],Ie.prototype,"useLogarithmicDepth",null);A([D()],Ie.prototype,"transparencyMode",null);class dh extends Ie{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=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new dh(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ui&&ui.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}j("BABYLON.MultiMaterial",dh);class jw{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class xb{}class Qw{constructor(){this.visibleInstances={},this.batchCache=new t0,this.batchCacheReplacementModeInFrozenMode=new t0,this.instancesBufferSize=32*16*4}}class t0{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Zw{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Jw{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 se extends hi{static _GetDefaultSideOrientation(e){return e||se.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(P.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(P.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 he),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new he),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new he),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new he),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new he),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 Jw,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Qw,this._thinInstanceDataStorage=new Zw,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=se.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(a,l,h)=>{a&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),Ur.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const a=s._ranges;for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&a[l]&&this.createAnimationRange(l,a[l].from,a[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ui&&ui.HasTags(s)&&ui.AddTagsTo(this,ui.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix()),this.id=e+"."+s.id,this.material=s.material,!r){const a=s.getDescendants(!0);for(let l=0;l{a.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new he(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;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return G.Warn("You cannot use a mesh as LOD level twice"),this;const i=new jw(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;ia*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const f=this.material||u.defaultMaterial;if(f){if(f._storeEffectOnSubMeshes)for(const _ of this.subMeshes){const g=_.getMaterial();if(g){if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,_,d))return!1}else if(!g.isReady(this,d))return!1}}else if(!f.isReady(this,d))return!1}const p=c.currentRenderPassId;for(const _ of this.lightSources){const g=_.getShadowGenerators();if(!g)continue;const v=g.values();for(let E=v.next();E.done!==!0;E=v.next()){const C=E.value;if(C&&(!(!((i=C.getShadowMap())===null||i===void 0)&&i.renderList)||!((s=C.getShadowMap())===null||s===void 0)&&s.renderList&&((n=(r=C.getShadowMap())===null||r===void 0?void 0:r.renderList)===null||n===void 0?void 0:n.indexOf(this))!==-1)){const b=(a=C.getShadowMap().renderPassIds)!==null&&a!==void 0?a:[c.currentRenderPassId];for(let R=0;R0){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 on(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=t);r++)on.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 De;r.set(t,e);const n=this.getScene();new sn(sn.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=sn.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(P.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(P.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(P.NormalKind);if(!r)return this;De.ComputeNormals(i,s,r),this.updateVerticesData(P.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(sn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new sn(sn.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 De;s.indices=e;const r=this.getScene();new sn(sn.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 Ie.PointFillMode:n=null;break;case Ie.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Ie.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==Ie.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ie.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const a=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?a.intermediateDefaultRenderId:a.defaultRenderId;n.visibleInstances[e]=a[l],!n.visibleInstances[e]&&h&&(n.visibleInstances[e]=a[h])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&n.visibleInstances[e]!==null&&n.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){var n;const a=i.visibleInstances[e._id],l=a?a.length:0,h=this._instanceDataStorage,c=h.instancesBufferSize;let u=h.instancesBuffer,d=h.instancesPreviousBuffer;const p=(l+1)*16*4;for(;h.instancesBufferSizeb._distanceToCamera>R._distanceToCamera?-1:b._distanceToCamera1&&h.activeCamera===h.activeCameras[0]||c<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const d=this._getInstancesRenderList(e._id,!!i);if(d.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const f=h.getEngine();let p=0,_=null;this.ignoreCameraMaxZ&&h.activeCamera&&!h._isInIntermediateRendering()&&(p=h.activeCamera.maxZ,_=h.activeCamera,h.activeCamera.maxZ=0,h.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const g=e.getRenderingMesh(),v=d.hardwareInstancedRendering[e._id]||g.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,E=this._instanceDataStorage,C=e.getMaterial();if(!C)return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;if(!E.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==C){if(C._storeEffectOnSubMeshes){if(!C.isReadyForSubMesh(this,e,v))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this}else if(!C.isReady(this,v))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=C}else if(C._storeEffectOnSubMeshes&&!(!((n=e.effect)===null||n===void 0)&&n._wasPreviouslyReady)||!C._storeEffectOnSubMeshes&&!(!((a=C.getEffect())===null||a===void 0)&&a._wasPreviouslyReady))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;t&&f.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let S;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?S=e._drawWrapper:S=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const b=(l=S==null?void 0:S.effect)!==null&&l!==void 0?l:null;for(const V of h._beforeRenderingMeshStage)V.action(this,e,d,b);if(!S||!b)return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;const R=i||this;let I;if(!E.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const V=R._getWorldMatrixDeterminant();I=this.overrideMaterialSideOrientation,I==null&&(I=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),V<0&&(I=I===Ie.ClockWiseSideOrientation?Ie.CounterClockWiseSideOrientation:Ie.ClockWiseSideOrientation),E.sideOrientation=I}else I=E.sideOrientation;const N=this._internalMeshDataInfo._effectiveMaterial._preBind(S,I);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&f.setDepthWrite(!0);const O=this._internalMeshDataInfo._effectiveMaterial,L=O.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,b,L,!1);const B=R.getWorldMatrix();O._storeEffectOnSubMeshes?O.bindForSubMesh(B,this,e):O.bind(B,this),!O.backFaceCulling&&O.separateCullingPass&&(f.setState(!0,O.zOffset,!1,!N,O.cullBackFaces,O.stencil,O.zOffsetUnits),this._processRendering(this,e,b,L,d,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),f.setState(!0,O.zOffset,!1,N,O.cullBackFaces,O.stencil,O.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,b,L,d,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const V of h._afterRenderingMeshStage)V.action(this,e,d,b);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),_&&(_.maxZ=p,h.updateTransformMatrix(!0)),h.performancePriority===Xo.Aggressive&&!E.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(P.MatricesWeightsKind)&&(this.isVerticesDataPresent(P.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(P.MatricesWeightsKind),t=e.length;for(let i=0;iv&&s++,b!==0&&C++,E+=b,v=b}if(h[C]++,C>n&&(n=C),E===0)r++;else{const S=1/E;let b=0;for(let R=0;Rc&&a++}}const u=this.skeleton.bones.length,d=this.getVerticesData(P.MatricesIndicesKind),f=this.getVerticesData(P.MatricesIndicesExtraKind);let p=0;for(let g=0;g=u||E<0)&&p++}const _="Number of Weights = "+i/4+` +`);break}}return e}}class Es{constructor(){this._dirty=!0,this._tempColor=new Ze(0,0,0,0),this._globalCurve=new Ze(0,0,0,0),this._highlightsCurve=new Ze(0,0,0,0),this._midtonesCurve=new Ze(0,0,0,0),this._shadowsCurve=new Ze(0,0,0,0),this._positiveCurve=new Ze(0,0,0,0),this._negativeCurve=new Ze(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,s,r){e!=null&&(e=Es._Clamp(e,0,360),t=Es._Clamp(t,-100,100),i=Es._Clamp(i,-100,100),s=Es._Clamp(s,-100,100),t=Es._ApplyColorGradingSliderNonlinear(t),t*=.5,s=Es._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),Es._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=Es._Clamp(e,0,360);const n=Es._Clamp(t/100,0,1),a=Es._Clamp(i/100,0,1);if(n===0)s.r=a,s.g=a,s.b=a;else{r/=60;const l=Math.floor(r),h=r-l,c=a*(1-n),u=a*(1-n*h),d=a*(1-n*(1-h));switch(l){case 0:s.r=a,s.g=d,s.b=c;break;case 1:s.r=u,s.g=a,s.b=c;break;case 2:s.r=c,s.g=a,s.b=d;break;case 3:s.r=c,s.g=u,s.b=a;break;case 4:s.r=d,s.g=c,s.b=a;break;default:s.r=a,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Xe.Clone(()=>new Es,this)}serialize(){return Xe.Serialize(this)}static Parse(e){return Xe.Parse(()=>new Es,e,null,null)}}A([D()],Es.prototype,"_globalHue",void 0);A([D()],Es.prototype,"_globalDensity",void 0);A([D()],Es.prototype,"_globalSaturation",void 0);A([D()],Es.prototype,"_globalExposure",void 0);A([D()],Es.prototype,"_highlightsHue",void 0);A([D()],Es.prototype,"_highlightsDensity",void 0);A([D()],Es.prototype,"_highlightsSaturation",void 0);A([D()],Es.prototype,"_highlightsExposure",void 0);A([D()],Es.prototype,"_midtonesHue",void 0);A([D()],Es.prototype,"_midtonesDensity",void 0);A([D()],Es.prototype,"_midtonesSaturation",void 0);A([D()],Es.prototype,"_midtonesExposure",void 0);Xe._ColorCurvesParser=Es.Parse;class Pw extends Wn{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 jt{constructor(){this.colorCurves=new Es,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=jt.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ze(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=jt.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new he}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Es.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}switch(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===jt._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case jt.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&&Es.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),a=n*r;const l=Math.sqrt(a*n);a=fe.Mix(a,l,this.vignetteStretch),n=fe.Mix(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return Xe.Clone(()=>new jt,this)}serialize(){return Xe.Serialize(this)}static Parse(e){const t=Xe.Parse(()=>new jt,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}}jt.TONEMAPPING_STANDARD=0;jt.TONEMAPPING_ACES=1;jt._VIGNETTEMODE_MULTIPLY=0;jt._VIGNETTEMODE_OPAQUE=1;A([iw()],jt.prototype,"colorCurves",void 0);A([D()],jt.prototype,"_colorCurvesEnabled",void 0);A([Jt("colorGradingTexture")],jt.prototype,"_colorGradingTexture",void 0);A([D()],jt.prototype,"_colorGradingEnabled",void 0);A([D()],jt.prototype,"_colorGradingWithGreenDepth",void 0);A([D()],jt.prototype,"_colorGradingBGR",void 0);A([D()],jt.prototype,"_exposure",void 0);A([D()],jt.prototype,"_toneMappingEnabled",void 0);A([D()],jt.prototype,"_toneMappingType",void 0);A([D()],jt.prototype,"_contrast",void 0);A([D()],jt.prototype,"vignetteStretch",void 0);A([D()],jt.prototype,"vignetteCenterX",void 0);A([D()],jt.prototype,"vignetteCenterY",void 0);A([D()],jt.prototype,"vignetteWeight",void 0);A([nx()],jt.prototype,"vignetteColor",void 0);A([D()],jt.prototype,"vignetteCameraFov",void 0);A([D()],jt.prototype,"_vignetteBlendMode",void 0);A([D()],jt.prototype,"_vignetteEnabled",void 0);A([D()],jt.prototype,"_ditheringEnabled",void 0);A([D()],jt.prototype,"_ditheringIntensity",void 0);A([D()],jt.prototype,"_skipFinalColorClamp",void 0);A([D()],jt.prototype,"_applyByPostProcess",void 0);A([D()],jt.prototype,"_isEnabled",void 0);Xe._ImageProcessingConfigurationParser=jt.Parse;We.prototype.createUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new bd(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};We.prototype.createDynamicUniformBuffer=function(o,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new bd(t);return this.bindUniformBuffer(i),o instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,o,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(o),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};We.prototype.updateUniformBuffer=function(o,e,t,i){this.bindUniformBuffer(o),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)};We.prototype.bindUniformBuffer=function(o){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,o?o.underlyingResource:null)};We.prototype.bindUniformBufferBase=function(o,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,o?o.underlyingResource:null)};We.prototype.bindUniformBlock=function(o,e,t){const i=o.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class it{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;r0){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;r1&&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&&(it._UpdatedUbosInFrame[this._name]||(it._UpdatedUbosInFrame[this._name]=0),it._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(s===void 0){if(this._buffer){G.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;ru[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),p=new Float32Array(e.buffer,u,c);return f.set(p),f}const d=u%4;return d&&(u=Math.max(0,u-d)),new Float32Array(e.buffer,u,c)}}return l?e.slice():e}}P._Counter=0;P.BYTE=5120;P.UNSIGNED_BYTE=5121;P.SHORT=5122;P.UNSIGNED_SHORT=5123;P.INT=5124;P.UNSIGNED_INT=5125;P.FLOAT=5126;P.PositionKind="position";P.NormalKind="normal";P.TangentKind="tangent";P.UVKind="uv";P.UV2Kind="uv2";P.UV3Kind="uv3";P.UV4Kind="uv4";P.UV5Kind="uv5";P.UV6Kind="uv6";P.ColorKind="color";P.ColorInstanceKind="instanceColor";P.MatricesIndicesKind="matricesIndices";P.MatricesWeightsKind="matricesWeights";P.MatricesIndicesExtraKind="matricesIndicesExtra";P.MatricesWeightsExtraKind="matricesWeightsExtra";class Vr{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(P.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const r=K.Vector3[0],n=K.Vector3[1],a=K.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(P.NormalKind);let c=i?T.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?T.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?T.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),d=d.scale(1-this.bu-this.bv),s=new T(c.x+u.x+d.x,c.y+u.y+d.y,c.z+u.z+d.z)}else{const h=this.pickedMesh.getVerticesData(P.PositionKind),c=i?T.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?T.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?T.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]),f=c.subtract(u),p=d.subtract(u);s=T.Cross(f,p)}const l=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(K.Matrix[0].copyFrom(u),u=K.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(K.Matrix[1]),u=K.Matrix[1]),T.TransformNormalToRef(c,u,c)};if(e&&l(this.pickedMesh,s),this.ray){const h=K.Vector3[0].copyFrom(s);e||l(this.pickedMesh,h),T.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=P.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=Re.FromArray(i,t[this.faceId*3]*2),r=Re.FromArray(i,t[this.faceId*3+1]*2),n=Re.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 Re(s.x+r.x+n.x,s.y+r.y+n.y)}}class A_{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[P.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[P.PositionKind]=new P(this._scene.getEngine(),e,P.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[P.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,r=0,n=!1){var a;const l=this._scene.getEngine();for(let h=0;hh!=null),s.length===0||!this._scene.postProcessesEnabled))return;const l=this._scene.getEngine();for(let h=0,c=s.length;ht._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._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=Ot.LeftClick&&i<=Ot.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=fu.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Ot.MouseWheelX:a.deltaX=s;break;case Ot.MouseWheelY:a.deltaY=s;break;case Ot.MouseWheelZ:a.deltaZ=s;break}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),l=r.pollInput(e,t,Ot.Horizontal),h=r.pollInput(e,t,Ot.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,R_.DeltaHorizontal),a.movementY=r.pollInput(e,t,R_.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=mt.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(mt.Keyboard),s=i&&t.pollInput(mt.Keyboard,0,18)===1,r=i&&t.pollInput(mt.Keyboard,0,17)===1,n=i&&(t.pollInput(mt.Keyboard,0,91)===1||t.pollInput(mt.Keyboard,0,92)===1||t.pollInput(mt.Keyboard,0,93)===1),a=i&&t.pollInput(mt.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class Ow{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,a)=>{const l=Nh.CreateDeviceEvent(s,r,n,a,this);i(s,r,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===mt.Mouse||e===mt.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const QS=255,ZS=Object.keys(Ot).length/2;class Nw{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=fe.IsSafari(),this._usingMacOS=ju()&&/(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=ju()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=ju()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=fe.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 ${mt[e]}`;e>=mt.DualShock&&e<=mt.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${mt[e]} in slot ${t}`;return i===Ot.Move&&fe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this===null||this===void 0?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const s=+i,r=t[s];if(r)for(let n=0;n{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(mt.Keyboard,0,QS));const t=this._inputs[mt.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(mt.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(mt.Keyboard,0,QS));const t=this._inputs[mt.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=Nh.CreateDeviceEvent(mt.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(mt.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(mt.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[mt.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let r=s===mt.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===mt.Touch&&r===-1){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId,this._onDeviceConnected(s,r);else{fe.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 a=i;a.inputIndex=Ot.Move,n[Ot.Horizontal]=i.clientX,n[Ot.Vertical]=i.clientY,s===mt.Touch&&n[Ot.LeftClick]===0&&(n[Ot.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,a),!this._usingSafari&&i.button!==-1&&(a.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,a))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===mt.Mouse?0:i.pointerId;if(s===mt.Touch){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId;else{fe.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===mt.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=n[Ot.Horizontal],l=n[Ot.Vertical];if(s===mt.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[Ot.Horizontal]=i.clientX,n[Ot.Vertical]=i.clientY,n[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,r,h),(a!==i.clientX||l!==i.clientY)&&(h.inputIndex=Ot.Move,this._onInputChanged(s,r,h))}},this._pointerUpEvent=i=>{var s,r,n,a,l;const h=this._getPointerType(i),c=h===mt.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(h===mt.Touch){if(c===-1)return;this._activeTouchIds[c]=-1}const u=(s=this._inputs[h])===null||s===void 0?void 0:s[c];if(u&&u[i.button+2]!==0){const d=u[Ot.Horizontal],f=u[Ot.Vertical];u[Ot.Horizontal]=i.clientX,u[Ot.Vertical]=i.clientY,u[i.button+2]=0;const p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(p.inputIndex=Ot.Move,this._onInputChanged(h,c,p)),p.inputIndex=i.button+2,h===mt.Mouse&&this._mouseId>=0&&(!((n=(r=this._elementToAttachTo).hasPointerCapture)===null||n===void 0)&&n.call(r,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&(!((l=(a=this._elementToAttachTo).hasPointerCapture)===null||l===void 0)&&l.call(a,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(h,c,p),h===mt.Touch&&this._onDeviceDisconnected(h,c)}},this._pointerCancelEvent=i=>{var s,r,n,a;if(i.pointerType==="mouse"){const l=this._inputs[mt.Mouse][0];this._mouseId>=0&&(!((r=(s=this._elementToAttachTo).hasPointerCapture)===null||r===void 0)&&r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Ot.LeftClick;h<=Ot.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Nh.CreateDeviceEvent(mt.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(mt.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;!((a=(n=this._elementToAttachTo).hasPointerCapture)===null||a===void 0)&&a.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[mt.Touch][l][Ot.LeftClick]=0;const h=Nh.CreateDeviceEvent(mt.Touch,l,Ot.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(mt.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(mt.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,a;if(this.isDeviceAvailable(mt.Mouse)){const l=this._inputs[mt.Mouse][0];this._mouseId>=0&&(!((s=(i=this._elementToAttachTo).hasPointerCapture)===null||s===void 0)&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=Ot.LeftClick;h<=Ot.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Nh.CreateDeviceEvent(mt.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(mt.Mouse,0,c)}}if(this.isDeviceAvailable(mt.Touch)){const l=this._inputs[mt.Touch];for(let h=0;h{const s=mt.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,ZS));const n=this._inputs[s][r];if(n){n[Ot.MouseWheelX]=i.deltaX||0,n[Ot.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[Ot.MouseWheelZ]=i.deltaZ||0;const a=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[Ot.MouseWheelX]!==0&&(a.inputIndex=Ot.MouseWheelX,this._onInputChanged(s,r,a)),n[Ot.MouseWheelY]!==0&&(a.inputIndex=Ot.MouseWheelY,this._onInputChanged(s,r,a)),n[Ot.MouseWheelZ]!==0&&(a.inputIndex=Ot.MouseWheelZ,this._onInputChanged(s,r,a))}},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(mt.Mouse)){const i=this._inputs[mt.Mouse][0];i[Ot.MouseWheelX]=0,i[Ot.MouseWheelY]=0,i[Ot.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?mt.DualSense:mt.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?mt.Xbox:e.indexOf("057e")!==-1?mt.Switch:mt.Generic}_getPointerType(e){let t=mt.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=mt.Touch),t}}class JS{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new he,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class ww{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let a=0;a{const a=this._registeredManagers.indexOf(n);a>-1&&this._registeredManagers.splice(a,1)};const t=Object.keys(mt).length/2;this._devices=new Array(t);const i=(n,a)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][a]||(this._devices[n][a]=a);for(const l of this._registeredManagers){const h=new JS(this._deviceInputSystem,n,a);l._addDevice(h)}},s=(n,a)=>{var l;!((l=this._devices[n])===null||l===void 0)&&l[a]&&delete this._devices[n][a];for(const h of this._registeredManagers)h._removeDevice(n,a)},r=(n,a,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(n,a,l)};typeof _native<"u"?this._deviceInputSystem=new Ow(i,s,r):this._deviceInputSystem=new Nw(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Fw{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(mt).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new ww(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new he(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new he,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,s;const r=(i=this._devices[e])===null||i===void 0?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(r),!((s=this._devices[e])===null||s===void 0)&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])===null||s===void 0?void 0:s[t])===null||r===void 0||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case mt.Keyboard:case mt.Mouse:this._firstDevice[e]=0;break;case mt.Touch:case mt.DualSense:case mt.DualShock:case mt.Xbox:case mt.Switch:case mt.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=Ot.MouseWheelX&&t.inputIndex<=Ot.MouseWheelZ?rt.POINTERWHEEL:rt.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let a;e?(a=new Ja(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Ja(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,k.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 Dw(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const r=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Ot.Move,!this._checkPrePointerObservable(e,i,rt.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,rt.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,_r.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,_r.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(4,_r.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(3,_r.CreateNew(e.pickedMesh,t,e));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const a=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);a!=null&&a.pickedMesh&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>Vs.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,_r.CreateNew(a.pickedMesh,t)))},Vs.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=rt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Ja(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Ja(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=Ot.Move;const r=new e0;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,rt.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=rt.POINTERPICK,a=new Ja(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(a,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,_r.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,_r.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,_r.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,_r.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Ja(rt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,rt.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,rt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=rt.POINTERTAP:i.doubleClick&&(n=rt.POINTERDOUBLETAP),n){const a=new Ja(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(a,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Fw(n),this._initActionManager=a=>{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);this._currentPickResult=l,l&&(a=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return a},this._delayedSimpleClick=(a,l,h)=>{if((Date.now()-this._previousStartingPointerTime>Vs.DoubleClickDelay&&!this._doubleClickOccured||a!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[a])){const c=this._delayedClicks[a].evt,u=rt.POINTERTAP,d=new Ja(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(d,u),this._delayedClicks[a]=null}},this._initClickEvent=(a,l,h,c)=>{var u,d;const f=new e0;this._currentPickResult=null;let p=null,_=a.hasSpecificMask(rt.POINTERPICK)||l.hasSpecificMask(rt.POINTERPICK)||a.hasSpecificMask(rt.POINTERTAP)||l.hasSpecificMask(rt.POINTERTAP)||a.hasSpecificMask(rt.POINTERDOUBLETAP)||l.hasSpecificMask(rt.POINTERDOUBLETAP);!_&&aa&&(p=this._initActionManager(p,f),p&&(_=p.hasPickTriggers));let g=!1;if(_){const v=h.button;if(f.hasSwiped=this._isPointerSwiping(),!f.hasSwiped){let E=!Vs.ExclusiveDoubleClickMode;if(E||(E=!a.hasSpecificMask(rt.POINTERDOUBLETAP)&&!l.hasSpecificMask(rt.POINTERDOUBLETAP),E&&!aa.HasSpecificTrigger(6)&&(p=this._initActionManager(p,f),p&&(E=!p.hasSpecificTrigger(6)))),E)(Date.now()-this._previousStartingPointerTime>Vs.DoubleClickDelay||v!==this._previousButtonPressed)&&(f.singleClick=!0,c(f,this._currentPickResult),g=!0);else{const S={evt:h,clickInfo:f,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,v,f,c),Vs.DoubleClickDelay)};this._delayedClicks[v]=S}let C=a.hasSpecificMask(rt.POINTERDOUBLETAP)||l.hasSpecificMask(rt.POINTERDOUBLETAP);!C&&aa.HasSpecificTrigger(6)&&(p=this._initActionManager(p,f),p&&(C=p.hasSpecificTrigger(6))),C&&(v===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(a),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Vs.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Vs.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,a,a.inputIndex>=Ot.MouseWheelX&&a.inputIndex<=Ot.MouseWheelZ?rt.POINTERWHEEL:rt.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new Vr,a);return}r.pointerMovePredicate||(r.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0));const l=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(a):null;this._processPointerMove(l,a)},this._onPointerDown=a=>{var l;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Vs.ExclusiveDoubleClickMode){for(let c=0;cc.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let h;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?h=new Vr:h=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers),this._processPointerDown(h,a)},this._onPointerUp=a=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(a),r.preventDefaultOnPointerUp&&s&&(a.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,a,(l,h)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,a,rt.POINTERUP)){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(rt.POINTERTAP)&&this._checkPrePointerObservable(null,a,rt.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(rt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,a,rt.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[a.pointerId]){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(aa&&aa.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,a,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=a=>{const l=dh.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const h=new XS(l,a);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Nv(l,a);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(14,_r.CreateNewFromScene(r,a))},this._onKeyUp=a=>{const l=dh.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const h=new XS(l,a);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Nv(l,a);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(15,_r.CreateNewFromScene(r,a))},this._deviceSourceManager.onDeviceConnectedObservable.add(a=>{a.deviceType===mt.Mouse?a.onInputChangedObservable.add(l=>{l.inputIndex===Ot.LeftClick||l.inputIndex===Ot.MiddleClick||l.inputIndex===Ot.RightClick||l.inputIndex===Ot.BrowserBack||l.inputIndex===Ot.BrowserForward?t&&a.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&a.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===Ot.Move?this._onPointerMove(l):(l.inputIndex===Ot.MouseWheelX||l.inputIndex===Ot.MouseWheelY||l.inputIndex===Ot.MouseWheelZ)&&this._onPointerMove(l))}):a.deviceType===mt.Touch?a.onInputChangedObservable.add(l=>{l.inputIndex===Ot.LeftClick&&(t&&a.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&a.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===Ot.Move&&this._onPointerMove(l)}):a.deviceType===mt.Keyboard&&a.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,_r.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,_r.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]}}Vs.DragMovementThreshold=10;Vs.LongPressDelay=500;Vs.DoubleClickDelay=300;Vs.ExclusiveDoubleClickMode=!1;class Pa{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){Pa.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Pa.Enabled&&(this._startMonitoringTime=ar.Now)}endMonitoring(e=!0){if(!Pa.Enabled)return;e&&this.fetchNewFrame();const t=ar.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=ar.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Pa.Enabled=!0;class Rn{constructor(e,t,i,s){this.normal=new T(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Rn(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=Rn._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,l=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],c=s*i[8]+r*i[9]+n*i[10]+a*i[11],u=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new Rn(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,a=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=r*h-n*l,u=n*a-s*h,d=s*l-r*a,f=Math.sqrt(c*c+u*u+d*d);let p;return f!==0?p=1/f:p=0,this.normal.x=c*p,this.normal.y=u*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return T.Dot(this.normal,e)<=t}signedDistanceTo(e){return T.Dot(e,this.normal)+this.d}static FromArray(e){return new Rn(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Rn(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Rn(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 T.Dot(i,t)+s}}Rn._TmpMatrix=k.Identity();class Aa{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Rn(0,0,0,0));return Aa.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){Aa.GetNearPlaneToRef(e,t[0]),Aa.GetFarPlaneToRef(e,t[1]),Aa.GetLeftPlaneToRef(e,t[2]),Aa.GetRightPlaneToRef(e,t[3]),Aa.GetTopPlaneToRef(e,t[4]),Aa.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 Jf{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Jf._UniqueIdCounter=1;class Bi{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Bi.FALLOFF_DEFAULT=0;Bi.FALLOFF_PHYSICAL=1;Bi.FALLOFF_GLTF=2;Bi.FALLOFF_STANDARD=3;Bi.LIGHTMAP_DEFAULT=0;Bi.LIGHTMAP_SPECULAR=1;Bi.LIGHTMAP_SHADOWSONLY=2;Bi.INTENSITYMODE_AUTOMATIC=0;Bi.INTENSITYMODE_LUMINOUSPOWER=1;Bi.INTENSITYMODE_LUMINOUSINTENSITY=2;Bi.INTENSITYMODE_ILLUMINANCE=3;Bi.INTENSITYMODE_LUMINANCE=4;Bi.LIGHTTYPEID_POINTLIGHT=0;Bi.LIGHTTYPEID_DIRECTIONALLIGHT=1;Bi.LIGHTTYPEID_SPOTLIGHT=2;Bi.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Lw{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Xo;(function(o){o[o.BackwardCompatible=0]="BackwardCompatible",o[o.Intermediate=1]="Intermediate",o[o.Aggressive=2]="Aggressive"})(Xo||(Xo={}));class Qe extends ks{static DefaultMaterialFactory(e){throw xt("StandardMaterial")}static CollisionCoordinatorFactory(){throw xt("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 Xo.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Xo.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Xo.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 Vs.DragMovementThreshold}static set DragMovementThreshold(e){Vs.DragMovementThreshold=e}static get LongPressDelay(){return Vs.LongPressDelay}static set LongPressDelay(e){Vs.LongPressDelay=e}static get DoubleClickDelay(){return Vs.DoubleClickDelay}static set DoubleClickDelay(e){Vs.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Vs.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Vs.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 K.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,K.Vector4[0].x,K.Vector4[0].y,K.Vector4[0].z):e.setVector4(t,K.Vector4[0])),K.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=qC(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Qe.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Qe.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Vs(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ze(.2,.2,.3,1),this.ambientColor=new Te(0,0,0),this.environmentIntensity=1,this._performancePriority=Xo.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new he,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 he,this._onDisposeObserver=null,this.onBeforeRenderObservable=new he,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new he,this.onAfterRenderCameraObservable=new he,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new he,this.onAfterAnimationsObservable=new he,this.onBeforeDrawPhaseObservable=new he,this.onAfterDrawPhaseObservable=new he,this.onReadyObservable=new he,this.onBeforeCameraRenderObservable=new he,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new he,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new he,this.onAfterActiveMeshesEvaluationObservable=new he,this.onBeforeParticlesRenderingObservable=new he,this.onAfterParticlesRenderingObservable=new he,this.onDataLoadedObservable=new he,this.onNewCameraAddedObservable=new he,this.onCameraRemovedObservable=new he,this.onNewLightAddedObservable=new he,this.onLightRemovedObservable=new he,this.onNewGeometryAddedObservable=new he,this.onGeometryRemovedObservable=new he,this.onNewTransformNodeAddedObservable=new he,this.onTransformNodeRemovedObservable=new he,this.onNewMeshAddedObservable=new he,this.onMeshRemovedObservable=new he,this.onNewSkeletonAddedObservable=new he,this.onSkeletonRemovedObservable=new he,this.onNewMaterialAddedObservable=new he,this.onNewMultiMaterialAddedObservable=new he,this.onMaterialRemovedObservable=new he,this.onMultiMaterialRemovedObservable=new he,this.onNewTextureAddedObservable=new he,this.onTextureRemovedObservable=new he,this.onBeforeRenderTargetsRenderObservable=new he,this.onAfterRenderTargetsRenderObservable=new he,this.onBeforeStepObservable=new he,this.onAfterStepObservable=new he,this.onActiveCameraChanged=new he,this.onActiveCamerasChanged=new he,this.onBeforeRenderingGroupObservable=new he,this.onAfterRenderingGroupObservable=new he,this.onMeshImportedObservable=new he,this.onAnimationFileImportedObservable=new he,this._registeredForLateAnimationBindings=new $l(256),this._pointerPickingConfiguration=new Lw,this.onPrePointerObservable=new he,this.onPointerObservable=new he,this.onPreKeyboardObservable=new he,this.onKeyboardObservable=new he,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Qe.FOGMODE_NONE,this.fogColor=new Te(.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 T(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new $l(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Pa,this._activeIndices=new Pa,this._activeParticles=new Pa,this._activeBones=new Pa,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 qs(256),this._processedMaterials=new qs(256),this._renderTargets=new $l(256),this._materialsRenderTargets=new $l(256),this._activeParticleSystems=new qs(256),this._activeSkeletons=new $l(32),this._softwareSkinnedMeshes=new $l(32),this._activeAnimatables=new Array,this._transformMatrix=k.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Fs.Create(),this._beforeClearStage=Fs.Create(),this._beforeRenderTargetClearStage=Fs.Create(),this._gatherRenderTargetsStage=Fs.Create(),this._gatherActiveCameraRenderTargetsStage=Fs.Create(),this._isReadyForMeshStage=Fs.Create(),this._beforeEvaluateActiveMeshStage=Fs.Create(),this._evaluateSubMeshStage=Fs.Create(),this._preActiveMeshStage=Fs.Create(),this._cameraDrawRenderTargetStage=Fs.Create(),this._beforeCameraDrawStage=Fs.Create(),this._beforeRenderTargetDrawStage=Fs.Create(),this._beforeRenderingGroupDrawStage=Fs.Create(),this._beforeRenderingMeshStage=Fs.Create(),this._afterRenderingMeshStage=Fs.Create(),this._afterRenderingGroupDrawStage=Fs.Create(),this._afterCameraDrawStage=Fs.Create(),this._afterCameraPostProcessStage=Fs.Create(),this._afterRenderTargetDrawStage=Fs.Create(),this._afterRenderTargetPostProcessStage=Fs.Create(),this._afterRenderStage=Fs.Create(),this._pointerMoveStage=Fs.Create(),this._pointerDownStage=Fs.Create(),this._pointerUpStage=Fs.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=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||ht.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(ht._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Fr(this),A_&&(this.postProcessManager=new A_(this)),gr()&&this.attachControl(),this._createUbo(),jt&&(this._imageProcessingConfiguration=new jt),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 t,i,s;if(this._isDisposed)return!1;let r;const n=this.getEngine(),a=n.currentRenderPassId;n.currentRenderPassId=(i=(t=this.activeCamera)===null||t===void 0?void 0:t.renderPassId)!==null&&i!==void 0?i:a;let l=!0;for(this._pendingData.length>0&&(l=!1),(s=this.prePassRenderer)===null||s===void 0||s.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&l&&(l=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r0;for(const d of this._isReadyForMeshStage)d.action(h,c)||(l=!1);if(!e)continue;const u=h.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const d of h.subMeshes){const f=d.getMaterial();f&&f.hasRenderTargetTextures&&f.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(f)===-1&&(this._processedMaterials.push(f),this._materialsRenderTargets.concatWithNoDuplicate(f.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(r=0;r0)for(const h of this.activeCameras)h.isReady(!0)||(l=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(l=!1));for(const h of this.particleSystems)h.isReady()||(l=!1);if(this.layers)for(const h of this.layers)h.isReady()||(l=!1);return n.areAllEffectsReady()||(l=!1),n.currentRenderPassId=a,l}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=ar.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?Aa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Aa.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 it(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 Jf.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(i=>{this.addMesh(i)}))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return i!==-1&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(s=>{this.removeMesh(s)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const 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=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;ne.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((e=this.activeCamera)===null||e===void 0||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const s=this._activeMeshes.length;for(let r=0;r0&&r.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(r),this.activeCamera._activeMeshes.push(r),n!==r&&n._activate(this._renderId,!1);for(const a of this._preActiveMeshStage)a.action(r);r._activate(this._renderId,!1)&&(r.isAnInstance?r._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=r):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(r,n)),r._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const h of this._gatherActiveCameraRenderTargetsStage)h.action(this._renderTargets);let l=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){fe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let h=0;h0),this._renderId++}for(const h of this._cameraDrawRenderTargetStage)l=h.action(this.activeCamera)||l;this._intermediateRendering=!1}this._engine.currentRenderPassId=(n=(r=(s=e.outputRenderTarget)===null||s===void 0?void 0:s.renderPassId)!==null&&r!==void 0?r:e.renderPassId)!==null&&n!==void 0?n:0,l&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const h of this._beforeCameraDrawStage)h.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),a.snapshotRendering&&a.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const h of this._afterCameraDrawStage)h.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const h=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,h)}for(const h of this._afterCameraPostProcessStage)h.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(s.trigger===13&&s._executeCurrent(_r.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(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Qe.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Qe.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let l=0;l0),this._intermediateRendering=!0;for(let l=0;l0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r=a==null?void 0:a.renderPassId)!==null&&r!==void 0?r:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const l of this._beforeClearStage)l.action();this._clearFrameBuffer(this.activeCamera);for(const l of this._gatherRenderTargetsStage)l.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let l=0;l0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const l of this._afterRenderStage)l.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let l=0;l{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){G.Error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;rr.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),ht._LastCreatedScene===this&&(this._engine.scenes.length>0?ht._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:ht._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!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const r=s.getBoundingInfo(),n=r.boundingBox.minimumWorld,a=r.boundingBox.maximumWorld;T.CheckExtends(n,t,i),T.CheckExtends(a,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw xt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw xt("Ray")}createPickingRayInCameraSpace(e,t,i){throw xt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw xt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const a=xt("Ray",!0);return a&&G.Warn(a),new Vr}pickWithBoundingInfo(e,t,i,s,r){const n=xt("Ray",!0);return n&&G.Warn(n),new Vr}pickWithRay(e,t,i,s){throw xt("Ray")}multiPick(e,t,i,s,r){throw xt("Ray")}multiPickWithRay(e,t,i){throw xt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const r in e){const n=e[r];ui&&ui.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,a){const l=uh(e,t,i,s?this.offlineProvider:void 0,r,n,a);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,a)=>{this._loadFile(e,l=>{n(l)},t,i,s,(l,h)=>{a(h)},r)})}_requestFile(e,t,i,s,r,n,a){const l=cx(e,t,i,s?this.offlineProvider:void 0,r,n,a);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,a)=>{this._requestFile(e,l=>{n(l)},t,i,s,l=>{a(l)},r)})}_readFile(e,t,i,s,r){const n=yd(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(a=>{this._activeRequests.splice(this._activeRequests.indexOf(a),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw xt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Qe.FOGMODE_NONE=0;Qe.FOGMODE_EXP=1;Qe.FOGMODE_EXP2=2;Qe.FOGMODE_LINEAR=3;Qe.MinDeltaTime=1;Qe.MaxDeltaTime=1e3;var _i;(function(o){o[o.LOCAL=0]="LOCAL",o[o.WORLD=1]="WORLD",o[o.BONE=2]="BONE"})(_i||(_i={}));class an{}an.X=new T(1,0,0);an.Y=new T(0,1,0);an.Z=new T(0,0,1);var Fh;(function(o){o[o.X=0]="X",o[o.Y=1]="Y",o[o.Z=2]="Z"})(Fh||(Fh={}));class rs extends Mi{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,a=null){var l;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=(l=s==null?void 0:s.clone())!==null&&l!==void 0?l:k.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new k,this._absoluteBindMatrix=new k,this._absoluteInverseBindMatrix=new k,this._finalMatrix=new k,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(){var e;if(this._linkedTransformNode){const t=K.Vector3[0],i=K.Quaternion[0],s=K.Vector3[1];this.getRestMatrix().decompose(t,i,s),this._linkedTransformNode.position.copyFrom(s),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!==null&&e!==void 0?e:Se.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=T.Zero(),this._localRotation=Se.Zero(),this._localPosition=T.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,k.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-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{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let n=r.length-1;n>=0;n--){const a=r[n];e&&a.animation.name!=e||t&&!t(a.target)||(a.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{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;s0)return;this._animationTimeLast=o}this.deltaTime=this.useConstantAnimationDeltaTime?16:(o-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=o;const e=this._activeAnimatables;if(e.length===0)return;this._animationTime+=this.deltaTime;const t=this._animationTime;for(let i=0;io.playOrder-e.playOrder)};Qe.prototype.beginWeightedAnimation=function(o,e,t,i=1,s,r=1,n,a,l,h,c=!1){const u=this.beginAnimation(o,e,t,s,r,n,a,!1,l,h,c);return u.weight=i,u};Qe.prototype.beginAnimation=function(o,e,t,i,s=1,r,n,a=!0,l,h,c=!1){e>t&&s>0&&(s*=-1),a&&this.stopAnimation(o,void 0,l),n||(n=new gb(this,o,e,t,i,s,r,void 0,h,c));const u=l?l(o):!0;if(o.animations&&u&&n.appendAnimations(o,o.animations),o.getAnimatables){const d=o.getAnimatables();for(let f=0;fi&&r>0)r*=-1;else if(i>t&&r<0){const c=i;i=t,t=c}return new gb(this,o,t,i,s,r,n,e,a,l)};Qe.prototype.beginDirectHierarchyAnimation=function(o,e,t,i,s,r,n,a,l,h=!1){const c=o.getDescendants(e),u=[];u.push(this.beginDirectAnimation(o,t,i,s,r,n,a,l,h));for(const d of c)u.push(this.beginDirectAnimation(d,t,i,s,r,n,a,l,h));return u};Qe.prototype.getAnimatableByTarget=function(o){for(let e=0;e0?l:-l,s),f.scaleAndAddToRef(l,t)}s.normalize()}for(let u=0;u0)s.copyFrom(i);else if(o.animations.length===1){if(Se.SlerpToRef(i,t.currentValue,Math.min(1,o.totalWeight),s),o.totalAdditiveWeight===0)return s}else if(o.animations.length>1){let r=1,n,a;if(o.totalWeight<1){const h=1-o.totalWeight;n=[],a=[],n.push(i),a.push(h)}else{if(o.animations.length===2&&(Se.SlerpToRef(o.animations[0].currentValue,o.animations[1].currentValue,o.animations[1].weight/o.totalWeight,e),o.totalAdditiveWeight===0))return e;n=[],a=[],r=o.totalWeight}for(let h=0;h=n&&g.frame<=a&&(i?(E=g.value.clone(),d?(v=E.getTranslation(),E.setTranslation(v.scaleInPlace(f))):p&&s?(v=E.getTranslation(),E.setTranslation(v.multiplyInPlace(s))):E=g.value):E=g.value,_.push({frame:g.frame+t,value:E}));return this.animations[0].createRange(e,n+t,a+t),!0};var zc;(function(o){o[o.CW=0]="CW",o[o.CCW=1]="CCW"})(zc||(zc={}));class ko{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 ko(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new ko(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=ye.Clamp(s,-1,1);const r=Math.acos(s);return new ko(r)}static FromRadians(e){return new ko(e)}static FromDegrees(e){return new ko(e*Math.PI/180)}}class Bw{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,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new Re((r*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*r)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=ko.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=ko.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=ko.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?zc.CW:zc.CCW,this.angle=ko.FromDegrees(this.orientation===zc.CW?l-c:c-l)}}class Q_{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Re(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new Re(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],a=new Re(e,t),l=new Re(i,s),h=new Bw(n,a,l);let c=h.angle.radians()/r;h.orientation===zc.CW&&(c*=-1);let u=h.startAngle.radians()+c;for(let d=0;d(1-l)*(1-l)*h+2*l*(1-l)*c+l*l*u,a=this._points[this._points.length-1];for(let l=0;l<=r;l++){const h=l/r,c=n(h,a.x,e,i),u=n(h,a.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,r,n,a=36){if(this.closed)return this;const l=(c,u,d,f,p)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*d+3*c*c*(1-c)*f+c*c*c*p,h=this._points[this._points.length-1];for(let c=0;c<=a;c++){const u=c/a,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;rNumber.EPSILON){if(h<0&&(n=this._points[r],l=-l,a=this._points[s],h=-h),e.ya.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(a.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=a.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return Re.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=h){const c=l.normalize(),u=t-i;return new Re(n.x+c.x*u,n.y+c.y*u)}i=h}return Re.Zero()}static StartingAt(e,t){return new Q_(e,t)}}class Ad{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:T.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:k.Identity()};for(let r=0;rt){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),a=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(r++,l.push(s)),l.push(...i.slice(r,a)),(t!==1||e===1)&&l.push(n),new Ad(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;st+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;ye.WithinEpsilon(Math.abs(e.y)/s,1,$t)?ye.WithinEpsilon(Math.abs(e.x)/s,1,$t)?ye.WithinEpsilon(Math.abs(e.z)/s,1,$t)?r=T.Zero():r=new T(0,0,1):r=new T(1,0,0):r=new T(0,-1,0),i=T.Cross(e,r)}else i=T.Cross(e,t),T.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 a=e*this.length();for(let l=1;la){const u=(n-a)/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=k.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(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=Se.RotationQuaternionFromAxis(s,r,i),c=Se.RotationQuaternionFromAxis(a,l,n);Se.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class Lo{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(a,l,h,c)=>(1-a)*(1-a)*l+2*a*(1-a)*h+a*a*c;for(let a=0;a<=s;a++)r.push(new T(n(a/s,e.x,t.x,i.x),n(a/s,e.y,t.y,i.y),n(a/s,e.z,t.z,i.z)));return new Lo(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],a=(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 T(a(l/r,e.x,t.x,i.x,s.x),a(l/r,e.y,t.y,i.y,s.y),a(l/r,e.z,t.z,i.z,s.z)));return new Lo(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],a=1/r;for(let l=0;l<=r;l++)n.push(T.Hermite(e,t,i,s,l*a));return new Lo(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const a=e.length;for(let l=0;l=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}ln.EASINGMODE_EASEIN=0;ln.EASINGMODE_EASEOUT=1;ln.EASINGMODE_EASEINOUT=2;class Vw extends ln{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Uw extends ln{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 kw extends ln{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 Gw extends ln{easeInCore(e){return e*e}}class vb extends ln{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class zw{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class ml{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let t=0;tn&&(n=l.to);const a=new ml(e[0].name+"_merged",e[0]._scene,s);for(const l of e){i&&l.normalize(r,n);for(const h of l.targetedAnimations)a.addTargetedAnimation(h.animation,h.target);t&&l.dispose()}return a}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new he,this.onAnimationLoopObservable=new he,this.onAnimationGroupLoopObservable=new he,this.onAnimationGroupEndObservable=new he,this.onAnimationGroupPauseObservable=new he,this.onAnimationGroupPlayObservable=new he,this.metadata=null,this._animationLoopFlags=[],this._scene=t||ht.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new zw;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-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;ie){const l={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,l)}if(a.frame{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.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(l)},this._processLoop(l,a,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;e0&&(this._scene._activeAnimatables[t++]=s)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-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 ml(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_[0].frame&&(h=_[0].frame),c<_[_.length-1].frame&&(c=_[_.length-1].frame)}a._from=h,a._to=c}return a}static ClipKeys(e,t,i,s,r){const n=e.clone(s||e.name);return ml.ClipKeysInPlace(n,t,i,r)}static ClipKeysInPlace(e,t,i,s){return ml.ClipInPlace(e,t,i,s,!1)}static ClipFrames(e,t,i,s,r){const n=e.clone(s||e.name);return ml.ClipFramesInPlace(n,t,i,r)}static ClipFramesInPlace(e,t,i,s){return ml.ClipInPlace(e,t,i,s,!0)}static ClipInPlace(e,t,i,s,r=!1){let n=Number.MAX_VALUE,a=-Number.MAX_VALUE;const l=e.targetedAnimations;for(let h=0;h=t&&_<=i||r&&g.frame>=t&&g.frame<=i){const v={frame:g.frame,value:g.value.clone?g.value.clone():g.value,inTangent:g.inTangent,outTangent:g.outTangent,interpolation:g.interpolation,lockedTangent:g.lockedTangent};p===Number.MAX_VALUE&&(p=v.frame),v.frame-=p,f.push(v)}}if(f.length===0){l.splice(h,1),h--;continue}n>f[0].frame&&(n=f[0].frame),a{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function Ww(o=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>o?(e=r,setTimeout(()=>{I_(t,i,s)},0)):I_(t,i,s)}}function xb(o,e,t,i,s){const r=()=>{let n;const a=l=>{l.done?t(l.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(o,a,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function fx(o,e){let t;return xb(o,I_,i=>t=i,i=>{throw i},e),t}function Tb(o,e,t){return new Promise((i,s)=>{xb(o,e,i,s,t)})}function Hw(o,e){return(...t)=>fx(o(...t),e)}class Na{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Na(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 Na(this.x,this.y,this.width,this.height)}}class et extends Mi{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,s;let r=0,n=0;if(this.mode===et.PERSPECTIVE_CAMERA)this.fovMode===et.FOVMODE_VERTICAL_FIXED?(n=this.minZ*2*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*n):(r=this.minZ*2*Math.tan(this.fov/2),n=r/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;r=((e=this.orthoRight)!==null&&e!==void 0?e:a)-((t=this.orthoLeft)!==null&&t!==void 0?t:-a),n=((i=this.orthoTop)!==null&&i!==void 0?i:l)-((s=this.orthoBottom)!==null&&s!==void 0?s:-l)}return r*n}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}constructor(e,t,i,s=!0){super(e,i),this._position=T.Zero(),this._upVector=T.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=et.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Na(0,0,1,1),this.layerMask=268435455,this.fovMode=et.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=et.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new he,this.onProjectionMatrixChangedObservable=new he,this.onAfterCheckInputsObservable=new he,this.onRestoreStateObservable=new he,this.isRigCamera=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new k,this._postProcesses=new Array,this._activeMeshes=new qs(256),this._globalPosition=T.Zero(),this._computedViewMatrix=k.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=k.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Se.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-1?(G.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 k.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const b=this.getEngine(),R=this.getScene(),I=b.useReverseDepthBuffer;if(this.mode===et.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=b.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let N;R.useRightHandedSystem?N=k.PerspectiveFovRHToRef:N=k.PerspectiveFovLHToRef,N(this.fov,b.getAspectRatio(this),I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===et.FOVMODE_VERTICAL_FIXED,b.isNDCHalfZRange,this.projectionPlaneTilt,I)}else{const N=b.getRenderWidth()/2,O=b.getRenderHeight()/2;R.useRightHandedSystem?this.oblique?k.ObliqueOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-N,(i=this.orthoRight)!==null&&i!==void 0?i:N,(s=this.orthoBottom)!==null&&s!==void 0?s:-O,(r=this.orthoTop)!==null&&r!==void 0?r:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):k.OrthoOffCenterRHToRef((n=this.orthoLeft)!==null&&n!==void 0?n:-N,(a=this.orthoRight)!==null&&a!==void 0?a:N,(l=this.orthoBottom)!==null&&l!==void 0?l:-O,(h=this.orthoTop)!==null&&h!==void 0?h:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange):this.oblique?k.ObliqueOffCenterLHToRef((c=this.orthoLeft)!==null&&c!==void 0?c:-N,(u=this.orthoRight)!==null&&u!==void 0?u:N,(d=this.orthoBottom)!==null&&d!==void 0?d:-O,(f=this.orthoTop)!==null&&f!==void 0?f:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):k.OrthoOffCenterLHToRef((p=this.orthoLeft)!==null&&p!==void 0?p:-N,(_=this.orthoRight)!==null&&_!==void 0?_:N,(g=this.orthoBottom)!==null&&g!==void 0?g:-O,(v=this.orthoTop)!==null&&v!==void 0?v:O,I?this.maxZ:this.minZ,I?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(E=this.oblique)===null||E===void 0?void 0:E.angle,this._cache.obliqueLength=(C=this.oblique)===null||C===void 0?void 0:C.length,this._cache.obliqueOffset=(S=this.oblique)===null||S===void 0?void 0:S.offset,this._cache.renderWidth=b.getRenderWidth(),this._cache.renderHeight=b.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?T.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Aa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Aa.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 xt("Ray")}getForwardRayToRef(e,t=100,i,s){throw xt("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!==et.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=fe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==et.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 k.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=fe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eet._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=et.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Xe.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=T.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(T.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(T.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{throw xt("UniversalCamera")};et.PERSPECTIVE_CAMERA=0;et.ORTHOGRAPHIC_CAMERA=1;et.FOVMODE_VERTICAL_FIXED=0;et.FOVMODE_HORIZONTAL_FIXED=1;et.RIG_MODE_NONE=0;et.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;et.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;et.RIG_MODE_STEREOSCOPIC_INTERLACED=14;et.RIG_MODE_VR=20;et.RIG_MODE_CUSTOM=22;et.ForceAttachControlToAlwaysPreventDefault=!1;A([kr("position")],et.prototype,"_position",void 0);A([kr("upVector")],et.prototype,"_upVector",void 0);A([D()],et.prototype,"orthoLeft",null);A([D()],et.prototype,"orthoRight",null);A([D()],et.prototype,"orthoBottom",null);A([D()],et.prototype,"orthoTop",null);A([D()],et.prototype,"fov",void 0);A([D()],et.prototype,"projectionPlaneTilt",void 0);A([D()],et.prototype,"minZ",void 0);A([D()],et.prototype,"maxZ",void 0);A([D()],et.prototype,"inertia",void 0);A([D()],et.prototype,"mode",null);A([D()],et.prototype,"layerMask",void 0);A([D()],et.prototype,"fovMode",void 0);A([D()],et.prototype,"cameraRigMode",void 0);A([D()],et.prototype,"interaxialDistance",void 0);A([D()],et.prototype,"isStereoscopicSideBySide",void 0);class wv{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Eo{constructor(e,t,i){this.vectors=js.BuildArray(8,T.Zero),this.center=T.Zero(),this.centerWorld=T.Zero(),this.extendSize=T.Zero(),this.extendSizeWorld=T.Zero(),this.directions=js.BuildArray(3,T.Zero),this.vectorsWorld=js.BuildArray(8,T.Zero),this.minimumWorld=T.Zero(),this.maximumWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,l,h),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(a,l,h),c[2].copyFromFloats(a,r,n),c[3].copyFromFloats(s,l,n),c[4].copyFromFloats(s,r,h),c[5].copyFromFloats(a,l,n),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||k.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Eo._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),a=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(a,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 a=0;a<8;++a)r[a].copyFrom(n[a]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let a=0;a<8;++a){const l=r[a];T.TransformCoordinatesToRef(n[a],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}T.FromArrayToRef(e.m,0,s[0]),T.FromArrayToRef(e.m,4,s[1]),T.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Eo.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Eo.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,a=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,f=-$t;return!(a-cc-s||l-uu-r||h-dd-n)}intersectsSphere(e){return Eo.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,l=s.x,h=s.y,c=s.z,u=e.x,d=e.y,f=e.z,p=t.x,_=t.y,g=t.z;return!(lp||h_||cg)}dispose(){var e,t;(e=this._drawWrapperFront)===null||e===void 0||e.dispose(),(t=this._drawWrapperBack)===null||t===void 0||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Eo._TmpVector3[0];return T.ClampToRef(i,e,t,r),T.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}}Eo._TmpVector3=js.BuildArray(3,T.Zero);class Rl{constructor(e,t,i){this.center=T.Zero(),this.centerWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=T.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||k.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Rl._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{T.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Rl._TmpVector3[0];T.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=T.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=T.Dot(e.centerWorld,o),s=Math.abs(T.Dot(e.directions[0],o))*e.extendSize.x,r=Math.abs(T.Dot(e.directions[1],o))*e.extendSize.y,n=Math.abs(T.Dot(e.directions[2],o))*e.extendSize.z,a=s+r+n;t.min=i-a,t.max=i+a},Vn=(o,e,t)=>(i0(o,e,ov),i0(o,t,lv),!(ov.min>lv.max||lv.min>ov.max));class ha{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Eo(e,t,i),this.boundingSphere=new Rl(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=ha._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=ha._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=T.Minimize(this.minimum,e),i=T.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=K.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=K.Vector3[0];return T.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),T.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,ha._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(!Rl.Intersects(this.boundingSphere,e.boundingSphere)||!Eo.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!Vn(i.directions[0],i,s)||!Vn(i.directions[1],i,s)||!Vn(i.directions[2],i,s)||!Vn(s.directions[0],i,s)||!Vn(s.directions[1],i,s)||!Vn(s.directions[2],i,s)||!Vn(T.Cross(i.directions[0],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[0],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[0],s.directions[2]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[1],s.directions[2]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[0]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[1]),i,s)||!Vn(T.Cross(i.directions[2],s.directions[2]),i,s))}}ha._TmpVector3=js.BuildArray(2,T.Zero);class Z_{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a!Array.isArray(o)&&!Array.isArray(e))],Z_,"extractMinAndMaxIndexed",null);A([ch.filter((...[o])=>!Array.isArray(o))],Z_,"extractMinAndMax",null);function Xw(o,e,t,i,s=null){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Z_.extractMinAndMaxIndexed(o,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 Rd(o,e,t,i=null,s){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),Z_.extractMinAndMax(o,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 on{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())===null||e===void 0?void 0:e.defines}set materialDefines(e){var t;const i=(t=this._mainDrawWrapperOverride)!==null&&t!==void 0?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Or(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])===null||i===void 0||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())===null||e===void 0?void 0:e.effect)!==null&&t!==void 0?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!==null&&e!==void 0?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,a,l=!0){return new on(e,t,i,s,r,n,a,l)}constructor(e,t,i,s,r,n,a,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=a||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){var t;const i=(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!==null&&t!==void 0?t:this._renderingMesh.material;if(i){if(this._isMultiMaterial(i)){const s=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return i}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(P.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=Xw(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ha(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let s=this.indexStart;sl&&(l=d)}return new on(e,a,l-a+1,t,i,s,r,n)}}class g_{}class Oe{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Hw(this._applyToCoroutine.bind(this)),this.uniqueId=Oe._UniqueIDGenerator,Oe._UniqueIDGenerator++}set(e,t){switch(e.length||G.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case P.PositionKind:this.positions=e;break;case P.NormalKind:this.normals=e;break;case P.TangentKind:this.tangents=e;break;case P.UVKind:this.uvs=e;break;case P.UV2Kind:this.uvs2=e;break;case P.UV3Kind:this.uvs3=e;break;case P.UV4Kind:this.uvs4=e;break;case P.UV5Kind:this.uvs5=e;break;case P.UV6Kind:this.uvs6=e;break;case P.ColorKind:this.colors=e;break;case P.MatricesIndicesKind:this.matricesIndices=e;break;case P.MatricesWeightsKind:this.matricesWeights=e;break;case P.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case P.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(P.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(P.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(P.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(P.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(P.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(P.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(P.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(P.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(P.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(P.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(P.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(P.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(P.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 on(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(P.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(P.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(P.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(P.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(P.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(P.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(P.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(P.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(P.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(P.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(P.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(P.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(P.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=K.Vector3[0],n=K.Vector3[1];for(let a=i;a({vertexData:a})):[{vertexData:e}];return fx(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,a=!1){var l,h,c,u;this._validate();let d=t.map(v=>v.vertexData),f=this;if(a)for(const v of d)v&&(v._validate(),!this.normals&&v.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&v.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&v.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&v.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&v.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&v.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&v.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&v.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&v.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&v.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&v.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&v.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&v.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const v of d)if(v){if(a)this.normals&&!v.normals&&(v.normals=new Float32Array(v.positions.length)),this.tangents&&!v.tangents&&(v.tangents=new Float32Array(v.positions.length/3*4)),this.uvs&&!v.uvs&&(v.uvs=new Float32Array(v.positions.length/3*2)),this.uvs2&&!v.uvs2&&(v.uvs2=new Float32Array(v.positions.length/3*2)),this.uvs3&&!v.uvs3&&(v.uvs3=new Float32Array(v.positions.length/3*2)),this.uvs4&&!v.uvs4&&(v.uvs4=new Float32Array(v.positions.length/3*2)),this.uvs5&&!v.uvs5&&(v.uvs5=new Float32Array(v.positions.length/3*2)),this.uvs6&&!v.uvs6&&(v.uvs6=new Float32Array(v.positions.length/3*2)),this.colors&&!v.colors&&(v.colors=new Float32Array(v.positions.length/3*4),v.colors.fill(1)),this.matricesIndices&&!v.matricesIndices&&(v.matricesIndices=new Float32Array(v.positions.length/3*4)),this.matricesWeights&&!v.matricesWeights&&(v.matricesWeights=new Float32Array(v.positions.length/3*4)),this.matricesIndicesExtra&&!v.matricesIndicesExtra&&(v.matricesIndicesExtra=new Float32Array(v.positions.length/3*4)),this.matricesWeightsExtra&&!v.matricesWeightsExtra&&(v.matricesWeightsExtra=new Float32Array(v.positions.length/3*4));else if(v._validate(),!this.normals!=!v.normals||!this.tangents!=!v.tangents||!this.uvs!=!v.uvs||!this.uvs2!=!v.uvs2||!this.uvs3!=!v.uvs3||!this.uvs4!=!v.uvs4||!this.uvs5!=!v.uvs5||!this.uvs6!=!v.uvs6||!this.colors!=!v.colors||!this.matricesIndices!=!v.matricesIndices||!this.matricesWeights!=!v.matricesWeights||!this.matricesIndicesExtra!=!v.matricesIndicesExtra||!this.matricesWeightsExtra!=!v.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let v=0,E=0,C=0;const S=[];let b=null;const R=[];for(const N of this.splitBasedOnMaterialID())R.push({vertexData:N,transform:e});for(const N of t)if(N.vertexData)for(const O of N.vertexData.splitBasedOnMaterialID())R.push({vertexData:O,transform:N.transform});R.sort((N,O)=>{const L=N.vertexData.materialInfos?N.vertexData.materialInfos[0].materialIndex:0,B=O.vertexData.materialInfos?O.vertexData.materialInfos[0].materialIndex:0;return L>B?1:L===B?0:-1});for(const N of R){const O=N.vertexData;if(O.materialInfos?v=O.materialInfos[0].materialIndex:v=0,b&&b.materialIndex===v)b.indexCount+=O.indices.length,b.verticesCount+=O.positions.length/3;else{const L=new g_;L.materialIndex=v,L.indexStart=E,L.indexCount=O.indices.length,L.verticesStart=C,L.verticesCount=O.positions.length/3,S.push(L),b=L}E+=O.indices.length,C+=O.positions.length/3}const I=R.splice(0,1)[0];f=I.vertexData,e=I.transform,d=R.map(N=>N.vertexData),t=R,this.materialInfos=S}const p=d.reduce((v,E)=>{var C,S;return v+((S=(C=E.indices)===null||C===void 0?void 0:C.length)!==null&&S!==void 0?S:0)},(h=(l=f.indices)===null||l===void 0?void 0:l.length)!==null&&h!==void 0?h:0);let g=r||d.some(v=>v.indices===f.indices)?(c=f.indices)===null||c===void 0?void 0:c.slice():f.indices;if(p>0){let v=(u=g==null?void 0:g.length)!==null&&u!==void 0?u:0;if(g||(g=new Array(p)),g.length!==p){if(Array.isArray(g))g.length=p;else{const C=i||g instanceof Uint32Array?new Uint32Array(p):new Uint16Array(p);C.set(g),g=C}e&&e.determinant()<0&&Oe._FlipFaces(g,0,v)}let E=f.positions?f.positions.length/3:0;for(const{vertexData:C,transform:S}of t)if(C.indices){for(let b=0;b[v.vertexData.positions,v.transform])),s&&(yield),f.normals&&(this.normals=Oe._MergeElement(P.NormalKind,f.normals,e,t.map(v=>[v.vertexData.normals,v.transform])),s&&(yield)),f.tangents&&(this.tangents=Oe._MergeElement(P.TangentKind,f.tangents,e,t.map(v=>[v.vertexData.tangents,v.transform])),s&&(yield)),f.uvs&&(this.uvs=Oe._MergeElement(P.UVKind,f.uvs,e,t.map(v=>[v.vertexData.uvs,v.transform])),s&&(yield)),f.uvs2&&(this.uvs2=Oe._MergeElement(P.UV2Kind,f.uvs2,e,t.map(v=>[v.vertexData.uvs2,v.transform])),s&&(yield)),f.uvs3&&(this.uvs3=Oe._MergeElement(P.UV3Kind,f.uvs3,e,t.map(v=>[v.vertexData.uvs3,v.transform])),s&&(yield)),f.uvs4&&(this.uvs4=Oe._MergeElement(P.UV4Kind,f.uvs4,e,t.map(v=>[v.vertexData.uvs4,v.transform])),s&&(yield)),f.uvs5&&(this.uvs5=Oe._MergeElement(P.UV5Kind,f.uvs5,e,t.map(v=>[v.vertexData.uvs5,v.transform])),s&&(yield)),f.uvs6&&(this.uvs6=Oe._MergeElement(P.UV6Kind,f.uvs6,e,t.map(v=>[v.vertexData.uvs6,v.transform])),s&&(yield)),f.colors&&(this.colors=Oe._MergeElement(P.ColorKind,f.colors,e,t.map(v=>[v.vertexData.colors,v.transform])),s&&(yield)),f.matricesIndices&&(this.matricesIndices=Oe._MergeElement(P.MatricesIndicesKind,f.matricesIndices,e,t.map(v=>[v.vertexData.matricesIndices,v.transform])),s&&(yield)),f.matricesWeights&&(this.matricesWeights=Oe._MergeElement(P.MatricesWeightsKind,f.matricesWeights,e,t.map(v=>[v.vertexData.matricesWeights,v.transform])),s&&(yield)),f.matricesIndicesExtra&&(this.matricesIndicesExtra=Oe._MergeElement(P.MatricesIndicesExtraKind,f.matricesIndicesExtra,e,t.map(v=>[v.vertexData.matricesIndicesExtra,v.transform])),s&&(yield)),f.matricesWeightsExtra&&(this.matricesWeightsExtra=Oe._MergeElement(P.MatricesWeightsExtraKind,f.matricesWeightsExtra,e,t.map(v=>[v.vertexData.matricesWeightsExtra,v.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),a=e===P.PositionKind?Oe._TransformVector3Coordinates:e===P.NormalKind?Oe._TransformVector3Normals:e===P.TangentKind?Oe._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(n);l.set(t),i&&a(l,i,0,t.length);let h=t.length;for(const[c,u]of r)l.set(c,h),u&&a(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(n);for(let c=0;c{const n=P.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(P.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(P.NormalKind,this.normals),this.tangents&&i(P.TangentKind,this.tangents),this.uvs&&i(P.UVKind,this.uvs),this.uvs2&&i(P.UV2Kind,this.uvs2),this.uvs3&&i(P.UV3Kind,this.uvs3),this.uvs4&&i(P.UV4Kind,this.uvs4),this.uvs5&&i(P.UV5Kind,this.uvs5),this.uvs6&&i(P.UV6Kind,this.uvs6),this.colors&&i(P.ColorKind,this.colors),this.matricesIndices&&i(P.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(P.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(P.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(P.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Oe.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)),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 Oe._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Oe._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Oe;return e.isVerticesDataPresent(P.PositionKind)&&(s.positions=e.getVerticesData(P.PositionKind,t,i)),e.isVerticesDataPresent(P.NormalKind)&&(s.normals=e.getVerticesData(P.NormalKind,t,i)),e.isVerticesDataPresent(P.TangentKind)&&(s.tangents=e.getVerticesData(P.TangentKind,t,i)),e.isVerticesDataPresent(P.UVKind)&&(s.uvs=e.getVerticesData(P.UVKind,t,i)),e.isVerticesDataPresent(P.UV2Kind)&&(s.uvs2=e.getVerticesData(P.UV2Kind,t,i)),e.isVerticesDataPresent(P.UV3Kind)&&(s.uvs3=e.getVerticesData(P.UV3Kind,t,i)),e.isVerticesDataPresent(P.UV4Kind)&&(s.uvs4=e.getVerticesData(P.UV4Kind,t,i)),e.isVerticesDataPresent(P.UV5Kind)&&(s.uvs5=e.getVerticesData(P.UV5Kind,t,i)),e.isVerticesDataPresent(P.UV6Kind)&&(s.uvs6=e.getVerticesData(P.UV6Kind,t,i)),e.isVerticesDataPresent(P.ColorKind)&&(s.colors=e.getVerticesData(P.ColorKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(P.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(P.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(P.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(P.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw xt("ribbonBuilder")}static CreateBox(e){throw xt("boxBuilder")}static CreateTiledBox(e){throw xt("tiledBoxBuilder")}static CreateTiledPlane(e){throw xt("tiledPlaneBuilder")}static CreateSphere(e){throw xt("sphereBuilder")}static CreateCylinder(e){throw xt("cylinderBuilder")}static CreateTorus(e){throw xt("torusBuilder")}static CreateLineSystem(e){throw xt("linesBuilder")}static CreateDashedLines(e){throw xt("linesBuilder")}static CreateGround(e){throw xt("groundBuilder")}static CreateTiledGround(e){throw xt("groundBuilder")}static CreateGroundFromHeightMap(e){throw xt("groundBuilder")}static CreatePlane(e){throw xt("planeBuilder")}static CreateDisc(e){throw xt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,a){throw xt("polygonBuilder")}static CreateIcoSphere(e){throw xt("icoSphereBuilder")}static CreatePolyhedron(e){throw xt("polyhedronBuilder")}static CreateCapsule(e={orientation:T.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw xt("capsuleBuilder")}static CreateTorusKnot(e){throw xt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,a=0,l=0,h=0,c=0,u=0,d=0,f=0,p=0,_=0,g=0,v=0,E=0,C=0,S=0,b=0,R=0,I=0,N=0,O=!1,L=!1,B=!1,V=!1,Z=1,ue=0,oe=null;s&&(O=!!s.facetNormals,L=!!s.facetPositions,B=!!s.facetPartitioning,Z=s.useRightHandedSystem===!0?-1:1,ue=s.ratio||0,V=!!s.depthSort,oe=s.distanceTo,V&&oe===void 0&&(oe=T.Zero()));let me=0,le=0,ae=0,ce=0;for(B&&s&&s.bbSize&&(me=s.subDiv.X*ue/s.bbSize.x,le=s.subDiv.Y*ue/s.bbSize.y,ae=s.subDiv.Z*ue/s.bbSize.z,ce=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(o))],Oe,"_TransformVector3Coordinates",null);A([ch.filter((...[o])=>!Array.isArray(o))],Oe,"_TransformVector3Normals",null);A([ch.filter((...[o])=>!Array.isArray(o))],Oe,"_TransformVector4Normals",null);A([ch.filter((...[o])=>!Array.isArray(o))],Oe,"_FlipFaces",null);class nr{static get ForceFullSceneLoadingForIncremental(){return nr._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nr._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nr._ShowLoadingScreen}static set ShowLoadingScreen(e){nr._ShowLoadingScreen=e}static get loggingLevel(){return nr._LoggingLevel}static set loggingLevel(e){nr._LoggingLevel=e}static get CleanBoneMatrixWeights(){return nr._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nr._CleanBoneMatrixWeights=e}}nr._ForceFullSceneLoadingForIncremental=!1;nr._ShowLoadingScreen=!0;nr._CleanBoneMatrixWeights=!1;nr._LoggingLevel=0;class pi{}pi.UseOpenGLOrientationForUV=!1;class sn{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 sn(sn.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||ht.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;e65535);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)),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(P.PositionKind),!e))return;this._extend=Rd(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===P.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let n=0;n0){for(let s=0;s0){for(let s=0;s0){for(let s=0;s-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Oe;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const a=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(P.PositionKind,a,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const a=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(P.NormalKind,a,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const a=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(P.TangentKind,a,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const a=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(pi.UseOpenGLOrientationForUV)for(let l=1;l0){const a=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(P.ColorKind,a,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesKind,l,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,l,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const a=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(P.MatricesWeightsKind,a,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const a=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(a,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const a=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(P.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let a=0;a>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(sn._CleanMatricesWeights(e,t),t.setVerticesData(P.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(P.MatricesIndicesKind),n=t.getVerticesData(P.MatricesIndicesExtraKind),a=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=a.length;for(let u=0;uh-1)&&(f=h-1),d>.001){const p=1/d;for(let _=0;_<4;_++)a[u+_]*=p;if(l)for(let _=0;_<4;_++)l[u+_]*=p}else f>=4?(l[u+f-4]=1-d,n[u+f-4]=s):(a[u+f]=1-d,r[u+f]=s)}t.setVerticesData(P.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new sn(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ui&&ui.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new ha(T.FromArray(e.boundingBoxMinimum),T.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(P.UVKind),e.hasUVs2&&s._delayInfo.push(P.UV2Kind),e.hasUVs3&&s._delayInfo.push(P.UV3Kind),e.hasUVs4&&s._delayInfo.push(P.UV4Kind),e.hasUVs5&&s._delayInfo.push(P.UV5Kind),e.hasUVs6&&s._delayInfo.push(P.UV6Kind),e.hasColors&&s._delayInfo.push(P.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(P.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(P.MatricesWeightsKind),s._delayLoadingFunction=Oe.ImportVertexData):Oe.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Yw{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new $w(e)}sampleFrame(e=ar.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 $w{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}}We.prototype.setAlphaConstants=function(o,e,t,i){this._alphaState.setAlphaBlendConstants(o,e,t,i)};We.prototype.setAlphaMode=function(o,e=!1){if(this._alphaMode===o){if(!e){const t=o===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(o){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=o===0),this._alphaMode=o};We.prototype.getAlphaMode=function(){return this._alphaMode};We.prototype.setAlphaEquation=function(o){if(this._alphaEquation!==o){switch(o){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=o}};We.prototype.getAlphaEquation=function(){return this._alphaEquation};function Fv(o,e,t=!1,i){switch(o){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}We.prototype._readTexturePixelsSync=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,l=0,h=0){var c,u;const d=this._gl;if(!d)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const p=d.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),i>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+i,(c=o._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,(u=o._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,s);let f=o.type!==void 0?this._getWebGLTextureType(o.type):d.UNSIGNED_BYTE;if(a)r||(r=Fv(o.type,4*e*t));else switch(f){case d.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),f=d.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),f=d.FLOAT;break}return n&&this.flushFramebuffer(),d.readPixels(l,h,e,t,d.RGBA,f,r),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),r};We.prototype._readTexturePixels=function(o,e,t,i=-1,s=0,r=null,n=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(o,e,t,i,s,r,n,a,l,h))};We.prototype.updateDynamicIndexBuffer=function(o,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(o);let i;o.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()};We.prototype.updateDynamicVertexBuffer=function(o,e,t,i){this.bindArrayBuffer(o),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 re extends We{static get NpmPackage(){return We.NpmPackage}static get Version(){return We.Version}static get Instances(){return ht.Instances}static get LastCreatedEngine(){return ht.LastCreatedEngine}static get LastCreatedScene(){return ht.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{this.createImageBitmap(n,t).then(a=>{s(a)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const r=this.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{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(),!re.audioEngine&&this._creationOptions.audioEngine&&re.AudioEngineFactory&&(re.audioEngine=re.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Zu()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&re._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=re.OfflineProviderFactory!==void 0,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;(e=this._onPointerLockChange)===null||e===void 0||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((s,r)=>{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,a)=>{r(a)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){var s;let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s=r==null?void 0:r.texture)!==null&&s!==void 0?s:null,i)}setTextureFromPostProcessOutput(e,t,i){var s,r;this._bindTexture(e,(r=(s=t==null?void 0:t._outputTexture)===null||s===void 0?void 0:s.texture)!==null&&r!==void 0?r:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&re._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&re._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&re._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){re._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;s1&&r){const a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=a}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(i=>{i._outputTexture===e&&(i._outputTexture=null)}),t.cameras.forEach(i=>{i._postProcesses.forEach(s=>{s&&s._outputTexture===e&&(s._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++re._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new uu(e,this._gl),a=new Ti(this,Ut.Unknown,!0);return a._hardwareTexture=n,a.baseWidth=s,a.baseHeight=r,a.width=s,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,s,l,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){G.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 bd(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise((r,n)=>{const a=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){n();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(a,i);return}r()};a()})}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,a.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,a),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();ht.Instances.length===1&&re.audioEngine&&(re.audioEngine.dispose(),re.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)),Zu()&&(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=ht.Instances.indexOf(this);t>=0&&ht.Instances.splice(t,1),re.Instances.length||ht.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(!gr())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!gr())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=re.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}}}re.ALPHA_DISABLE=0;re.ALPHA_ADD=1;re.ALPHA_COMBINE=2;re.ALPHA_SUBTRACT=3;re.ALPHA_MULTIPLY=4;re.ALPHA_MAXIMIZED=5;re.ALPHA_ONEONE=6;re.ALPHA_PREMULTIPLIED=7;re.ALPHA_PREMULTIPLIED_PORTERDUFF=8;re.ALPHA_INTERPOLATE=9;re.ALPHA_SCREENMODE=10;re.DELAYLOADSTATE_NONE=0;re.DELAYLOADSTATE_LOADED=1;re.DELAYLOADSTATE_LOADING=2;re.DELAYLOADSTATE_NOTLOADED=4;re.NEVER=512;re.ALWAYS=519;re.LESS=513;re.EQUAL=514;re.LEQUAL=515;re.GREATER=516;re.GEQUAL=518;re.NOTEQUAL=517;re.KEEP=7680;re.REPLACE=7681;re.INCR=7682;re.DECR=7683;re.INVERT=5386;re.INCR_WRAP=34055;re.DECR_WRAP=34056;re.TEXTURE_CLAMP_ADDRESSMODE=0;re.TEXTURE_WRAP_ADDRESSMODE=1;re.TEXTURE_MIRROR_ADDRESSMODE=2;re.TEXTUREFORMAT_ALPHA=0;re.TEXTUREFORMAT_LUMINANCE=1;re.TEXTUREFORMAT_LUMINANCE_ALPHA=2;re.TEXTUREFORMAT_RGB=4;re.TEXTUREFORMAT_RGBA=5;re.TEXTUREFORMAT_RED=6;re.TEXTUREFORMAT_R=6;re.TEXTUREFORMAT_RG=7;re.TEXTUREFORMAT_RED_INTEGER=8;re.TEXTUREFORMAT_R_INTEGER=8;re.TEXTUREFORMAT_RG_INTEGER=9;re.TEXTUREFORMAT_RGB_INTEGER=10;re.TEXTUREFORMAT_RGBA_INTEGER=11;re.TEXTURETYPE_UNSIGNED_BYTE=0;re.TEXTURETYPE_UNSIGNED_INT=0;re.TEXTURETYPE_FLOAT=1;re.TEXTURETYPE_HALF_FLOAT=2;re.TEXTURETYPE_BYTE=3;re.TEXTURETYPE_SHORT=4;re.TEXTURETYPE_UNSIGNED_SHORT=5;re.TEXTURETYPE_INT=6;re.TEXTURETYPE_UNSIGNED_INTEGER=7;re.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;re.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;re.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;re.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;re.TEXTURETYPE_UNSIGNED_INT_24_8=12;re.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;re.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;re.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;re.TEXTURE_NEAREST_SAMPLINGMODE=1;re.TEXTURE_BILINEAR_SAMPLINGMODE=2;re.TEXTURE_TRILINEAR_SAMPLINGMODE=3;re.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;re.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;re.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;re.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;re.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;re.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;re.TEXTURE_NEAREST_LINEAR=7;re.TEXTURE_NEAREST_NEAREST=1;re.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;re.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;re.TEXTURE_LINEAR_LINEAR=2;re.TEXTURE_LINEAR_NEAREST=12;re.TEXTURE_EXPLICIT_MODE=0;re.TEXTURE_SPHERICAL_MODE=1;re.TEXTURE_PLANAR_MODE=2;re.TEXTURE_CUBIC_MODE=3;re.TEXTURE_PROJECTION_MODE=4;re.TEXTURE_SKYBOX_MODE=5;re.TEXTURE_INVCUBIC_MODE=6;re.TEXTURE_EQUIRECTANGULAR_MODE=7;re.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;re.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;re.SCALEMODE_FLOOR=1;re.SCALEMODE_NEAREST=2;re.SCALEMODE_CEILING=3;re._RescalePostProcessFactory=null;re._RenderPassIdCounter=0;const Kw=k.Compose(T.One(),Se.FromEulerAngles(0,Math.PI,0),T.Zero());class It extends Mi{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&It.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!==It.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 T(0,0,1),this._up=new T(0,1,0),this._right=new T(1,0,0),this._position=T.Zero(),this._rotation=T.Zero(),this._rotationQuaternion=null,this._scaling=T.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=It.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=k.Zero(),this._usePivotMatrix=!1,this._absolutePosition=T.Zero(),this._absoluteScaling=T.Zero(),this._absoluteRotationQuaternion=Se.Identity(),this._pivotMatrix=k.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new he,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 T.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return T.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return T.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=k.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==It.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=k.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||Se.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=K.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),T.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=T.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=K.Matrix[0];return this._localMatrix.invertToRef(e),T.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=T.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=_i.LOCAL){const n=It._LookAtVectorCache,a=r===_i.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===_i.WORLD&&this.parent)if(this.rotationQuaternion){const l=K.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=K.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=K.Quaternion[0];Se.FromEulerVectorToRef(this.rotation,l);const h=K.Matrix[0];l.toRotationMatrix(h);const c=K.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=T.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return T.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?Se.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=_i.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==_i.WORLD){const s=K.Matrix[0];i.invertToRef(s),e=T.TransformCoordinates(e,s)}return this.setPivotMatrix(k.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=T.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=T.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),T.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=K.Quaternion[0],r=K.Vector3[0],n=K.Vector3[1],a=K.Matrix[1];k.IdentityToRef(a);const l=K.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=It._TmpRotation,Se.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),k.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(a),l.multiplyToRef(a,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(k.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===_i.LOCAL)s=Se.RotationAxisToRef(e,t,It._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=this.parent.getWorldMatrix(),n=K.Matrix[0];r.invertToRef(n),e=T.TransformNormal(e,n),r.determinant()<0&&(t*=-1)}s=Se.RotationAxisToRef(e,t,It._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Se.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=K.Vector3[0],r=K.Vector3[1],n=K.Vector3[2],a=K.Quaternion[0],l=K.Matrix[0],h=K.Matrix[1],c=K.Matrix[2],u=K.Matrix[3];return e.subtractToRef(this.position,s),k.TranslationToRef(s.x,s.y,s.z,l),k.TranslationToRef(-s.x,-s.y,-s.z,h),k.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===_i.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=K.Quaternion[1],Se.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=K.Quaternion[0];return Se.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!==It.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=It._TmpScaling;let a=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new T(h.m[12],h.m[13],h.m[14]);a=It._TmpTranslation,a.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Se.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=It._TmpRotation,Se.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=K.Matrix[1];k.ScalingToRef(n.x,n.y,n.z,h);const c=K.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,K.Matrix[4]),K.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else k.ComposeToRef(n,l,a,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(),K.Matrix[7])}else K.Matrix[7].copyFrom(r.getWorldMatrix());const h=K.Vector3[5],c=K.Vector3[6],u=K.Quaternion[0];K.Matrix[7].decompose(c,u,h),k.ScalingToRef(c.x,c.y,c.z,K.Matrix[7]),K.Matrix[7].setTranslation(h),It.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(K.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const h=this.parent;h.getSkeleton().prepare(),this._localMatrix.multiplyToRef(h.getFinalMatrix(),K.Matrix[6]),K.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=K.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),K.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&K.Matrix[1].multiplyToRef(Kw,K.Matrix[1]),K.Matrix[1].setTranslationFromFloats(0,0,0),K.Matrix[1].invertToRef(K.Matrix[0]),(this.billboardMode&It.BILLBOARDMODE_ALL)!==It.BILLBOARDMODE_ALL){K.Matrix[0].decompose(void 0,K.Quaternion[0],void 0);const c=K.Vector3[1];K.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&It.BILLBOARDMODE_X)!==It.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&It.BILLBOARDMODE_Y)!==It.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&It.BILLBOARDMODE_Z)!==It.BILLBOARDMODE_Z&&(c.z=0),k.RotationYawPitchRollToRef(c.y,c.x,c.z,K.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(K.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(K.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=K.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(K.Matrix[1]);const u=K.Vector3[1];T.TransformCoordinatesToRef(c,K.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),p=-Math.atan2(u.y,f);if(Se.RotationYawPitchRollToRef(d,p,0,K.Quaternion[0]),(this.billboardMode&It.BILLBOARDMODE_ALL)!==It.BILLBOARDMODE_ALL){const _=K.Vector3[1];K.Quaternion[0].toEulerAnglesToRef(_),(this.billboardMode&It.BILLBOARDMODE_X)!==It.BILLBOARDMODE_X&&(_.x=0),(this.billboardMode&It.BILLBOARDMODE_Y)!==It.BILLBOARDMODE_Y&&(_.y=0),(this.billboardMode&It.BILLBOARDMODE_Z)!==It.BILLBOARDMODE_Z&&(_.z=0),k.RotationYawPitchRollToRef(_.y,_.x,_.z,K.Matrix[0])}else k.FromQuaternionToRef(K.Quaternion[0],K.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(K.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(K.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=k.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew It(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;nnew It(e.name,t),e,t,i);return e.localMatrix?s.setPreTransformMatrix(k.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(k.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof It),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),l=Math.max(a.x,a.y,a.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)}}It.BILLBOARDMODE_NONE=0;It.BILLBOARDMODE_X=1;It.BILLBOARDMODE_Y=2;It.BILLBOARDMODE_Z=4;It.BILLBOARDMODE_ALL=7;It.BILLBOARDMODE_USE_POSITION=128;It.BillboardUseParentOrientation=!1;It._TmpRotation=Se.Zero();It._TmpScaling=T.Zero();It._TmpTranslation=T.Zero();It._LookAtVectorCache=new T(0,0,0);It._RotationAxisCache=new Se;A([kr("position")],It.prototype,"_position",void 0);A([kr("rotation")],It.prototype,"_rotation",void 0);A([sw("rotationQuaternion")],It.prototype,"_rotationQuaternion",void 0);A([kr("scaling")],It.prototype,"_scaling",void 0);A([D("billboardMode")],It.prototype,"_billboardMode",void 0);A([D()],It.prototype,"scalingDeterminant",void 0);A([D("infiniteDistance")],It.prototype,"_infiniteDistance",void 0);A([D()],It.prototype,"ignoreNonUniformScaling",void 0);A([D()],It.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class qw{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new T(0,0,0),this._diffPositionForCollisions=new T(0,0,0),this._collisionResponse=!0}}class jw{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=T.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Qw{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new jw,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 qw,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class hi extends It{static get BILLBOARDMODE_NONE(){return It.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return It.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return It.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return It.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return It.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return It.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)===null||t===void 0?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Qw,this._waitingMaterialId=null,this.cullingStrategy=hi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new he,this.onCollisionPositionChangeObservable=new he,this.onMaterialChangedObservable=new he,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=Te.Red(),this.outlineWidth=.02,this.overlayColor=Te.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 T(.5,1,.5),this.ellipsoidOffset=new T(0,0,0),this.edgesWidth=1,this.edgesColor=new Ze(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 he,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>re.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 it(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Xo.Aggressive:this.doNotSyncBoundingInfo=!0;case Xo.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!==It.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes)for(const t of this.subMeshes)t._rebuild()}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!==null&&e!==void 0?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new ha(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(P.MatricesIndicesKind)&&this.isVerticesDataPresent(P.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===It.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 k;(this.rotationQuaternion?this.rotationQuaternion:Se.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=T.Zero(),a=this.definedFacingForward?-1:1;return T.TransformCoordinatesFromFloatsToRef(e*a,t,i*a,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new T(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=Rd(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new ha(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i4,l=a?this.getVerticesData(P.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(P.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=K.Vector3[0],d=K.Matrix[0],f=K.Matrix[1];let p=0;for(let _=0;_0&&(k.FromFloat32ArrayToRefScaled(c,Math.floor(r[p+g]*16),v,f),d.addToSelf(f));if(a)for(g=0;g<4;g++)v=h[p+g],v>0&&(k.FromFloat32ArrayToRefScaled(c,Math.floor(l[p+g]*16),v,f),d.addToSelf(f));s===P.NormalKind?T.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],d,u):T.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],d,u),u.toArray(i,_),s===P.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,P.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,P.PositionKind)}_getPositionData(e,t){var i;let s=this.getVerticesData(P.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),s&&(e&&this.skeleton||t&&this.morphTargetManager)){if(s=s.slice(),this._generatePointsArray(),this._positions){const r=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(r.length);for(let n=0;n1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var s;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const r=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let a=r;a1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=K.Matrix[0],i=K.Matrix[1];return k.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const a=new Vr,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 a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:T.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let p=!1;for(let _=0;_1&&!n&&!g.canIntersects(e))continue;const v=g.intersects(e,this._positions,this.getIndices(),t,i);if(v&&(t||!u||v.distancea!==this&&a.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let l=a.includedOnlyMeshes.indexOf(this);l!==-1&&a.includedOnlyMeshes.splice(l,1),l=a.excludedMeshes.indexOf(this),l!==-1&&a.excludedMeshes.splice(l,1);const h=a.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 a=this._parentContainer.meshes.indexOf(this);a>-1&&this._parentContainer.meshes.splice(a,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){a=!0;break}a?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(a,l){return l.sqDistance-a.sqDistance},!e.facetDepthSortFrom){const a=this.getScene().activeCamera;e.facetDepthSortFrom=a?a.position:T.Zero()}e.depthSortedFacets=[];for(let a=0;a$t?r.maximum.x-r.minimum.x:$t,e.bbSize.y=r.maximum.y-r.minimum.y>$t?r.maximum.y-r.minimum.y:$t,e.bbSize.z=r.maximum.z-r.minimum.z>$t?r.maximum.z-r.minimum.z:$t;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),T.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Oe.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const a=e.depthSortedIndices.length/3|0;for(let l=0;lr.subDiv.max||a<0||a>r.subDiv.max||l<0||l>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),l=K.Matrix[5];a.invertToRef(l);const h=K.Vector3[8];T.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&T.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,l=0,h=0,c=0,u=0,d=0,f=0,p=0,_=0;const g=this.getFacetLocalPositions(),v=this.getFacetLocalNormals(),E=this.getFacetsAtLocalCoordinates(e,t,i);if(!E)return null;let C=Number.MAX_VALUE,S=C,b,R,I;for(let N=0;N=0||r&&!n&&u<=0)&&(u=R.x*I.x+R.y*I.y+R.z*I.z,d=-(R.x*e+R.y*t+R.z*i-u)/(R.x*R.x+R.y*R.y+R.z*R.z),f=e+R.x*d,p=t+R.y*d,_=i+R.z*d,l=f-e,h=p-t,c=_-i,S=l*l+h*h+c*c,Se.emitter===this)}}hi.OCCLUSION_TYPE_NONE=0;hi.OCCLUSION_TYPE_OPTIMISTIC=1;hi.OCCLUSION_TYPE_STRICT=2;hi.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;hi.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;hi.CULLINGSTRATEGY_STANDARD=0;hi.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;hi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;hi.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;j("BABYLON.AbstractMesh",hi);function Ao(o){o.indexOf("vClipPlane")===-1&&o.push("vClipPlane"),o.indexOf("vClipPlane2")===-1&&o.push("vClipPlane2"),o.indexOf("vClipPlane3")===-1&&o.push("vClipPlane3"),o.indexOf("vClipPlane4")===-1&&o.push("vClipPlane4"),o.indexOf("vClipPlane5")===-1&&o.push("vClipPlane5"),o.indexOf("vClipPlane6")===-1&&o.push("vClipPlane6")}function xh(o,e,t){var i,s,r,n,a,l;const h=!!((i=o.clipPlane)!==null&&i!==void 0?i:e.clipPlane),c=!!((s=o.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),u=!!((r=o.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),d=!!((n=o.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),f=!!((a=o.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),p=!!((l=o.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);h&&t.push("#define CLIPPLANE"),c&&t.push("#define CLIPPLANE2"),u&&t.push("#define CLIPPLANE3"),d&&t.push("#define CLIPPLANE4"),f&&t.push("#define CLIPPLANE5"),p&&t.push("#define CLIPPLANE6")}function Zw(o,e,t){var i,s,r,n,a,l;let h=!1;const c=!!((i=o.clipPlane)!==null&&i!==void 0?i:e.clipPlane),u=!!((s=o.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),d=!!((r=o.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),f=!!((n=o.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),p=!!((a=o.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),_=!!((l=o.clipPlane6)!==null&&l!==void 0?l:e.clipPlane6);return t.CLIPPLANE!==c&&(t.CLIPPLANE=c,h=!0),t.CLIPPLANE2!==u&&(t.CLIPPLANE2=u,h=!0),t.CLIPPLANE3!==d&&(t.CLIPPLANE3=d,h=!0),t.CLIPPLANE4!==f&&(t.CLIPPLANE4=f,h=!0),t.CLIPPLANE5!==p&&(t.CLIPPLANE5=p,h=!0),t.CLIPPLANE6!==_&&(t.CLIPPLANE6=_,h=!0),h}function so(o,e,t){var i,s,r,n,a,l;let h=(i=e.clipPlane)!==null&&i!==void 0?i:t.clipPlane;Cc(o,"vClipPlane",h),h=(s=e.clipPlane2)!==null&&s!==void 0?s:t.clipPlane2,Cc(o,"vClipPlane2",h),h=(r=e.clipPlane3)!==null&&r!==void 0?r:t.clipPlane3,Cc(o,"vClipPlane3",h),h=(n=e.clipPlane4)!==null&&n!==void 0?n:t.clipPlane4,Cc(o,"vClipPlane4",h),h=(a=e.clipPlane5)!==null&&a!==void 0?a:t.clipPlane5,Cc(o,"vClipPlane5",h),h=(l=e.clipPlane6)!==null&&l!==void 0?l:t.clipPlane6,Cc(o,"vClipPlane6",h)}function Cc(o,e,t){t&&o.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}class Me{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==Qe.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,s,r,n,a,l=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=r&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=l)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===et.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===et.PERSPECTIVE_CAMERA?1:0;(s^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=n===1,t.CAMERA_PERSPECTIVE=a===1,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,s,r,n=null,a=!1){let l=Me.PrepareDefinesForCamera(e,s);n!==!1&&(l=Zw(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,l=!0),s.INSTANCES!==r&&(s.INSTANCES=r,l=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,l=!0),l&&s.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=t.BONETEXTURE!==void 0;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=i?!1:void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const r=s.excludedSkinnedMesh.indexOf(e)===-1;t.BONES_VELOCITY_ENABLED=r}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE!==void 0&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!(i&&i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,s,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(P.NormalKind),t._needNormals&&e.isVerticesDataPresent(P.TangentKind)&&(t.TANGENT=!0);for(let l=1;l<=6;++l)t["UV"+l]=t._needUVs?e.isVerticesDataPresent(`uv${l===1?"":l}`):!1;if(i){const l=e.useVertexColors&&e.isVerticesDataPresent(P.ColorKind);t.VERTEXCOLOR=l,t.VERTEXALPHA=e.hasVertexAlpha&&l&&n}return e.isVerticesDataPresent(P.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=e.activeCamera.outputRenderTarget!==null&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(s!==t.ORDER_INDEPENDENT_TRANSPARENCY||r!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let n=0;n0&&(a.shadowEnabled=!0,h.prepareDefines(r,s))}}i.lightmapMode!=Bi.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Bi.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}static PrepareDefinesForLights(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const l={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(const c of t.lightSources)if(this.PrepareDefinesForLight(e,t,c,a,i,s,l),a++,a===r)break}i.SPECULARTERM=l.specularEnabled,i.SHADOWS=l.shadowEnabled;for(let c=a;c0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&ht.LastCreatedEngine){const r=ht.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&i.NORMAL,l=n&&n.supportsTangents&&i.TANGENT,h=n&&n.supportsUVs&&i.UV1;for(let c=0;cr&&G.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push(P.MatricesIndicesKind),e.push(P.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(P.MatricesIndicesExtraKind),e.push(P.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(P.ColorInstanceKind)}static PushAttributesForInstances(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}static BindLights(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let a=0;a-1){const r=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",r),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const r=s.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),Me._CopyBonesTransformationMatrices(r,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;!e||!i||t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const s=i.activeCamera;s.mode===et.ORTHOGRAPHIC_CAMERA&&G.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}}}Me._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0};Me._TempFogColor=Te.Black();class Nl{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){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([D()],Nl.prototype,"func",null);A([D()],Nl.prototype,"funcRef",null);A([D()],Nl.prototype,"funcMask",null);A([D()],Nl.prototype,"opStencilFail",null);A([D()],Nl.prototype,"opDepthFail",null);A([D()],Nl.prototype,"opStencilDepthPass",null);A([D()],Nl.prototype,"mask",null);A([D()],Nl.prototype,"enabled",null);var Lr;(function(o){o[o.Created=1]="Created",o[o.Disposed=2]="Disposed",o[o.GetDefineNames=4]="GetDefineNames",o[o.PrepareUniformBuffer=8]="PrepareUniformBuffer",o[o.IsReadyForSubMesh=16]="IsReadyForSubMesh",o[o.PrepareDefines=32]="PrepareDefines",o[o.BindForSubMesh=64]="BindForSubMesh",o[o.PrepareEffect=128]="PrepareEffect",o[o.GetAnimatables=256]="GetAnimatables",o[o.GetActiveTextures=512]="GetActiveTextures",o[o.HasTexture=1024]="HasTexture",o[o.FillRenderTargetTextures=2048]="FillRenderTargetTextures",o[o.HasRenderTargetTextures=4096]="HasRenderTargetTextures",o[o.HardBindForSubMesh=8192]="HardBindForSubMesh"})(Lr||(Lr={}));class Ie{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(Ie.MiscDirtyFlag+Ie.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Ie.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Ie.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 he),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 he),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new he),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Ie.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(Ie.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Ie.WireFrameFillMode:case Ie.LineListDrawMode:case Ie.LineLoopDrawMode:case Ie.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Ie.WireFrameFillMode:Ie.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Ie.PointFillMode:case Ie.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Ie.PointFillMode:Ie.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Ie.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&G.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 he,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 Nl,this._useUBO=!1,this._fillMode=Ie.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||ht.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||fe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Or(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Ie.ClockWiseSideOrientation:this.sideOrientation=Ie.CounterClockWiseSideOrientation,this._uniformBuffer=new it(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ie.OnEventObservable.notifyObservers(this,Lr.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===Ie.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ie.MATERIAL_OPAQUE||this._transparencyMode===Ie.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const s of i.subMeshes)s.getMaterial()===this&&s.effect&&(s.effect._wasPreviouslyReady=!1,s.effect._wasPreviouslyUsingInstances=null,s.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(Ie.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===Ie.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(Lr.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i.effect;s&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Me.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}if(this.disableColorWrite){const i=this._scene.getEngine();this._cachedColorWriteState=i.getColorWrite(),i.setColorWrite(!1)}if(this.depthFunction!==0){const i=this._scene.getEngine();this._cachedDepthFunctionState=i.getDepthFunction()||0,i.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Lr.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Lr.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Lr.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ie._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const r=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Rn(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const d=new on(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=a,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,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||(Ie._DirtyCallbackArray.length=0,e&Ie.TextureDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._TextureDirtyCallBack),e&Ie.LightDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._LightsDirtyCallBack),e&Ie.FresnelDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._FresnelDirtyCallBack),e&Ie.AttributesDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._AttributeDirtyCallBack),e&Ie.MiscDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._MiscDirtyCallBack),e&Ie.PrePassDirtyFlag&&Ie._DirtyCallbackArray.push(Ie._PrePassDirtyCallBack),Ie._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ie._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(Ie._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ie._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ie._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ie._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ie._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ie._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ie._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ie._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ie._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ie._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Xo.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(Lr.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=Xe.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 G.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=fe.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,s){var r;if(e.plugins)for(const n in e.plugins){const a=e.plugins[n];let l=(r=t.pluginManager)===null||r===void 0?void 0:r.getPlugin(a.name);if(!l){const h=fe.Instantiate("BABYLON."+n);h&&(l=new h(t))}l==null||l.parse(a,i,s)}}}Ie.TriangleFillMode=0;Ie.WireFrameFillMode=1;Ie.PointFillMode=2;Ie.PointListDrawMode=3;Ie.LineListDrawMode=4;Ie.LineLoopDrawMode=5;Ie.LineStripDrawMode=6;Ie.TriangleStripDrawMode=7;Ie.TriangleFanDrawMode=8;Ie.ClockWiseSideOrientation=0;Ie.CounterClockWiseSideOrientation=1;Ie.TextureDirtyFlag=1;Ie.LightDirtyFlag=2;Ie.FresnelDirtyFlag=4;Ie.AttributesDirtyFlag=8;Ie.MiscDirtyFlag=16;Ie.PrePassDirtyFlag=32;Ie.AllDirtyFlag=63;Ie.MATERIAL_OPAQUE=0;Ie.MATERIAL_ALPHATEST=1;Ie.MATERIAL_ALPHABLEND=2;Ie.MATERIAL_ALPHATESTANDBLEND=3;Ie.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;Ie.MATERIAL_NORMALBLENDMETHOD_RNM=1;Ie.OnEventObservable=new he;Ie._AllDirtyCallBack=o=>o.markAllAsDirty();Ie._ImageProcessingDirtyCallBack=o=>o.markAsImageProcessingDirty();Ie._TextureDirtyCallBack=o=>o.markAsTexturesDirty();Ie._FresnelDirtyCallBack=o=>o.markAsFresnelDirty();Ie._MiscDirtyCallBack=o=>o.markAsMiscDirty();Ie._PrePassDirtyCallBack=o=>o.markAsPrePassDirty();Ie._LightsDirtyCallBack=o=>o.markAsLightDirty();Ie._AttributeDirtyCallBack=o=>o.markAsAttributesDirty();Ie._FresnelAndMiscDirtyCallBack=o=>{Ie._FresnelDirtyCallBack(o),Ie._MiscDirtyCallBack(o)};Ie._TextureAndMiscDirtyCallBack=o=>{Ie._TextureDirtyCallBack(o),Ie._MiscDirtyCallBack(o)};Ie._DirtyCallbackArray=[];Ie._RunDirtyCallBacks=o=>{for(const e of Ie._DirtyCallbackArray)e(o)};A([D()],Ie.prototype,"id",void 0);A([D()],Ie.prototype,"uniqueId",void 0);A([D()],Ie.prototype,"name",void 0);A([D()],Ie.prototype,"metadata",void 0);A([D()],Ie.prototype,"checkReadyOnEveryCall",void 0);A([D()],Ie.prototype,"checkReadyOnlyOnce",void 0);A([D()],Ie.prototype,"state",void 0);A([D("alpha")],Ie.prototype,"_alpha",void 0);A([D("backFaceCulling")],Ie.prototype,"_backFaceCulling",void 0);A([D("cullBackFaces")],Ie.prototype,"_cullBackFaces",void 0);A([D()],Ie.prototype,"sideOrientation",void 0);A([D("alphaMode")],Ie.prototype,"_alphaMode",void 0);A([D()],Ie.prototype,"_needDepthPrePass",void 0);A([D()],Ie.prototype,"disableDepthWrite",void 0);A([D()],Ie.prototype,"disableColorWrite",void 0);A([D()],Ie.prototype,"forceDepthWrite",void 0);A([D()],Ie.prototype,"depthFunction",void 0);A([D()],Ie.prototype,"separateCullingPass",void 0);A([D("fogEnabled")],Ie.prototype,"_fogEnabled",void 0);A([D()],Ie.prototype,"pointSize",void 0);A([D()],Ie.prototype,"zOffset",void 0);A([D()],Ie.prototype,"zOffsetUnits",void 0);A([D()],Ie.prototype,"pointsCloud",null);A([D()],Ie.prototype,"fillMode",null);A([D()],Ie.prototype,"useLogarithmicDepth",null);A([D()],Ie.prototype,"transparencyMode",null);class fh extends Ie{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=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new fh(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ui&&ui.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}j("BABYLON.MultiMaterial",fh);class Jw{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Eb{}class eF{constructor(){this.visibleInstances={},this.batchCache=new s0,this.batchCacheReplacementModeInFrozenMode=new s0,this.instancesBufferSize=32*16*4}}class s0{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class tF{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class iF{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 se extends hi{static _GetDefaultSideOrientation(e){return e||se.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(P.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(P.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 he),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new he),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new he),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new he),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new he),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 iF,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new eF,this._thinInstanceDataStorage=new tF,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=se.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(a,l,h)=>{a&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),Ur.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const a=s._ranges;for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&a[l]&&this.createAnimationRange(l,a[l].from,a[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ui&&ui.HasTags(s)&&ui.AddTagsTo(this,ui.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix()),this.id=e+"."+s.id,this.material=s.material,!r){const a=s.getDescendants(!0);for(let l=0;l{a.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new he(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;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return G.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Jw(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;ia*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const f=this.material||u.defaultMaterial;if(f){if(f._storeEffectOnSubMeshes)for(const _ of this.subMeshes){const g=_.getMaterial();if(g){if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,_,d))return!1}else if(!g.isReady(this,d))return!1}}else if(!f.isReady(this,d))return!1}const p=c.currentRenderPassId;for(const _ of this.lightSources){const g=_.getShadowGenerators();if(!g)continue;const v=g.values();for(let E=v.next();E.done!==!0;E=v.next()){const C=E.value;if(C&&(!(!((i=C.getShadowMap())===null||i===void 0)&&i.renderList)||!((s=C.getShadowMap())===null||s===void 0)&&s.renderList&&((n=(r=C.getShadowMap())===null||r===void 0?void 0:r.renderList)===null||n===void 0?void 0:n.indexOf(this))!==-1)){const b=(a=C.getShadowMap().renderPassIds)!==null&&a!==void 0?a:[c.currentRenderPassId];for(let R=0;R0){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 on(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=t);r++)on.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 Oe;r.set(t,e);const n=this.getScene();new sn(sn.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=sn.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(P.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(P.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(P.NormalKind);if(!r)return this;Oe.ComputeNormals(i,s,r),this.updateVerticesData(P.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(sn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new sn(sn.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 Oe;s.indices=e;const r=this.getScene();new sn(sn.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 Ie.PointFillMode:n=null;break;case Ie.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Ie.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==Ie.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ie.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const a=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?a.intermediateDefaultRenderId:a.defaultRenderId;n.visibleInstances[e]=a[l],!n.visibleInstances[e]&&h&&(n.visibleInstances[e]=a[h])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&n.visibleInstances[e]!==null&&n.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){var n;const a=i.visibleInstances[e._id],l=a?a.length:0,h=this._instanceDataStorage,c=h.instancesBufferSize;let u=h.instancesBuffer,d=h.instancesPreviousBuffer;const p=(l+1)*16*4;for(;h.instancesBufferSizeb._distanceToCamera>R._distanceToCamera?-1:b._distanceToCamera1&&h.activeCamera===h.activeCameras[0]||c<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const d=this._getInstancesRenderList(e._id,!!i);if(d.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const f=h.getEngine();let p=0,_=null;this.ignoreCameraMaxZ&&h.activeCamera&&!h._isInIntermediateRendering()&&(p=h.activeCamera.maxZ,_=h.activeCamera,h.activeCamera.maxZ=0,h.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const g=e.getRenderingMesh(),v=d.hardwareInstancedRendering[e._id]||g.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,E=this._instanceDataStorage,C=e.getMaterial();if(!C)return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;if(!E.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==C){if(C._storeEffectOnSubMeshes){if(!C.isReadyForSubMesh(this,e,v))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this}else if(!C.isReady(this,v))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=C}else if(C._storeEffectOnSubMeshes&&!(!((n=e.effect)===null||n===void 0)&&n._wasPreviouslyReady)||!C._storeEffectOnSubMeshes&&!(!((a=C.getEffect())===null||a===void 0)&&a._wasPreviouslyReady))return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;t&&f.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let S;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?S=e._drawWrapper:S=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const b=(l=S==null?void 0:S.effect)!==null&&l!==void 0?l:null;for(const V of h._beforeRenderingMeshStage)V.action(this,e,d,b);if(!S||!b)return _&&(_.maxZ=p,h.updateTransformMatrix(!0)),this;const R=i||this;let I;if(!E.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const V=R._getWorldMatrixDeterminant();I=this.overrideMaterialSideOrientation,I==null&&(I=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),V<0&&(I=I===Ie.ClockWiseSideOrientation?Ie.CounterClockWiseSideOrientation:Ie.ClockWiseSideOrientation),E.sideOrientation=I}else I=E.sideOrientation;const N=this._internalMeshDataInfo._effectiveMaterial._preBind(S,I);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&f.setDepthWrite(!0);const O=this._internalMeshDataInfo._effectiveMaterial,L=O.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,b,L,!1);const B=R.getWorldMatrix();O._storeEffectOnSubMeshes?O.bindForSubMesh(B,this,e):O.bind(B,this),!O.backFaceCulling&&O.separateCullingPass&&(f.setState(!0,O.zOffset,!1,!N,O.cullBackFaces,O.stencil,O.zOffsetUnits),this._processRendering(this,e,b,L,d,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),f.setState(!0,O.zOffset,!1,N,O.cullBackFaces,O.stencil,O.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,b,L,d,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const V of h._afterRenderingMeshStage)V.action(this,e,d,b);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),_&&(_.maxZ=p,h.updateTransformMatrix(!0)),h.performancePriority===Xo.Aggressive&&!E.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(P.MatricesWeightsKind)&&(this.isVerticesDataPresent(P.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(P.MatricesWeightsKind),t=e.length;for(let i=0;iv&&s++,b!==0&&C++,E+=b,v=b}if(h[C]++,C>n&&(n=C),E===0)r++;else{const S=1/E;let b=0;for(let R=0;Rc&&a++}}const u=this.skeleton.bones.length,d=this.getVerticesData(P.MatricesIndicesKind),f=this.getVerticesData(P.MatricesIndicesExtraKind);let p=0;for(let g=0;g=u||E<0)&&p++}const _="Number of Weights = "+i/4+` Maximum influences = `+n+` Missing Weights = `+r+` Not Sorted = `+s+` Not Normalized = `+a+` WeightCounts = [`+h+`] Number of bones = `+u+` -Bad Bone Indices = `+p;return{skinned:!0,valid:r===0&&a===0&&p===0,report:_}}_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 fe.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(P.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(P.PositionKind);const s=T.Zero();let r;for(r=0;r{const d=u.width,f=u.height,_=this.getEngine().createCanvas(d,f).getContext("2d");_.drawImage(u,0,0);const g=_.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(g,d,f,t,i,r,n,a),s&&s(this)};return fe.LoadImage(e,c,l||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,a,l=!1){if(!this.isVerticesDataPresent(P.PositionKind)||!this.isVerticesDataPresent(P.NormalKind)||!this.isVerticesDataPresent(P.UVKind))return G.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(P.PositionKind,!0,!0),c=this.getVerticesData(P.NormalKind),u=this.getVerticesData(P.UVKind);let d=T.Zero();const f=T.Zero(),p=Re.Zero();n=n||Re.Zero(),a=a||new Re(1,1);for(let _=0;_{const h=new Float32Array(i.length*l);let c=0;for(let u=0;u{const a=s.length-1-n,l=s[a];for(let h=0;h{for(let a=0;a-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;r4,h=l?this.getVerticesData(P.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(P.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=T.Zero(),f=new k,p=new k;let _=0,g;for(let v=0;v0&&(k.FromFloat32ArrayToRefScaled(u,Math.floor(n[_+g]*16),E,p),f.addToSelf(p));if(l)for(g=0;g<4;g++)E=c[_+g],E>0&&(k.FromFloat32ArrayToRefScaled(u,Math.floor(h[_+g]*16),E,p),f.addToSelf(p));T.TransformCoordinatesFromFloatsToRef(i._sourcePositions[v],i._sourcePositions[v+1],i._sourcePositions[v+2],f,d),d.toArray(s,v),t&&(T.TransformNormalFromFloatsToRef(i._sourceNormals[v],i._sourceNormals[v+1],i._sourceNormals[v+2],f,d),d.toArray(r,v)),f.reset()}return this.updateVerticesData(P.PositionKind,s),t&&this.updateVerticesData(P.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:T.Zero(),max:T.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?se.MinMax(e):e;return T.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return ux(se._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return vb(se._MergeMeshesCoroutine(e,t,i,s,r,n,!0),kw())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,a){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let I=0;for(l=0;l=65536)return G.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{const N=I.computeWorldMatrix(!0);return{vertexData:De.ExtractFromMesh(I,!1,!1),transform:N}},{vertexData:_,transform:g}=p(f);a&&(yield);const v=new Array(e.length-1);for(let I=1;I{throw xt("GroundMesh")};se._GoldbergMeshParser=(o,e)=>{throw xt("GoldbergMesh")};se._LinesMeshParser=(o,e)=>{throw xt("LinesMesh")};se._GreasedLineMeshParser=(o,e)=>{throw xt("GreasedLineMesh")};se._GreasedLineRibbonMeshParser=(o,e)=>{throw xt("GreasedLineRibbonMesh")};se._TrailMeshParser=(o,e)=>{throw xt("TrailMesh")};j("BABYLON.Mesh",se);se._instancedMeshFactory=(o,e)=>{const t=new dx(o,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class dx extends hi{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||t===void 0?void 0:t.receiveShadows)!==e&&fe.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||t===void 0?void 0:t.material)!==e&&fe.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||t===void 0?void 0:t.visibility)!==e&&fe.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||t===void 0?void 0:t.skeleton)!==e&&fe.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||G.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||G.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!==It.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new k);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,K.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(K.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;e0&&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=Yt.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Xe.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Xe.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)})),Xe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=Mi.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=Yt.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Xe.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{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 a of n)a._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===Yt.INTENSITYMODE_AUTOMATIC&&(t===Yt.LIGHTTYPEID_DIRECTIONALLIGHT?i=Yt.INTENSITYMODE_ILLUMINANCE:i=Yt.INTENSITYMODE_LUMINOUSINTENSITY),t){case Yt.LIGHTTYPEID_POINTLIGHT:case Yt.LIGHTTYPEID_SPOTLIGHT:switch(i){case Yt.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Yt.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Yt.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Yt.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Yt.INTENSITYMODE_ILLUMINANCE:e=1;break;case Yt.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case Yt.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Yt.FALLOFF_DEFAULT=Bi.FALLOFF_DEFAULT;Yt.FALLOFF_PHYSICAL=Bi.FALLOFF_PHYSICAL;Yt.FALLOFF_GLTF=Bi.FALLOFF_GLTF;Yt.FALLOFF_STANDARD=Bi.FALLOFF_STANDARD;Yt.LIGHTMAP_DEFAULT=Bi.LIGHTMAP_DEFAULT;Yt.LIGHTMAP_SPECULAR=Bi.LIGHTMAP_SPECULAR;Yt.LIGHTMAP_SHADOWSONLY=Bi.LIGHTMAP_SHADOWSONLY;Yt.INTENSITYMODE_AUTOMATIC=Bi.INTENSITYMODE_AUTOMATIC;Yt.INTENSITYMODE_LUMINOUSPOWER=Bi.INTENSITYMODE_LUMINOUSPOWER;Yt.INTENSITYMODE_LUMINOUSINTENSITY=Bi.INTENSITYMODE_LUMINOUSINTENSITY;Yt.INTENSITYMODE_ILLUMINANCE=Bi.INTENSITYMODE_ILLUMINANCE;Yt.INTENSITYMODE_LUMINANCE=Bi.INTENSITYMODE_LUMINANCE;Yt.LIGHTTYPEID_POINTLIGHT=Bi.LIGHTTYPEID_POINTLIGHT;Yt.LIGHTTYPEID_DIRECTIONALLIGHT=Bi.LIGHTTYPEID_DIRECTIONALLIGHT;Yt.LIGHTTYPEID_SPOTLIGHT=Bi.LIGHTTYPEID_SPOTLIGHT;Yt.LIGHTTYPEID_HEMISPHERICLIGHT=Bi.LIGHTTYPEID_HEMISPHERICLIGHT;A([ds()],Yt.prototype,"diffuse",void 0);A([ds()],Yt.prototype,"specular",void 0);A([D()],Yt.prototype,"falloffType",void 0);A([D()],Yt.prototype,"intensity",void 0);A([D()],Yt.prototype,"range",null);A([D()],Yt.prototype,"intensityMode",null);A([D()],Yt.prototype,"radius",null);A([D()],Yt.prototype,"_renderPriority",void 0);A([Ce("_reorderLightsInScene")],Yt.prototype,"renderPriority",void 0);A([D("shadowEnabled")],Yt.prototype,"_shadowEnabled",void 0);A([D("excludeWithLayerMask")],Yt.prototype,"_excludeWithLayerMask",void 0);A([D("includeOnlyWithLayerMask")],Yt.prototype,"_includeOnlyWithLayerMask",void 0);A([D("lightmapMode")],Yt.prototype,"_lightmapMode",void 0);class eF extends ks{}class tF{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 iF extends ks{constructor(e){super(),this._wasAddedToScene=!1,e=e||ht.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 a of e)t.set(a.uniqueId,a);const i={dependsOn:new Map,dependedBy:new Map};for(const a of e){const l=a.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const a of e){const l=a.uniqueId,h=i.dependsOn.get(l);if(a instanceof dx){const u=a.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 a.getDescendants()){const d=u.uniqueId;t.has(d)&&(c.add(d),i.dependsOn.get(d).add(l))}}const s=[],r=[];for(const a of e){const l=a.uniqueId;i.dependsOn.get(l).size===0&&(r.push(a),t.delete(l))}const n=r;for(;n.length>0;){const a=n.shift();s.push(a);const l=i.dependedBy.get(a.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(a.uniqueId),c.size===0&&t.get(h)&&(n.push(t.get(h)),t.delete(h))}}return t.size>0&&(G.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(a=>G.Error(a.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 se&&this.meshes.indexOf(e)!==-1||e instanceof It&&this.transformNodes.indexOf(e)!==-1||e instanceof Yt&&this.lights.indexOf(e)!==-1||e instanceof et&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return G.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 G.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 G.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 G.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||fe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new tF,a=[],l=[],h=Object.assign({doNotInstantiate:!0},i),c=(_,g)=>{if(s[_.uniqueId]=g.uniqueId,r[g.uniqueId]=g,e&&(g.name=e(_.name)),g instanceof se){const v=g;if(v.morphTargetManager){const E=_.morphTargetManager;v.morphTargetManager=E.clone();for(let C=0;C{if(c(_,g),_.parent){const v=s[_.parent.uniqueId],E=r[v];E?g.parent=E:g.parent=_.parent}if(g.position&&_.position&&g.position.copyFrom(_.position),g.rotationQuaternion&&_.rotationQuaternion&&g.rotationQuaternion.copyFrom(_.rotationQuaternion),g.rotation&&_.rotation&&g.rotation.copyFrom(_.rotation),g.scaling&&_.scaling&&g.scaling.copyFrom(_.scaling),g.material){const v=g;if(v.material)if(t){const E=_.material;if(l.indexOf(E)===-1){let C=E.clone(e?e(E.name):"Clone of "+E.name);if(l.push(E),s[E.uniqueId]=C.uniqueId,r[C.uniqueId]=C,E.getClassName()==="MultiMaterial"){const S=E;for(const b of S.subMaterials)b&&(C=b.clone(e?e(b.name):"Clone of "+b.name),l.push(b),s[b.uniqueId]=C.uniqueId,r[C.uniqueId]=C);S.subMaterials=S.subMaterials.map(b=>b&&r[s[b.uniqueId]])}}v.getClassName()!=="InstancedMesh"&&(v.material=r[s[E.uniqueId]])}else v.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(v.material)===-1&&this.scene.addMultiMaterial(v.material):this.scene.materials.indexOf(v.material)===-1&&this.scene.addMaterial(v.material)}g.parent===null&&n.rootNodes.push(g)};return f.forEach(_=>{if(_.getClassName()==="InstancedMesh"){const g=_,v=g.sourceMesh,E=s[v.uniqueId],S=(typeof E=="number"?r[E]:v).createInstance(g.name);p(g,S)}else{let g=!0;_.getClassName()==="TransformNode"||_.getClassName()==="Node"||_.skeleton||!_.getTotalVertices||_.getTotalVertices()===0?g=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?g=!h.doNotInstantiate(_):g=!h.doNotInstantiate);const v=g?_.createInstance(`instance of ${_.name}`):_.clone(`Clone of ${_.name}`,null,!0);if(!v)throw new Error(`Could not clone or instantiate node on Asset Container ${_.name}`);p(_,v)}}),this.skeletons.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const g=_.clone(e?e(_.name):"Clone of "+_.name);for(const v of this.meshes)if(v.skeleton===_&&!v.isAnInstance){const E=r[s[v.uniqueId]];if(!E||E.isAnInstance||(E.skeleton=g,a.indexOf(g)!==-1))continue;a.push(g);for(const C of g.bones)C._linkedTransformNode&&(C._linkedTransformNode=r[s[C._linkedTransformNode.uniqueId]])}n.skeletons.push(g)}),this.animationGroups.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const g=_.clone(e?e(_.name):"Clone of "+_.name,v=>r[s[v.uniqueId]]||v);n.animationGroups.push(g)}),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||fe.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()||fe.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 eF);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 se("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=ht.LastCreatedScene,t,i=null){if(!e)return G.Error("No scene available to merge animations to"),[];const s=i||(a=>{let l=null;const h=a.animations.length?a.animations[0].targetProperty:"",c=a.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(a.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(a.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(a.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(a=>{const l=s(a);if(l!==null){for(const h of a.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(a.animations)}});const n=[];return this.animationGroups.slice().forEach(a=>{n.push(a.clone(a.name,s)),a.animatables.forEach(l=>{l.stop()})}),t.forEach(a=>{const l=s(a.target);l&&(e.beginAnimation(l,a.fromFrame,a.toFrame,a.loopAnimation,a.speedRatio,a.onAnimationEnd?a.onAnimationEnd:void 0,void 0,!0,void 0,a.onAnimationLoop?a.onAnimationLoop:void 0),e.stopAnimation(a.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 se?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof It?this.transformNodes.push(s):s instanceof Yt?this.lights.push(s):s instanceof et&&this.cameras.push(s),s instanceof hi){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()}}re.AudioEngineFactory=(o,e,t)=>new sF(o,e,t);class sF{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 he,this.onAudioLockedObservable=new he,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!gr())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||e===void 0?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?(t=this._audioContext)===null||t===void 0||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return!((e=this._audioContext)===null||e===void 0)&&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,G.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 Yo{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=re.audioEngine)===null||e===void 0)&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:re.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,a,l,h,c;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 he,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=T.Zero(),this._localDirection=new T(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||ht.LastCreatedScene,!!i)if(this._scene=i,Yo._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(u,d,f,p,_)=>d0&&(f=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":d.push(t);case"Array":d.length===0&&(d=t);for(let p=0;p{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(_,g=>{this._soundLoaded(g)},void 0,!0,!0,g=>{g&&G.Error("XHR "+g.status+" error on: "+_+"."),G.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:u=!1;break}u?f||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):G.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{G.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),re.audioEngine&&!re.audioEngine.WarnedWebAudioUnsupported&&(G.Error("Web Audio is not supported by your browser."),re.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;!((e=re.audioEngine)===null||e===void 0)&&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=re.audioEngine)===null||t===void 0)&&t.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.audioContext&&re.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{G.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,s,r,n,a,l,h,c,u,d;e&&(this.loop=(t=e.loop)!==null&&t!==void 0?t:this.loop,this.maxDistance=(i=e.maxDistance)!==null&&i!==void 0?i:this.maxDistance,this.useCustomAttenuation=(s=e.useCustomAttenuation)!==null&&s!==void 0?s:this.useCustomAttenuation,this.rolloffFactor=(r=e.rolloffFactor)!==null&&r!==void 0?r:this.rolloffFactor,this.refDistance=(n=e.refDistance)!==null&&n!==void 0?n:this.refDistance,this.distanceModel=(a=e.distanceModel)!==null&&a!==void 0?a:this.distanceModel,this._playbackRate=(l=e.playbackRate)!==null&&l!==void 0?l:this._playbackRate,this._length=(h=e.length)!==null&&h!==void 0?h:void 0,this.spatialSound=(c=e.spatialSound)!==null&&c!==void 0?c:this._spatialSound,this._setOffset((u=e.offset)!==null&&u!==void 0?u:void 0),this.setVolume((d=e.volume)!==null&&d!==void 0?d: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,t;!((e=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&re.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=(t=this._soundPanner)!==null&&t!==void 0?t:re.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===void 0||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=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{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=re.audioEngine)===null||c===void 0)&&c.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,p;(f=re.audioEngine)===null||f===void 0||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(p=re.audioEngine)===null||p===void 0?void 0:p.onAudioUnlockedObservable.addOnce(()=>{h()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=re.audioEngine)===null||u===void 0?void 0:u.onAudioUnlockedObservable.addOnce(()=>{h()}))};h()}}else{const h=()=>{var c,u,d,f;if(!((c=re.audioEngine)===null||c===void 0)&&c.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const p=this._soundSource;p.onended=()=>{p.disconnect()}}if(this._soundSource=(u=re.audioEngine)===null||u===void 0?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=re.audioEngine)===null||d===void 0?void 0:d.audioContext.currentTime)+e:re.audioEngine.audioContext.currentTime;const p=((this.isPaused?this.currentTime:0)+((f=this._offset)!==null&&f!==void 0?f:0))%this._soundSource.buffer.duration;this._soundSource.start(l,p,this.loop?void 0:i)}}};((a=re.audioEngine)===null||a===void 0?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var c;((c=re.audioEngine)===null||c===void 0?void 0:c.audioContext.state)==="suspended"?(re.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=re.audioEngine.onAudioUnlockedObservable.addOnce(()=>{h()}))):h()},500):h()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){G.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=re.audioEngine)===null||t===void 0)&&t.audioContext&&this._soundSource){const i=e?re.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=re.audioEngine)===null||e===void 0)&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=re.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;!((i=re.audioEngine)===null||i===void 0)&&i.canUseWebAudio&&this._soundGain&&(t&&re.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(re.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,re.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,re.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=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Yo(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 a={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let l;if(!s)l=new Yo(r,n,t,()=>{t.removePendingData(l)},a),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 Yo(r,new ArrayBuffer(0),t,null,a),h()}if(e.position){const h=T.FromArray(e.position);l.setPosition(h)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const h=T.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=re.audioEngine)===null||e===void 0||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Yo._SceneComponentInitialization=o=>{throw xt("AudioSceneComponent")};class rF{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||ht.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=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&re.audioEngine.audioContext&&(this._outputAudioNode=re.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(re.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(re.audioEngine&&re.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=re.audioEngine)===null||t===void 0)&&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=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(!((e=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio)for(let t=0;t{var s;let r=[],n;if(t.sounds=t.sounds||[],o.sounds!==void 0&&o.sounds!==null)for(let a=0,l=o.sounds.length;a{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;t0&&(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),T.TransformNormalToRef(Gn._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{let e=o._getComponent(Fe.NAME_AUDIO);e||(e=new Gn(o),o._addComponent(e))};class pu{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,e=e||ht.LastCreatedScene,e&&(this._scene=e,this.animationParameters=new Dt(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 pu(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,s=30){this.animationParameters=new Dt(e,t,i,s)}dispose(e){var t;e&&((t=this._texture)===null||t===void 0||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([Jt(),Ce("_markSubMeshesAsAttributesDirty")],pu.prototype,"texture",void 0);A([D(),Ce("_markSubMeshesAsAttributesDirty")],pu.prototype,"isEnabled",void 0);A([D()],pu.prototype,"animationParameters",void 0);A([D()],pu.prototype,"time",void 0);class Vh{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=ya.Zero(),this._cachedBaseSize=ya.Zero(),this._initialSamplingMode=2,this._texture=Vh._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 Ei extends Vh{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===void 0||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===void 0||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=du()),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=Ei.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 he,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Ei._IsScene(e)?this._scene=e:this._engine=e:this._scene=ht.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 k.IdentityReadOnly}getReflectionTextureMatrix(){return k.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 a=this._getEngine();if(!a)return null;const l=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let c=0;c=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=Xe.Serialize(this);return Xe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Ei.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;A([D()],Ei.prototype,"uniqueId",void 0);A([D()],Ei.prototype,"name",void 0);A([D()],Ei.prototype,"metadata",void 0);A([D("hasAlpha")],Ei.prototype,"_hasAlpha",void 0);A([D("getAlphaFromRGB")],Ei.prototype,"_getAlphaFromRGB",void 0);A([D()],Ei.prototype,"level",void 0);A([D("coordinatesIndex")],Ei.prototype,"_coordinatesIndex",void 0);A([D()],Ei.prototype,"optimizeUVAllocation",void 0);A([D("coordinatesMode")],Ei.prototype,"_coordinatesMode",void 0);A([D()],Ei.prototype,"wrapU",null);A([D()],Ei.prototype,"wrapV",null);A([D()],Ei.prototype,"wrapR",void 0);A([D()],Ei.prototype,"anisotropicFilteringLevel",void 0);A([D()],Ei.prototype,"isCube",null);A([D()],Ei.prototype,"is3D",null);A([D()],Ei.prototype,"is2DArray",null);A([D()],Ei.prototype,"gammaSpace",null);A([D()],Ei.prototype,"invertZ",void 0);A([D()],Ei.prototype,"lodLevelInAlpha",void 0);A([D()],Ei.prototype,"lodGenerationOffset",null);A([D()],Ei.prototype,"lodGenerationScale",null);A([D()],Ei.prototype,"linearSpecularLOD",null);A([Jt()],Ei.prototype,"irradianceTexture",null);A([D()],Ei.prototype,"isRenderTarget",void 0);function Tb(o,e,t=!1){const i=e.width,s=e.height;if(o instanceof Float32Array){let h=o.byteLength/o.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=o[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}o=c}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const a=n.createImageData(i,s);if(a.data.set(o),n.putImageData(a,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 nF(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=o._readPixelsSync(e,t);return s?Tb(s,o.getSize(),i.invertY):null}async function aF(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=await o.readPixels(e,t);return s?Tb(s,o.getSize(),i.invertY):null}class ee extends Ei{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=ee.TRILINEAR_SAMPLINGMODE,a={},l,h=5){throw xt("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=ee.TRILINEAR_SAMPLINGMODE,n=null,a=null,l=null,h=!1,c,u,d,f,p){var _,g,v,E,C,S,b,R,I,N;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 he,this._isBlocking=!0,this.name=e||"",this.url=e;let O,L=!1,B=null,V=!0;typeof i=="object"&&i!==null?(O=(_=i.noMipmap)!==null&&_!==void 0?_:!1,s=(g=i.invertY)!==null&&g!==void 0?g:!pi.UseOpenGLOrientationForUV,r=(v=i.samplingMode)!==null&&v!==void 0?v:ee.TRILINEAR_SAMPLINGMODE,n=(E=i.onLoad)!==null&&E!==void 0?E:null,a=(C=i.onError)!==null&&C!==void 0?C:null,l=(S=i.buffer)!==null&&S!==void 0?S:null,h=(b=i.deleteBuffer)!==null&&b!==void 0?b:!1,c=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,L=(R=i.useSRGBBuffer)!==null&&R!==void 0?R:!1,B=(I=i.internalTexture)!==null&&I!==void 0?I:null,V=(N=i.gammaSpace)!==null&&N!==void 0?N:V):O=!!i,this._gammaSpace=V,this._noMipmap=O,this._invertY=s===void 0?!pi.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=L,this._forcedExtension=p,c&&(this._format=c);const Z=this.getScene(),ue=this._getEngine();if(!ue)return;ue.onBeforeTextureInitObservable.notifyObservers(this);const oe=()=>{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&&Z&&Z.resetCachedMaterial()},me=(le,ae)=>{this._loadingError=!0,this._errorObject={message:le,exception:ae},a&&a(le,ae),ee.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!B){this._delayedOnLoad=oe,this._delayedOnError=me;return}if(this._texture=B??this._getFromCache(this.url,O,r,this._invertY,L,this.isCube),this._texture)if(this._texture.isReady)Qc.SetImmediate(()=>oe());else{const le=this._texture.onLoadedObservable.add(oe);this._texture.onErrorObservable.add(ae=>{var ce;me(ae.message,ae.exception),(ce=this._texture)===null||ce===void 0||ce.onLoadedObservable.remove(le)})}else if(!Z||!Z.useDelayedTextureLoading){try{this._texture=ue.createTexture(this.url,O,this._invertY,Z,r,oe,me,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,L)}catch(le){throw me("error loading",le),le}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=oe,this._delayedOnError=me}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?Qc.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,T.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=k.Zero(),this._rowGenerationMatrix=new k,this._t0=T.Zero(),this._t1=T.Zero(),this._t2=T.Zero()),k.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(k.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,K.Matrix[0]),k.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,K.Matrix[1]),k.ScalingToRef(this._cachedUScale,this._cachedVScale,0,K.Matrix[2]),k.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,K.Matrix[3]),K.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.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),k.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===ee.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=k.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=k.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 ee.PLANAR_MODE:{k.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 ee.PROJECTION_MODE:{k.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:k.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 Xe.Clone(()=>new ee(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;const i=this.name;ee.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const s=super.serialize(ee._SerializeInternalTextureUniqueId);return s?((ee.SerializeBuffers||ee.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(s.base64String=this._buffer,s.name=s.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?s.base64String="data:image/png;base64,"+rb(this._buffer):(ee.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(s.base64String=!this._engine||this._engine._features.supportSyncTextureRead?nF(this):aF(this))),s.invertY=this._invertY,s.samplingMode=this.samplingMode,s._creationFlags=this._creationFlags,s._useSRGBBuffer=this._useSRGBBuffer,ee._SerializeInternalTextureUniqueId&&(s.internalTextureUniqueId=(t=(e=this._texture)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:void 0),s.noMipmap=this._noMipmap,this.name=i,s):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=td.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 ee._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{var l,h,c;let u=!0;if(e.noMipmap&&(u=!1),e.mirrorPlane){const d=ee._CreateMirror(e.name,e.renderTargetSize,t,u);return d._waitingRenderList=e.renderList,d.mirrorPlane=An.FromArray(e.mirrorPlane),n(d),d}else if(e.isRenderTarget){let d=null;if(e.isCube){if(t.reflectionProbes)for(let f=0;f{n(d)},(h=e._creationFlags)!==null&&h!==void 0?h:0,(c=e._useSRGBBuffer)!==null&&c!==void 0?c:!1),d.name=e.name;else{let f;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?f=e.name:f=i+e.name,e.url&&(e.url.startsWith("data:")||ee.UseSerializedUrlIfAny)&&(f=e.url);const p={noMipmap:!u,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(d)},internalTexture:r};d=new ee(f,t,p)}return d}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=ee.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c){return new ee("data:"+t,i,s,r,n,a,l,e,!1,h,void 0,void 0,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,a=ee.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new ee(e,i,r,n,a,l,h,t,s,c,void 0,void 0,u)}}ee.SerializeBuffers=!0;ee.ForceSerializeBuffers=!1;ee.OnTextureLoadErrorObservable=new he;ee._SerializeInternalTextureUniqueId=!1;ee._CubeTextureParser=(o,e,t)=>{throw xt("CubeTexture")};ee._CreateMirror=(o,e,t,i)=>{throw xt("MirrorTexture")};ee._CreateRenderTargetTexture=(o,e,t,i,s)=>{throw xt("RenderTargetTexture")};ee.NEAREST_SAMPLINGMODE=1;ee.NEAREST_NEAREST_MIPLINEAR=8;ee.BILINEAR_SAMPLINGMODE=2;ee.LINEAR_LINEAR_MIPNEAREST=11;ee.TRILINEAR_SAMPLINGMODE=3;ee.LINEAR_LINEAR_MIPLINEAR=3;ee.NEAREST_NEAREST_MIPNEAREST=4;ee.NEAREST_LINEAR_MIPNEAREST=5;ee.NEAREST_LINEAR_MIPLINEAR=6;ee.NEAREST_LINEAR=7;ee.NEAREST_NEAREST=1;ee.LINEAR_NEAREST_MIPNEAREST=9;ee.LINEAR_NEAREST_MIPLINEAR=10;ee.LINEAR_LINEAR=2;ee.LINEAR_NEAREST=12;ee.EXPLICIT_MODE=0;ee.SPHERICAL_MODE=1;ee.PLANAR_MODE=2;ee.CUBIC_MODE=3;ee.PROJECTION_MODE=4;ee.SKYBOX_MODE=5;ee.INVCUBIC_MODE=6;ee.EQUIRECTANGULAR_MODE=7;ee.FIXED_EQUIRECTANGULAR_MODE=8;ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ee.CLAMP_ADDRESSMODE=0;ee.WRAP_ADDRESSMODE=1;ee.MIRROR_ADDRESSMODE=2;ee.UseSerializedUrlIfAny=!1;A([D()],ee.prototype,"url",void 0);A([D()],ee.prototype,"uOffset",void 0);A([D()],ee.prototype,"vOffset",void 0);A([D()],ee.prototype,"uScale",void 0);A([D()],ee.prototype,"vScale",void 0);A([D()],ee.prototype,"uAng",void 0);A([D()],ee.prototype,"vAng",void 0);A([D()],ee.prototype,"wAng",void 0);A([D()],ee.prototype,"uRotationCenter",void 0);A([D()],ee.prototype,"vRotationCenter",void 0);A([D()],ee.prototype,"wRotationCenter",void 0);A([D()],ee.prototype,"homogeneousRotationInUVTransform",void 0);A([D()],ee.prototype,"isBlocking",null);j("BABYLON.Texture",ee);Xe._TextureParser=ee.Parse;We.prototype.updateRawTexture=function(o,e,t,i,s=null,r=0,n=!1){if(!o)return;const a=this._getRGBABufferInternalSizedFormat(r,t,n),l=this._getInternalFormat(t),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,o,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.type=r,o.invertY=i,o._compression=s),o.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],o.width,o.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,o.width,o.height,0,l,h,e),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),o.isReady=!0};We.prototype.createRawTexture=function(o,e,t,i,s,r,n,a=null,l=0,h=0,c=!1){const u=new Ti(this,Vt.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=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=o),this.updateRawTexture(u,o,i,r,a,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};We.prototype.createRawCubeTexture=function(o,e,t,i,s,r,n,a=null){const l=this._gl,h=new Ti(this,Vt.CubeRaw);h.isCube=!0,h.format=t,h.type=i,this._doNotHandleContextLost||(h._bufferViewArray=o);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,G.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,G.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,G.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,G.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=a,!this.needPOTTextures||fe.IsExponentOfTwo(h.width)&&fe.IsExponentOfTwo(h.height)||(s=!1),o)this.updateRawCubeTexture(h,o,t,i,r,a);else{const g=this._getRGBABufferInternalSizedFormat(i),v=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let E=0;E<6;E++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+E,v,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+E,v,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),o&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const _=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.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};We.prototype.updateRawCubeTexture=function(o,e,t,i,s,r=null,n=0){o._bufferViewArray=e,o.format=t,o.type=i,o.invertY=s,o._compression=r;const a=this._gl,l=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,o,!0),this._unpackFlipY(s===void 0?!0:!!s),o.width%4!==0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let p=e[f];r?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,this.getCaps().s3tc[r],o.width,o.height,0,p):(u&&(p=Eb(p,o.width,o.height,i)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,c,o.width,o.height,0,h,l,p))}(!this.needPOTTextures||fe.IsExponentOfTwo(o.width)&&fe.IsExponentOfTwo(o.height))&&o.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),o.isReady=!0};We.prototype.createRawCubeTextureFromUrl=function(o,e,t,i,s,r,n,a,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=o,f.isReady=!1,this._internalTexturesCache.push(f);const p=(g,v)=>{e==null||e.removePendingData(f),h&&g&&h(g.status+" "+g.statusText,v)},_=g=>{const v=f.width,E=n(g);if(E){if(a){const C=this._getWebGLTextureType(s);let S=this._getInternalFormat(i);const b=this._getRGBABufferInternalSizedFormat(s);let R=!1;S===d.RGB&&(S=d.RGBA,R=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const I=a(E);for(let N=0;N>N;for(let L=0;L<6;L++){let B=I[N][L];R&&(B=Eb(B,O,O,s)),d.texImage2D(L,N,b,O,O,0,S,C,B)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,E,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(o,g=>{_(g)},void 0,e==null?void 0:e.offlineProvider,!0,p),f};function Eb(o,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;n0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===rt.POINTERDOWN){this._isPointerDown=!0;return}i.type===rt.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=ar.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??ar.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)<$t:!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=ar.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 Gh{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)return;i.computeWorldMatrix(!0);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||(Gh.EasingFunction.setEasingMode(Gh.EasingMode),this._radiusBounceTransition=Ee.CreateAnimation("radius",Ee.ANIMATIONTYPE_FLOAT,60,Gh.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ee.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()}}Gh.EasingFunction=new Lw(.3);Gh.EasingMode=ln.EASINGMODE_EASEOUT;class Un{constructor(){this.onTargetFramingAnimationEndObservable=new he,this._mode=Un.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();Un.EasingFunction.setEasingMode(Un.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===rt.POINTERDOWN){this._isPointerDown=!0;return}i.type===rt.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&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 T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n{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===Un.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=ar.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=Ee.CreateAnimation("beta",Ee.ANIMATIONTYPE_FLOAT,60,Un.EasingFunction));const s=Ee.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=ar.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}}Un.EasingFunction=new Bw;Un.EasingMode=ln.EASINGMODE_EASEINOUT;Un.IgnoreBoundsSizeMode=0;Un.FitFrustumSidesMode=1;class Kt{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new Kt(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Kt._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Kt._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n=0,a=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.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),a=Math.min(c,a),n>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.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),a=Math.min(c,a),n>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.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),a=Math.min(c,a),n>a)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,a=e.radius+t,l=a*a;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=Kt._TmpVector3[0],r=Kt._TmpVector3[1],n=Kt._TmpVector3[2],a=Kt._TmpVector3[3],l=Kt._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),T.CrossToRef(this.direction,r,n);const h=T.Dot(s,n);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,a);const u=T.Dot(a,n)*c;if(u<0||u>1)return null;T.CrossToRef(a,s,l);const d=T.Dot(this.direction,l)*c;if(d<0||u+d>1)return null;const f=T.Dot(r,l)*c;return f>this.length?null:new wv(1-u-d,u,f)}intersectsPlane(e){let t;const i=T.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=T.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 T(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 T(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 T(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 a=K.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?Kt.TransformToRef(this,a,this._tmpRay):this._tmpRay=Kt.Transform(this,a),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=K.Vector3[0],n=K.Vector3[1],a=K.Vector3[2],l=K.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Kt._Rayl,a),s.addToRef(a,n),e.subtractToRef(s,l);const h=T.Dot(r,r),c=T.Dot(r,a),u=T.Dot(a,a),d=T.Dot(r,l),f=T.Dot(a,l),p=h*u-c*c;let _,g=p,v,E=p;pg&&(_=g,v=f+c,E=u)),v<0?(v=0,-d<0?_=0:-d>h?_=g:(_=-d,g=h)):v>E&&(v=E,-d+c<0?_=0:-d+c>h?_=g:(_=-d+c,g=h));const C=Math.abs(_)0&&S<=this.length&&I.lengthSquared()=o.distance?null:h};Qe.prototype._internalPick=function(o,e,t,i,s){let r=null;const n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n(this._tempPickingRay||(this._tempPickingRay=Kt.Zero()),this.createPickingRayToRef(o,e,n,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return r&&(r.ray=this.createPickingRay(o,e,k.Identity(),s||null)),r};Object.defineProperty(Qe.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Qe.prototype.pick=function(o,e,t,i,s,r,n=!1){const a=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=Kt.Zero()),this.createPickingRayToRef(o,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,r);return a&&(a.ray=this.createPickingRay(o,e,k.Identity(),s||null)),a};Qe.prototype.pickWithRay=function(o,e,t,i){const s=this._internalPick(r=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=k.Identity()),r.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Kt.Zero()),Kt.TransformToRef(o,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=o),s};Qe.prototype.multiPick=function(o,e,t,i,s){return this._internalMultiPick(r=>this.createPickingRay(o,e,r,i||null),t,s)};Qe.prototype.multiPickWithRay=function(o,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=k.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Kt.Zero()),Kt.TransformToRef(o,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};et.prototype.getForwardRay=function(o=100,e,t){return this.getForwardRayToRef(new Kt(T.Zero(),T.Zero(),o),o,e,t)};et.prototype.getForwardRayToRef=function(o,e=100,t,i){t||(t=this.getWorldMatrix()),o.length=e,i?o.origin.copyFrom(i):o.origin.copyFrom(this.position);const s=K.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);const r=K.Vector3[3];return T.TransformNormalToRef(s,t,r),T.NormalizeToRef(r,o.direction),o};function fx(o){const e=[],t=[],i=[],s=[],r=o.width||o.size||1,n=o.height||o.size||1,a=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,l=r/2,h=n/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,pi.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,pi.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,pi.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,pi.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),De._ComputeSides(a,t,e,i,s,o.frontUVs,o.backUVs);const c=new De;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function J_(o,e={},t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,fx(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}De.CreatePlane=fx;se.CreatePlane=(o,e,t,i,s)=>J_(o,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);class oi{}oi.ANCHOR_SYSTEM="xr-anchor-system";oi.BACKGROUND_REMOVER="xr-background-remover";oi.HIT_TEST="xr-hit-test";oi.MESH_DETECTION="xr-mesh-detection";oi.PHYSICS_CONTROLLERS="xr-physics-controller";oi.PLANE_DETECTION="xr-plane-detection";oi.POINTER_SELECTION="xr-controller-pointer-selection";oi.TELEPORTATION="xr-controller-teleportation";oi.FEATURE_POINTS="xr-feature-points";oi.HAND_TRACKING="xr-hand-tracking";oi.IMAGE_TRACKING="xr-image-tracking";oi.NEAR_INTERACTION="xr-near-interaction";oi.DOM_OVERLAY="xr-dom-overlay";oi.MOVEMENT="xr-controller-movement";oi.LIGHT_ESTIMATION="xr-light-estimation";oi.EYE_TRACKING="xr-eye-tracking";oi.WALKING_LOCOMOTION="xr-walking-locomotion";oi.LAYERS="xr-layers";oi.DEPTH_SENSING="xr-depth-sensing";oi.SPACE_WARP="xr-space-warp";oi.RAW_CAMERA_ACCESS="xr-raw-camera-access";class _s{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()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.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 a=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(t==="stable"?a=_s.GetStableVersionOfFeature(n):t==="latest"?a=_s.GetLatestVersionOfFeature(n):a=+t,a===-1||isNaN(a))throw new Error(`feature not found - ${n} (${t})`)}else a=t;const l=_s._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=_s.ConstructFeature(n,a,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:a,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 fe.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=Object.assign(Object.assign({},e),n)}}return e}}_s._AvailableFeatures={};_s._ConflictingFeatures={[oi.TELEPORTATION]:oi.MOVEMENT,[oi.MOVEMENT]:oi.TELEPORTATION};class Cr{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName="",this.onFeatureAttachObservable=new he,this.onFeatureDetachObservable=new he}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,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){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class ts{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)}}ts.DistanceJoint=0;ts.HingeJoint=1;ts.BallAndSocketJoint=2;ts.WheelJoint=3;ts.SliderJoint=4;ts.PrismaticJoint=5;ts.UniversalJoint=6;ts.Hinge2Joint=ts.WheelJoint;ts.PointToPointJoint=8;ts.SpringJoint=9;ts.LockJoint=10;se._PhysicsImpostorParser=function(o,e,t){return new Ct(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},o)};class Ct{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=T.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Se,this._tmpQuat2=new Se,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 Se),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,Ct._TmpVecs[0]),this.object.translate(Ct._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(a=>a.otherImpostors.indexOf(n)!==-1).forEach(a=>{a.callback(this,n,r.point,r.distance,r.impulse,r.normal)}))},!this.object){G.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&G.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=Se.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Se),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&&G.Warn("You must affect impostors to children before affecting impostor to parent.")):G.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 hi?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=Ct.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 Ct.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):T.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):T.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):G.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):G.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,a)=>{if(n.callback===t&&n.otherImpostors.length===i.length){const l=n.otherImpostors.every(h=>i.indexOf(h)>-1);return l&&(s=a),l}return!1})?this._onPhysicsCollideCallbacks.splice(s,1):G.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):Se.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 ts(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 Ct(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 Se),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=Ct._TmpVecs[0],a=this.object;if(a.rotationQuaternion)if(r){const l=Ct._TmpQuat;a.rotationQuaternion.multiplyToRef(r,l),e.setRotationQuaternion(l,_i.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,_i.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(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const a=this.object;if(a.rotationQuaternion)if(r){const c=Ct._TmpQuat;e.getRotationQuaternionToRef(_i.WORLD,t,c),c.multiplyToRef(r,a.rotationQuaternion)}else e.getRotationQuaternionToRef(_i.WORLD,t,a.rotationQuaternion);const l=Ct._TmpVecs[0],h=Ct._TmpVecs[1];n||(n=Ct._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),a.setAbsolutePosition(l)}}Ct.DEFAULT_OBJECT_SIZE=new T(1,1,1);Ct.IDENTITY_QUATERNION=Se.Identity();Ct._TmpVecs=js.BuildArray(3,T.Zero);Ct._TmpQuat=Se.Identity();Ct.NoImpostor=0;Ct.SphereImpostor=1;Ct.BoxImpostor=2;Ct.PlaneImpostor=3;Ct.MeshImpostor=4;Ct.CapsuleImpostor=6;Ct.CylinderImpostor=7;Ct.ParticleImpostor=8;Ct.HeightmapImpostor=9;Ct.ConvexHullImpostor=10;Ct.CustomImpostor=100;Ct.RopeImpostor=101;Ct.ClothImpostor=102;Ct.SoftbodyImpostor=103;var $l;(function(o){o[o.Clean=0]="Clean",o[o.Stop=1]="Stop",o[o.Sync=2]="Sync",o[o.NoSync=3]="NoSync"})($l||($l={}));class Ft{static get ForceFullSceneLoadingForIncremental(){return nr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nr.ShowLoadingScreen}static set ShowLoadingScreen(e){nr.ShowLoadingScreen=e}static get loggingLevel(){return nr.loggingLevel}static set loggingLevel(e){nr.loggingLevel=e}static get CleanBoneMatrixWeights(){return nr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ft._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=Ft._RegisteredPlugins[e];return t||(G.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"),Ft.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ft._RegisteredPlugins){const i=Ft._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ft._RegisteredPlugins[t]}return Ft.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 Ft._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,a,l){const h=Ft._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=a?Ft._GetPluginForExtension(a):h?Ft._GetPluginForDirectLoad(e.url):Ft._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(Ft.OnPluginActivatedObservable.notifyObservers(u),h&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!hx(e.url))){if(u.directLoad){const S=u.directLoad(t,h);S.then?S.then(b=>{i(u,b)}).catch(b=>{r("Error in directLoad of _loadData: "+b,b)}):i(u,S)}else i(u,h);return u}const d=c.isBinary,f=(S,b)=>{if(t.isDisposed){r("Scene has been disposed");return}i(u,S,b)};let p=null,_=!1;const g=u.onDisposeObservable;g&&g.add(()=>{_=!0,p&&(p.abort(),p=null),n()});const v=()=>{if(_)return;const S=(b,R)=>{r(b==null?void 0:b.statusText,R)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,s,d,S,l):t._loadFile(e.file||e.url,f,s,!0,d,S)},E=t.getEngine();let C=E.enableOfflineSupport;if(C){let S=!1;for(const b of t.disableOfflineSupportExceptionRules)if(b.test(e.url)){S=!0;break}C=!S}return C&&re.OfflineProviderFactory?t.offlineProvider=re.OfflineProviderFactory(e.url,v,E.disableManifestCheck):v(),u}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(!t)i=e,s=fe.GetFilename(e),e=fe.GetFolderPath(e);else if(t.name){const a=t;i=`file:${a.name}`,s=a.name,r=a}else if(ArrayBuffer.isView(t))i="",s="arrayBuffer",n=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const a=t;if(a.substr(0,1)==="/")return fe.Error("Wrong sceneFilename parameter"),null;i=e+a,s=a}return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Ft._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ft._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;Ft._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{Ft._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=ht.LastCreatedScene,r=null,n=null,a=null,l=null,h=""){if(!s)return G.Error("No scene available to import mesh to"),null;const c=Ft._GetFileInfo(t,i);if(!c)return null;const u={};s.addPendingData(u);const d=()=>{s.removePendingData(u)},f=(g,v)=>{const E=Ft._FormatErrorMessage(c,g,v);a?a(s,E,new Ko(E,sh.SceneLoaderError,v)):G.Error(E),d()},p=n?g=>{try{n(g)}catch(v){f("Error in onProgress callback: "+v,v)}}:void 0,_=(g,v,E,C,S,b,R)=>{if(s.importedMeshesFiles.push(c.url),r)try{r(g,v,E,C,S,b,R)}catch(I){f("Error in onSuccess callback: "+I,I)}s.removePendingData(u)};return Ft._LoadData(c,s,(g,v,E)=>{if(g.rewriteRootURL&&(c.rootUrl=g.rewriteRootURL(c.rootUrl,E)),g.importMesh){const C=g,S=[],b=[],R=[];if(!C.importMesh(e,s,v,c.rootUrl,S,b,R,f))return;s.loadingPluginName=g.name,_(S,b,R,[],[],[],[])}else g.importMeshAsync(e,s,v,c.rootUrl,p,c.name).then(S=>{s.loadingPluginName=g.name,_(S.meshes,S.particleSystems,S.skeletons,S.animationGroups,S.transformNodes,S.geometries,S.lights)}).catch(S=>{f(S.message,S)})},p,f,d,l,h)}static ImportMeshAsync(e,t,i="",s=ht.LastCreatedScene,r=null,n=null,a=""){return new Promise((l,h)=>{Ft.ImportMesh(e,t,i,s,(c,u,d,f,p,_,g)=>{l({meshes:c,particleSystems:u,skeletons:d,animationGroups:f,transformNodes:p,geometries:_,lights:g})},r,(c,u,d)=>{h(d||new Error(u))},n,a)})}static Load(e,t="",i=ht.LastCreatedEngine,s=null,r=null,n=null,a=null,l=""){return i?Ft.Append(e,t,new Qe(i),s,r,n,a,l):(fe.Error("No engine available"),null)}static LoadAsync(e,t="",i=ht.LastCreatedEngine,s=null,r=null,n=""){return new Promise((a,l)=>{Ft.Load(e,t,i,h=>{a(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static Append(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=null,a=null,l=""){if(!i)return G.Error("No scene available to append to"),null;const h=Ft._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};Ft.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const d=(_,g)=>{const v=Ft._FormatErrorMessage(h,_,g);n?n(i,v,new Ko(v,sh.SceneLoaderError,g)):G.Error(v),u()},f=r?_=>{try{r(_)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=()=>{if(s)try{s(i)}catch(_){d("Error in onSuccess callback",_)}i.removePendingData(c)};return Ft._LoadData(h,i,(_,g)=>{if(_.load){if(!_.load(i,g,h.rootUrl,d))return;i.loadingPluginName=_.name,p()}else _.loadAsync(i,g,h.rootUrl,f,h.name).then(()=>{i.loadingPluginName=_.name,p()}).catch(E=>{d(E.message,E)})},f,d,u,a,l)}static AppendAsync(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=""){return new Promise((a,l)=>{Ft.Append(e,t,i,h=>{a(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static LoadAssetContainer(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=null,a=null,l=""){if(!i)return G.Error("No scene available to load asset container to"),null;const h=Ft._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(_,g)=>{const v=Ft._FormatErrorMessage(h,_,g);n?n(i,v,new Ko(v,sh.SceneLoaderError,g)):G.Error(v),u()},f=r?_=>{try{r(_)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=_=>{if(s)try{s(_)}catch(g){d("Error in onSuccess callback",g)}i.removePendingData(c)};return Ft._LoadData(h,i,(_,g)=>{if(_.loadAssetContainer){const E=_.loadAssetContainer(i,g,h.rootUrl,d);if(!E)return;E.populateRootNodes(),i.loadingPluginName=_.name,p(E)}else _.loadAssetContainerAsync?_.loadAssetContainerAsync(i,g,h.rootUrl,f,h.name).then(E=>{E.populateRootNodes(),i.loadingPluginName=_.name,p(E)}).catch(E=>{d(E.message,E)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,u,a,l)}static LoadAssetContainerAsync(e,t="",i=ht.LastCreatedScene,s=null,r=null){return new Promise((n,a)=>{Ft.LoadAssetContainer(e,t,i,l=>{n(l)},s,(l,h,c)=>{a(c||new Error(h))},r)})}static ImportAnimations(e,t="",i=ht.LastCreatedScene,s=!0,r=$l.Clean,n=null,a=null,l=null,h=null,c=null){if(!i){G.Error("No scene available to load animations to");return}if(s){for(const p of i.animatables)p.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(p=>{p.dispose()}),i.getNodes().forEach(p=>{p.animations&&(p.animations=[])})}else switch(r){case $l.Clean:i.animationGroups.slice().forEach(f=>{f.dispose()});break;case $l.Stop:i.animationGroups.forEach(f=>{f.stop()});break;case $l.Sync:i.animationGroups.forEach(f=>{f.reset(),f.restart()});break;case $l.NoSync:break;default:G.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),a&&a(i)};this.LoadAssetContainer(e,t,i,d,l,h,c)}static ImportAnimationsAsync(e,t="",i=ht.LastCreatedScene,s=!0,r=$l.Clean,n=null,a=null,l=null,h=null,c=null){return new Promise((u,d)=>{Ft.ImportAnimations(e,t,i,s,r,n,f=>{u(f)},l,(f,p,_)=>{d(_||new Error(p))},c)})}}Ft.NO_LOGGING=0;Ft.MINIMAL_LOGGING=1;Ft.SUMMARY_LOGGING=2;Ft.DETAILED_LOGGING=3;Ft.OnPluginActivatedObservable=new he;Ft._RegisteredPlugins={};Ft._ShowingLoadingScreen=!1;class ep extends Ie{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new k,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var M;(function(o){o[o.Float=1]="Float",o[o.Int=2]="Int",o[o.Vector2=4]="Vector2",o[o.Vector3=8]="Vector3",o[o.Vector4=16]="Vector4",o[o.Color3=32]="Color3",o[o.Color4=64]="Color4",o[o.Matrix=128]="Matrix",o[o.Object=256]="Object",o[o.AutoDetect=1024]="AutoDetect",o[o.BasedOnInput=2048]="BasedOnInput",o[o.All=4095]="All"})(M||(M={}));var W;(function(o){o[o.Vertex=1]="Vertex",o[o.Fragment=2]="Fragment",o[o.Neutral=4]="Neutral",o[o.VertexAndFragment=3]="VertexAndFragment"})(W||(W={}));class i0{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===W.Fragment;this.compilationString=` +Bad Bone Indices = `+p;return{skinned:!0,valid:r===0&&a===0&&p===0,report:_}}_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 fe.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(P.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(P.PositionKind);const s=T.Zero();let r;for(r=0;r{const d=u.width,f=u.height,_=this.getEngine().createCanvas(d,f).getContext("2d");_.drawImage(u,0,0);const g=_.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(g,d,f,t,i,r,n,a),s&&s(this)};return fe.LoadImage(e,c,l||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,a,l=!1){if(!this.isVerticesDataPresent(P.PositionKind)||!this.isVerticesDataPresent(P.NormalKind)||!this.isVerticesDataPresent(P.UVKind))return G.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(P.PositionKind,!0,!0),c=this.getVerticesData(P.NormalKind),u=this.getVerticesData(P.UVKind);let d=T.Zero();const f=T.Zero(),p=Re.Zero();n=n||Re.Zero(),a=a||new Re(1,1);for(let _=0;_{const h=new Float32Array(i.length*l);let c=0;for(let u=0;u{const a=s.length-1-n,l=s[a];for(let h=0;h{for(let a=0;a-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;r4,h=l?this.getVerticesData(P.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(P.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=T.Zero(),f=new k,p=new k;let _=0,g;for(let v=0;v0&&(k.FromFloat32ArrayToRefScaled(u,Math.floor(n[_+g]*16),E,p),f.addToSelf(p));if(l)for(g=0;g<4;g++)E=c[_+g],E>0&&(k.FromFloat32ArrayToRefScaled(u,Math.floor(h[_+g]*16),E,p),f.addToSelf(p));T.TransformCoordinatesFromFloatsToRef(i._sourcePositions[v],i._sourcePositions[v+1],i._sourcePositions[v+2],f,d),d.toArray(s,v),t&&(T.TransformNormalFromFloatsToRef(i._sourceNormals[v],i._sourceNormals[v+1],i._sourceNormals[v+2],f,d),d.toArray(r,v)),f.reset()}return this.updateVerticesData(P.PositionKind,s),t&&this.updateVerticesData(P.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:T.Zero(),max:T.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?se.MinMax(e):e;return T.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return fx(se._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return Tb(se._MergeMeshesCoroutine(e,t,i,s,r,n,!0),Ww())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,a){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let I=0;for(l=0;l=65536)return G.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{const N=I.computeWorldMatrix(!0);return{vertexData:Oe.ExtractFromMesh(I,!1,!1),transform:N}},{vertexData:_,transform:g}=p(f);a&&(yield);const v=new Array(e.length-1);for(let I=1;I{throw xt("GroundMesh")};se._GoldbergMeshParser=(o,e)=>{throw xt("GoldbergMesh")};se._LinesMeshParser=(o,e)=>{throw xt("LinesMesh")};se._GreasedLineMeshParser=(o,e)=>{throw xt("GreasedLineMesh")};se._GreasedLineRibbonMeshParser=(o,e)=>{throw xt("GreasedLineRibbonMesh")};se._TrailMeshParser=(o,e)=>{throw xt("TrailMesh")};j("BABYLON.Mesh",se);se._instancedMeshFactory=(o,e)=>{const t=new px(o,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class px extends hi{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||t===void 0?void 0:t.receiveShadows)!==e&&fe.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||t===void 0?void 0:t.material)!==e&&fe.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||t===void 0?void 0:t.visibility)!==e&&fe.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||t===void 0?void 0:t.skeleton)!==e&&fe.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||G.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||G.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!==It.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new k);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,K.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(K.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;e0&&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=Yt.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Xe.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Xe.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)})),Xe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=Mi.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=Yt.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Xe.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{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 a of n)a._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===Yt.INTENSITYMODE_AUTOMATIC&&(t===Yt.LIGHTTYPEID_DIRECTIONALLIGHT?i=Yt.INTENSITYMODE_ILLUMINANCE:i=Yt.INTENSITYMODE_LUMINOUSINTENSITY),t){case Yt.LIGHTTYPEID_POINTLIGHT:case Yt.LIGHTTYPEID_SPOTLIGHT:switch(i){case Yt.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Yt.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Yt.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Yt.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Yt.INTENSITYMODE_ILLUMINANCE:e=1;break;case Yt.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case Yt.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Yt.FALLOFF_DEFAULT=Bi.FALLOFF_DEFAULT;Yt.FALLOFF_PHYSICAL=Bi.FALLOFF_PHYSICAL;Yt.FALLOFF_GLTF=Bi.FALLOFF_GLTF;Yt.FALLOFF_STANDARD=Bi.FALLOFF_STANDARD;Yt.LIGHTMAP_DEFAULT=Bi.LIGHTMAP_DEFAULT;Yt.LIGHTMAP_SPECULAR=Bi.LIGHTMAP_SPECULAR;Yt.LIGHTMAP_SHADOWSONLY=Bi.LIGHTMAP_SHADOWSONLY;Yt.INTENSITYMODE_AUTOMATIC=Bi.INTENSITYMODE_AUTOMATIC;Yt.INTENSITYMODE_LUMINOUSPOWER=Bi.INTENSITYMODE_LUMINOUSPOWER;Yt.INTENSITYMODE_LUMINOUSINTENSITY=Bi.INTENSITYMODE_LUMINOUSINTENSITY;Yt.INTENSITYMODE_ILLUMINANCE=Bi.INTENSITYMODE_ILLUMINANCE;Yt.INTENSITYMODE_LUMINANCE=Bi.INTENSITYMODE_LUMINANCE;Yt.LIGHTTYPEID_POINTLIGHT=Bi.LIGHTTYPEID_POINTLIGHT;Yt.LIGHTTYPEID_DIRECTIONALLIGHT=Bi.LIGHTTYPEID_DIRECTIONALLIGHT;Yt.LIGHTTYPEID_SPOTLIGHT=Bi.LIGHTTYPEID_SPOTLIGHT;Yt.LIGHTTYPEID_HEMISPHERICLIGHT=Bi.LIGHTTYPEID_HEMISPHERICLIGHT;A([ds()],Yt.prototype,"diffuse",void 0);A([ds()],Yt.prototype,"specular",void 0);A([D()],Yt.prototype,"falloffType",void 0);A([D()],Yt.prototype,"intensity",void 0);A([D()],Yt.prototype,"range",null);A([D()],Yt.prototype,"intensityMode",null);A([D()],Yt.prototype,"radius",null);A([D()],Yt.prototype,"_renderPriority",void 0);A([Ce("_reorderLightsInScene")],Yt.prototype,"renderPriority",void 0);A([D("shadowEnabled")],Yt.prototype,"_shadowEnabled",void 0);A([D("excludeWithLayerMask")],Yt.prototype,"_excludeWithLayerMask",void 0);A([D("includeOnlyWithLayerMask")],Yt.prototype,"_includeOnlyWithLayerMask",void 0);A([D("lightmapMode")],Yt.prototype,"_lightmapMode",void 0);class sF extends ks{}class rF{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 nF extends ks{constructor(e){super(),this._wasAddedToScene=!1,e=e||ht.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 a of e)t.set(a.uniqueId,a);const i={dependsOn:new Map,dependedBy:new Map};for(const a of e){const l=a.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const a of e){const l=a.uniqueId,h=i.dependsOn.get(l);if(a instanceof px){const u=a.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 a.getDescendants()){const d=u.uniqueId;t.has(d)&&(c.add(d),i.dependsOn.get(d).add(l))}}const s=[],r=[];for(const a of e){const l=a.uniqueId;i.dependsOn.get(l).size===0&&(r.push(a),t.delete(l))}const n=r;for(;n.length>0;){const a=n.shift();s.push(a);const l=i.dependedBy.get(a.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(a.uniqueId),c.size===0&&t.get(h)&&(n.push(t.get(h)),t.delete(h))}}return t.size>0&&(G.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(a=>G.Error(a.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 se&&this.meshes.indexOf(e)!==-1||e instanceof It&&this.transformNodes.indexOf(e)!==-1||e instanceof Yt&&this.lights.indexOf(e)!==-1||e instanceof et&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return G.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 G.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 G.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 G.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||fe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new rF,a=[],l=[],h=Object.assign({doNotInstantiate:!0},i),c=(_,g)=>{if(s[_.uniqueId]=g.uniqueId,r[g.uniqueId]=g,e&&(g.name=e(_.name)),g instanceof se){const v=g;if(v.morphTargetManager){const E=_.morphTargetManager;v.morphTargetManager=E.clone();for(let C=0;C{if(c(_,g),_.parent){const v=s[_.parent.uniqueId],E=r[v];E?g.parent=E:g.parent=_.parent}if(g.position&&_.position&&g.position.copyFrom(_.position),g.rotationQuaternion&&_.rotationQuaternion&&g.rotationQuaternion.copyFrom(_.rotationQuaternion),g.rotation&&_.rotation&&g.rotation.copyFrom(_.rotation),g.scaling&&_.scaling&&g.scaling.copyFrom(_.scaling),g.material){const v=g;if(v.material)if(t){const E=_.material;if(l.indexOf(E)===-1){let C=E.clone(e?e(E.name):"Clone of "+E.name);if(l.push(E),s[E.uniqueId]=C.uniqueId,r[C.uniqueId]=C,E.getClassName()==="MultiMaterial"){const S=E;for(const b of S.subMaterials)b&&(C=b.clone(e?e(b.name):"Clone of "+b.name),l.push(b),s[b.uniqueId]=C.uniqueId,r[C.uniqueId]=C);S.subMaterials=S.subMaterials.map(b=>b&&r[s[b.uniqueId]])}}v.getClassName()!=="InstancedMesh"&&(v.material=r[s[E.uniqueId]])}else v.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(v.material)===-1&&this.scene.addMultiMaterial(v.material):this.scene.materials.indexOf(v.material)===-1&&this.scene.addMaterial(v.material)}g.parent===null&&n.rootNodes.push(g)};return f.forEach(_=>{if(_.getClassName()==="InstancedMesh"){const g=_,v=g.sourceMesh,E=s[v.uniqueId],S=(typeof E=="number"?r[E]:v).createInstance(g.name);p(g,S)}else{let g=!0;_.getClassName()==="TransformNode"||_.getClassName()==="Node"||_.skeleton||!_.getTotalVertices||_.getTotalVertices()===0?g=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?g=!h.doNotInstantiate(_):g=!h.doNotInstantiate);const v=g?_.createInstance(`instance of ${_.name}`):_.clone(`Clone of ${_.name}`,null,!0);if(!v)throw new Error(`Could not clone or instantiate node on Asset Container ${_.name}`);p(_,v)}}),this.skeletons.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const g=_.clone(e?e(_.name):"Clone of "+_.name);for(const v of this.meshes)if(v.skeleton===_&&!v.isAnInstance){const E=r[s[v.uniqueId]];if(!E||E.isAnInstance||(E.skeleton=g,a.indexOf(g)!==-1))continue;a.push(g);for(const C of g.bones)C._linkedTransformNode&&(C._linkedTransformNode=r[s[C._linkedTransformNode.uniqueId]])}n.skeletons.push(g)}),this.animationGroups.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const g=_.clone(e?e(_.name):"Clone of "+_.name,v=>r[s[v.uniqueId]]||v);n.animationGroups.push(g)}),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||fe.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()||fe.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 sF);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 se("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=ht.LastCreatedScene,t,i=null){if(!e)return G.Error("No scene available to merge animations to"),[];const s=i||(a=>{let l=null;const h=a.animations.length?a.animations[0].targetProperty:"",c=a.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(a.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(a.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(a.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(a=>{const l=s(a);if(l!==null){for(const h of a.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(a.animations)}});const n=[];return this.animationGroups.slice().forEach(a=>{n.push(a.clone(a.name,s)),a.animatables.forEach(l=>{l.stop()})}),t.forEach(a=>{const l=s(a.target);l&&(e.beginAnimation(l,a.fromFrame,a.toFrame,a.loopAnimation,a.speedRatio,a.onAnimationEnd?a.onAnimationEnd:void 0,void 0,!0,void 0,a.onAnimationLoop?a.onAnimationLoop:void 0),e.stopAnimation(a.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 se?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof It?this.transformNodes.push(s):s instanceof Yt?this.lights.push(s):s instanceof et&&this.cameras.push(s),s instanceof hi){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()}}re.AudioEngineFactory=(o,e,t)=>new aF(o,e,t);class aF{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 he,this.onAudioLockedObservable=new he,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!gr())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||e===void 0?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?(t=this._audioContext)===null||t===void 0||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return!((e=this._audioContext)===null||e===void 0)&&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,G.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 Yo{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=re.audioEngine)===null||e===void 0)&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:re.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,a,l,h,c;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 he,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=T.Zero(),this._localDirection=new T(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||ht.LastCreatedScene,!!i)if(this._scene=i,Yo._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(u,d,f,p,_)=>d0&&(f=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":d.push(t);case"Array":d.length===0&&(d=t);for(let p=0;p{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(_,g=>{this._soundLoaded(g)},void 0,!0,!0,g=>{g&&G.Error("XHR "+g.status+" error on: "+_+"."),G.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:u=!1;break}u?f||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):G.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{G.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),re.audioEngine&&!re.audioEngine.WarnedWebAudioUnsupported&&(G.Error("Web Audio is not supported by your browser."),re.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;!((e=re.audioEngine)===null||e===void 0)&&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=re.audioEngine)===null||t===void 0)&&t.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.audioContext&&re.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{G.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,s,r,n,a,l,h,c,u,d;e&&(this.loop=(t=e.loop)!==null&&t!==void 0?t:this.loop,this.maxDistance=(i=e.maxDistance)!==null&&i!==void 0?i:this.maxDistance,this.useCustomAttenuation=(s=e.useCustomAttenuation)!==null&&s!==void 0?s:this.useCustomAttenuation,this.rolloffFactor=(r=e.rolloffFactor)!==null&&r!==void 0?r:this.rolloffFactor,this.refDistance=(n=e.refDistance)!==null&&n!==void 0?n:this.refDistance,this.distanceModel=(a=e.distanceModel)!==null&&a!==void 0?a:this.distanceModel,this._playbackRate=(l=e.playbackRate)!==null&&l!==void 0?l:this._playbackRate,this._length=(h=e.length)!==null&&h!==void 0?h:void 0,this.spatialSound=(c=e.spatialSound)!==null&&c!==void 0?c:this._spatialSound,this._setOffset((u=e.offset)!==null&&u!==void 0?u:void 0),this.setVolume((d=e.volume)!==null&&d!==void 0?d: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,t;!((e=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&re.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=(t=this._soundPanner)!==null&&t!==void 0?t:re.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===void 0||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=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;!((t=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{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=re.audioEngine)===null||c===void 0)&&c.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,p;(f=re.audioEngine)===null||f===void 0||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(p=re.audioEngine)===null||p===void 0?void 0:p.onAudioUnlockedObservable.addOnce(()=>{h()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=re.audioEngine)===null||u===void 0?void 0:u.onAudioUnlockedObservable.addOnce(()=>{h()}))};h()}}else{const h=()=>{var c,u,d,f;if(!((c=re.audioEngine)===null||c===void 0)&&c.audioContext){if(i=i||this._length,t!==void 0&&this._setOffset(t),this._soundSource){const p=this._soundSource;p.onended=()=>{p.disconnect()}}if(this._soundSource=(u=re.audioEngine)===null||u===void 0?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=re.audioEngine)===null||d===void 0?void 0:d.audioContext.currentTime)+e:re.audioEngine.audioContext.currentTime;const p=((this.isPaused?this.currentTime:0)+((f=this._offset)!==null&&f!==void 0?f:0))%this._soundSource.buffer.duration;this._soundSource.start(l,p,this.loop?void 0:i)}}};((a=re.audioEngine)===null||a===void 0?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var c;((c=re.audioEngine)===null||c===void 0?void 0:c.audioContext.state)==="suspended"?(re.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=re.audioEngine.onAudioUnlockedObservable.addOnce(()=>{h()}))):h()},500):h()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){G.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=re.audioEngine)===null||t===void 0)&&t.audioContext&&this._soundSource){const i=e?re.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=re.audioEngine)===null||e===void 0)&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=re.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;!((i=re.audioEngine)===null||i===void 0)&&i.canUseWebAudio&&this._soundGain&&(t&&re.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(re.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,re.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,re.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=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Yo(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 a={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let l;if(!s)l=new Yo(r,n,t,()=>{t.removePendingData(l)},a),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 Yo(r,new ArrayBuffer(0),t,null,a),h()}if(e.position){const h=T.FromArray(e.position);l.setPosition(h)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const h=T.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=re.audioEngine)===null||e===void 0||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Yo._SceneComponentInitialization=o=>{throw xt("AudioSceneComponent")};class oF{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||ht.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=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio&&re.audioEngine.audioContext&&(this._outputAudioNode=re.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(re.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(re.audioEngine&&re.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=re.audioEngine)===null||t===void 0)&&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=re.audioEngine)===null||t===void 0)&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(!((e=re.audioEngine)===null||e===void 0)&&e.canUseWebAudio)for(let t=0;t{var s;let r=[],n;if(t.sounds=t.sounds||[],o.sounds!==void 0&&o.sounds!==null)for(let a=0,l=o.sounds.length;a{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;t0&&(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),T.TransformNormalToRef(Gn._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{let e=o._getComponent(Fe.NAME_AUDIO);e||(e=new Gn(o),o._addComponent(e))};class pu{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,e=e||ht.LastCreatedScene,e&&(this._scene=e,this.animationParameters=new Dt(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 pu(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,s=30){this.animationParameters=new Dt(e,t,i,s)}dispose(e){var t;e&&((t=this._texture)===null||t===void 0||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([Jt(),Ce("_markSubMeshesAsAttributesDirty")],pu.prototype,"texture",void 0);A([D(),Ce("_markSubMeshesAsAttributesDirty")],pu.prototype,"isEnabled",void 0);A([D()],pu.prototype,"animationParameters",void 0);A([D()],pu.prototype,"time",void 0);class Uh{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=ya.Zero(),this._cachedBaseSize=ya.Zero(),this._initialSamplingMode=2,this._texture=Uh._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 Ei extends Uh{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===void 0||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===void 0||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=du()),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=Ei.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 he,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Ei._IsScene(e)?this._scene=e:this._engine=e:this._scene=ht.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 k.IdentityReadOnly}getReflectionTextureMatrix(){return k.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 a=this._getEngine();if(!a)return null;const l=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let c=0;c=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=Xe.Serialize(this);return Xe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Ei.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;A([D()],Ei.prototype,"uniqueId",void 0);A([D()],Ei.prototype,"name",void 0);A([D()],Ei.prototype,"metadata",void 0);A([D("hasAlpha")],Ei.prototype,"_hasAlpha",void 0);A([D("getAlphaFromRGB")],Ei.prototype,"_getAlphaFromRGB",void 0);A([D()],Ei.prototype,"level",void 0);A([D("coordinatesIndex")],Ei.prototype,"_coordinatesIndex",void 0);A([D()],Ei.prototype,"optimizeUVAllocation",void 0);A([D("coordinatesMode")],Ei.prototype,"_coordinatesMode",void 0);A([D()],Ei.prototype,"wrapU",null);A([D()],Ei.prototype,"wrapV",null);A([D()],Ei.prototype,"wrapR",void 0);A([D()],Ei.prototype,"anisotropicFilteringLevel",void 0);A([D()],Ei.prototype,"isCube",null);A([D()],Ei.prototype,"is3D",null);A([D()],Ei.prototype,"is2DArray",null);A([D()],Ei.prototype,"gammaSpace",null);A([D()],Ei.prototype,"invertZ",void 0);A([D()],Ei.prototype,"lodLevelInAlpha",void 0);A([D()],Ei.prototype,"lodGenerationOffset",null);A([D()],Ei.prototype,"lodGenerationScale",null);A([D()],Ei.prototype,"linearSpecularLOD",null);A([Jt()],Ei.prototype,"irradianceTexture",null);A([D()],Ei.prototype,"isRenderTarget",void 0);function Sb(o,e,t=!1){const i=e.width,s=e.height;if(o instanceof Float32Array){let h=o.byteLength/o.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=o[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}o=c}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const a=n.createImageData(i,s);if(a.data.set(o),n.putImageData(a,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 lF(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=o._readPixelsSync(e,t);return s?Sb(s,o.getSize(),i.invertY):null}async function hF(o,e=0,t=0){const i=o.getInternalTexture();if(!i)return null;const s=await o.readPixels(e,t);return s?Sb(s,o.getSize(),i.invertY):null}class ee extends Ei{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=ee.TRILINEAR_SAMPLINGMODE,a={},l,h=5){throw xt("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=ee.TRILINEAR_SAMPLINGMODE,n=null,a=null,l=null,h=!1,c,u,d,f,p){var _,g,v,E,C,S,b,R,I,N;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 he,this._isBlocking=!0,this.name=e||"",this.url=e;let O,L=!1,B=null,V=!0;typeof i=="object"&&i!==null?(O=(_=i.noMipmap)!==null&&_!==void 0?_:!1,s=(g=i.invertY)!==null&&g!==void 0?g:!pi.UseOpenGLOrientationForUV,r=(v=i.samplingMode)!==null&&v!==void 0?v:ee.TRILINEAR_SAMPLINGMODE,n=(E=i.onLoad)!==null&&E!==void 0?E:null,a=(C=i.onError)!==null&&C!==void 0?C:null,l=(S=i.buffer)!==null&&S!==void 0?S:null,h=(b=i.deleteBuffer)!==null&&b!==void 0?b:!1,c=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,L=(R=i.useSRGBBuffer)!==null&&R!==void 0?R:!1,B=(I=i.internalTexture)!==null&&I!==void 0?I:null,V=(N=i.gammaSpace)!==null&&N!==void 0?N:V):O=!!i,this._gammaSpace=V,this._noMipmap=O,this._invertY=s===void 0?!pi.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=L,this._forcedExtension=p,c&&(this._format=c);const Z=this.getScene(),ue=this._getEngine();if(!ue)return;ue.onBeforeTextureInitObservable.notifyObservers(this);const oe=()=>{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&&Z&&Z.resetCachedMaterial()},me=(le,ae)=>{this._loadingError=!0,this._errorObject={message:le,exception:ae},a&&a(le,ae),ee.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!B){this._delayedOnLoad=oe,this._delayedOnError=me;return}if(this._texture=B??this._getFromCache(this.url,O,r,this._invertY,L,this.isCube),this._texture)if(this._texture.isReady)Qc.SetImmediate(()=>oe());else{const le=this._texture.onLoadedObservable.add(oe);this._texture.onErrorObservable.add(ae=>{var ce;me(ae.message,ae.exception),(ce=this._texture)===null||ce===void 0||ce.onLoadedObservable.remove(le)})}else if(!Z||!Z.useDelayedTextureLoading){try{this._texture=ue.createTexture(this.url,O,this._invertY,Z,r,oe,me,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,L)}catch(le){throw me("error loading",le),le}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=oe,this._delayedOnError=me}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?Qc.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,T.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=k.Zero(),this._rowGenerationMatrix=new k,this._t0=T.Zero(),this._t1=T.Zero(),this._t2=T.Zero()),k.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(k.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,K.Matrix[0]),k.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,K.Matrix[1]),k.ScalingToRef(this._cachedUScale,this._cachedVScale,0,K.Matrix[2]),k.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,K.Matrix[3]),K.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(K.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),k.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===ee.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=k.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=k.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 ee.PLANAR_MODE:{k.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 ee.PROJECTION_MODE:{k.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:k.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 Xe.Clone(()=>new ee(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;const i=this.name;ee.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const s=super.serialize(ee._SerializeInternalTextureUniqueId);return s?((ee.SerializeBuffers||ee.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(s.base64String=this._buffer,s.name=s.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?s.base64String="data:image/png;base64,"+ab(this._buffer):(ee.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(s.base64String=!this._engine||this._engine._features.supportSyncTextureRead?lF(this):hF(this))),s.invertY=this._invertY,s.samplingMode=this.samplingMode,s._creationFlags=this._creationFlags,s._useSRGBBuffer=this._useSRGBBuffer,ee._SerializeInternalTextureUniqueId&&(s.internalTextureUniqueId=(t=(e=this._texture)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:void 0),s.noMipmap=this._noMipmap,this.name=i,s):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=td.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 ee._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{var l,h,c;let u=!0;if(e.noMipmap&&(u=!1),e.mirrorPlane){const d=ee._CreateMirror(e.name,e.renderTargetSize,t,u);return d._waitingRenderList=e.renderList,d.mirrorPlane=Rn.FromArray(e.mirrorPlane),n(d),d}else if(e.isRenderTarget){let d=null;if(e.isCube){if(t.reflectionProbes)for(let f=0;f{n(d)},(h=e._creationFlags)!==null&&h!==void 0?h:0,(c=e._useSRGBBuffer)!==null&&c!==void 0?c:!1),d.name=e.name;else{let f;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?f=e.name:f=i+e.name,e.url&&(e.url.startsWith("data:")||ee.UseSerializedUrlIfAny)&&(f=e.url);const p={noMipmap:!u,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(d)},internalTexture:r};d=new ee(f,t,p)}return d}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=ee.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c){return new ee("data:"+t,i,s,r,n,a,l,e,!1,h,void 0,void 0,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,a=ee.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u){return e.substr(0,5)!=="data:"&&(e="data:"+e),new ee(e,i,r,n,a,l,h,t,s,c,void 0,void 0,u)}}ee.SerializeBuffers=!0;ee.ForceSerializeBuffers=!1;ee.OnTextureLoadErrorObservable=new he;ee._SerializeInternalTextureUniqueId=!1;ee._CubeTextureParser=(o,e,t)=>{throw xt("CubeTexture")};ee._CreateMirror=(o,e,t,i)=>{throw xt("MirrorTexture")};ee._CreateRenderTargetTexture=(o,e,t,i,s)=>{throw xt("RenderTargetTexture")};ee.NEAREST_SAMPLINGMODE=1;ee.NEAREST_NEAREST_MIPLINEAR=8;ee.BILINEAR_SAMPLINGMODE=2;ee.LINEAR_LINEAR_MIPNEAREST=11;ee.TRILINEAR_SAMPLINGMODE=3;ee.LINEAR_LINEAR_MIPLINEAR=3;ee.NEAREST_NEAREST_MIPNEAREST=4;ee.NEAREST_LINEAR_MIPNEAREST=5;ee.NEAREST_LINEAR_MIPLINEAR=6;ee.NEAREST_LINEAR=7;ee.NEAREST_NEAREST=1;ee.LINEAR_NEAREST_MIPNEAREST=9;ee.LINEAR_NEAREST_MIPLINEAR=10;ee.LINEAR_LINEAR=2;ee.LINEAR_NEAREST=12;ee.EXPLICIT_MODE=0;ee.SPHERICAL_MODE=1;ee.PLANAR_MODE=2;ee.CUBIC_MODE=3;ee.PROJECTION_MODE=4;ee.SKYBOX_MODE=5;ee.INVCUBIC_MODE=6;ee.EQUIRECTANGULAR_MODE=7;ee.FIXED_EQUIRECTANGULAR_MODE=8;ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ee.CLAMP_ADDRESSMODE=0;ee.WRAP_ADDRESSMODE=1;ee.MIRROR_ADDRESSMODE=2;ee.UseSerializedUrlIfAny=!1;A([D()],ee.prototype,"url",void 0);A([D()],ee.prototype,"uOffset",void 0);A([D()],ee.prototype,"vOffset",void 0);A([D()],ee.prototype,"uScale",void 0);A([D()],ee.prototype,"vScale",void 0);A([D()],ee.prototype,"uAng",void 0);A([D()],ee.prototype,"vAng",void 0);A([D()],ee.prototype,"wAng",void 0);A([D()],ee.prototype,"uRotationCenter",void 0);A([D()],ee.prototype,"vRotationCenter",void 0);A([D()],ee.prototype,"wRotationCenter",void 0);A([D()],ee.prototype,"homogeneousRotationInUVTransform",void 0);A([D()],ee.prototype,"isBlocking",null);j("BABYLON.Texture",ee);Xe._TextureParser=ee.Parse;We.prototype.updateRawTexture=function(o,e,t,i,s=null,r=0,n=!1){if(!o)return;const a=this._getRGBABufferInternalSizedFormat(r,t,n),l=this._getInternalFormat(t),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,o,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.type=r,o.invertY=i,o._compression=s),o.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],o.width,o.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,o.width,o.height,0,l,h,e),o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),o.isReady=!0};We.prototype.createRawTexture=function(o,e,t,i,s,r,n,a=null,l=0,h=0,c=!1){const u=new Ti(this,Ut.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=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=o),this.updateRawTexture(u,o,i,r,a,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};We.prototype.createRawCubeTexture=function(o,e,t,i,s,r,n,a=null){const l=this._gl,h=new Ti(this,Ut.CubeRaw);h.isCube=!0,h.format=t,h.type=i,this._doNotHandleContextLost||(h._bufferViewArray=o);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,G.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,G.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,G.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,G.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=a,!this.needPOTTextures||fe.IsExponentOfTwo(h.width)&&fe.IsExponentOfTwo(h.height)||(s=!1),o)this.updateRawCubeTexture(h,o,t,i,r,a);else{const g=this._getRGBABufferInternalSizedFormat(i),v=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let E=0;E<6;E++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+E,v,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+E,v,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),o&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const _=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.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};We.prototype.updateRawCubeTexture=function(o,e,t,i,s,r=null,n=0){o._bufferViewArray=e,o.format=t,o.type=i,o.invertY=s,o._compression=r;const a=this._gl,l=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,o,!0),this._unpackFlipY(s===void 0?!0:!!s),o.width%4!==0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let p=e[f];r?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,this.getCaps().s3tc[r],o.width,o.height,0,p):(u&&(p=Cb(p,o.width,o.height,i)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,c,o.width,o.height,0,h,l,p))}(!this.needPOTTextures||fe.IsExponentOfTwo(o.width)&&fe.IsExponentOfTwo(o.height))&&o.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),o.isReady=!0};We.prototype.createRawCubeTextureFromUrl=function(o,e,t,i,s,r,n,a,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=o,f.isReady=!1,this._internalTexturesCache.push(f);const p=(g,v)=>{e==null||e.removePendingData(f),h&&g&&h(g.status+" "+g.statusText,v)},_=g=>{const v=f.width,E=n(g);if(E){if(a){const C=this._getWebGLTextureType(s);let S=this._getInternalFormat(i);const b=this._getRGBABufferInternalSizedFormat(s);let R=!1;S===d.RGB&&(S=d.RGBA,R=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const I=a(E);for(let N=0;N>N;for(let L=0;L<6;L++){let B=I[N][L];R&&(B=Cb(B,O,O,s)),d.texImage2D(L,N,b,O,O,0,S,C,B)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,E,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(o,g=>{_(g)},void 0,e==null?void 0:e.offlineProvider,!0,p),f};function Cb(o,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;n0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===rt.POINTERDOWN){this._isPointerDown=!0;return}i.type===rt.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=ar.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??ar.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)<$t:!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=ar.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 zh{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)return;i.computeWorldMatrix(!0);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||(zh.EasingFunction.setEasingMode(zh.EasingMode),this._radiusBounceTransition=Ee.CreateAnimation("radius",Ee.ANIMATIONTYPE_FLOAT,60,zh.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ee.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()}}zh.EasingFunction=new Uw(.3);zh.EasingMode=ln.EASINGMODE_EASEOUT;class Un{constructor(){this.onTargetFramingAnimationEndObservable=new he,this._mode=Un.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();Un.EasingFunction.setEasingMode(Un.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===rt.POINTERDOWN){this._isPointerDown=!0;return}i.type===rt.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&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 T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n{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===Un.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=ar.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=Ee.CreateAnimation("beta",Ee.ANIMATIONTYPE_FLOAT,60,Un.EasingFunction));const s=Ee.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=ar.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}}Un.EasingFunction=new kw;Un.EasingMode=ln.EASINGMODE_EASEINOUT;Un.IgnoreBoundsSizeMode=0;Un.FitFrustumSidesMode=1;class Kt{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new Kt(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Kt._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Kt._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n=0,a=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.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),a=Math.min(c,a),n>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.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),a=Math.min(c,a),n>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.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),a=Math.min(c,a),n>a)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,a=e.radius+t,l=a*a;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=Kt._TmpVector3[0],r=Kt._TmpVector3[1],n=Kt._TmpVector3[2],a=Kt._TmpVector3[3],l=Kt._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),T.CrossToRef(this.direction,r,n);const h=T.Dot(s,n);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,a);const u=T.Dot(a,n)*c;if(u<0||u>1)return null;T.CrossToRef(a,s,l);const d=T.Dot(this.direction,l)*c;if(d<0||u+d>1)return null;const f=T.Dot(r,l)*c;return f>this.length?null:new wv(1-u-d,u,f)}intersectsPlane(e){let t;const i=T.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=T.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 T(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 T(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 T(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 a=K.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?Kt.TransformToRef(this,a,this._tmpRay):this._tmpRay=Kt.Transform(this,a),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=K.Vector3[0],n=K.Vector3[1],a=K.Vector3[2],l=K.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Kt._Rayl,a),s.addToRef(a,n),e.subtractToRef(s,l);const h=T.Dot(r,r),c=T.Dot(r,a),u=T.Dot(a,a),d=T.Dot(r,l),f=T.Dot(a,l),p=h*u-c*c;let _,g=p,v,E=p;pg&&(_=g,v=f+c,E=u)),v<0?(v=0,-d<0?_=0:-d>h?_=g:(_=-d,g=h)):v>E&&(v=E,-d+c<0?_=0:-d+c>h?_=g:(_=-d+c,g=h));const C=Math.abs(_)0&&S<=this.length&&I.lengthSquared()=o.distance?null:h};Qe.prototype._internalPick=function(o,e,t,i,s){let r=null;const n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n(this._tempPickingRay||(this._tempPickingRay=Kt.Zero()),this.createPickingRayToRef(o,e,n,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return r&&(r.ray=this.createPickingRay(o,e,k.Identity(),s||null)),r};Object.defineProperty(Qe.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Qe.prototype.pick=function(o,e,t,i,s,r,n=!1){const a=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=Kt.Zero()),this.createPickingRayToRef(o,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,r);return a&&(a.ray=this.createPickingRay(o,e,k.Identity(),s||null)),a};Qe.prototype.pickWithRay=function(o,e,t,i){const s=this._internalPick(r=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=k.Identity()),r.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Kt.Zero()),Kt.TransformToRef(o,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=o),s};Qe.prototype.multiPick=function(o,e,t,i,s){return this._internalMultiPick(r=>this.createPickingRay(o,e,r,i||null),t,s)};Qe.prototype.multiPickWithRay=function(o,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=k.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Kt.Zero()),Kt.TransformToRef(o,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};et.prototype.getForwardRay=function(o=100,e,t){return this.getForwardRayToRef(new Kt(T.Zero(),T.Zero(),o),o,e,t)};et.prototype.getForwardRayToRef=function(o,e=100,t,i){t||(t=this.getWorldMatrix()),o.length=e,i?o.origin.copyFrom(i):o.origin.copyFrom(this.position);const s=K.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);const r=K.Vector3[3];return T.TransformNormalToRef(s,t,r),T.NormalizeToRef(r,o.direction),o};function _x(o){const e=[],t=[],i=[],s=[],r=o.width||o.size||1,n=o.height||o.size||1,a=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,l=r/2,h=n/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,pi.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,pi.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,pi.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,pi.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Oe._ComputeSides(a,t,e,i,s,o.frontUVs,o.backUVs);const c=new Oe;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function J_(o,e={},t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,_x(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}Oe.CreatePlane=_x;se.CreatePlane=(o,e,t,i,s)=>J_(o,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);class oi{}oi.ANCHOR_SYSTEM="xr-anchor-system";oi.BACKGROUND_REMOVER="xr-background-remover";oi.HIT_TEST="xr-hit-test";oi.MESH_DETECTION="xr-mesh-detection";oi.PHYSICS_CONTROLLERS="xr-physics-controller";oi.PLANE_DETECTION="xr-plane-detection";oi.POINTER_SELECTION="xr-controller-pointer-selection";oi.TELEPORTATION="xr-controller-teleportation";oi.FEATURE_POINTS="xr-feature-points";oi.HAND_TRACKING="xr-hand-tracking";oi.IMAGE_TRACKING="xr-image-tracking";oi.NEAR_INTERACTION="xr-near-interaction";oi.DOM_OVERLAY="xr-dom-overlay";oi.MOVEMENT="xr-controller-movement";oi.LIGHT_ESTIMATION="xr-light-estimation";oi.EYE_TRACKING="xr-eye-tracking";oi.WALKING_LOCOMOTION="xr-walking-locomotion";oi.LAYERS="xr-layers";oi.DEPTH_SENSING="xr-depth-sensing";oi.SPACE_WARP="xr-space-warp";oi.RAW_CAMERA_ACCESS="xr-raw-camera-access";class _s{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()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.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 a=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(t==="stable"?a=_s.GetStableVersionOfFeature(n):t==="latest"?a=_s.GetLatestVersionOfFeature(n):a=+t,a===-1||isNaN(a))throw new Error(`feature not found - ${n} (${t})`)}else a=t;const l=_s._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=_s.ConstructFeature(n,a,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:a,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 fe.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=Object.assign(Object.assign({},e),n)}}return e}}_s._AvailableFeatures={};_s._ConflictingFeatures={[oi.TELEPORTATION]:oi.MOVEMENT,[oi.MOVEMENT]:oi.TELEPORTATION};class Cr{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName="",this.onFeatureAttachObservable=new he,this.onFeatureDetachObservable=new he}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,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){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class ts{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)}}ts.DistanceJoint=0;ts.HingeJoint=1;ts.BallAndSocketJoint=2;ts.WheelJoint=3;ts.SliderJoint=4;ts.PrismaticJoint=5;ts.UniversalJoint=6;ts.Hinge2Joint=ts.WheelJoint;ts.PointToPointJoint=8;ts.SpringJoint=9;ts.LockJoint=10;se._PhysicsImpostorParser=function(o,e,t){return new Ct(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},o)};class Ct{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=T.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Se,this._tmpQuat2=new Se,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 Se),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,Ct._TmpVecs[0]),this.object.translate(Ct._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(a=>a.otherImpostors.indexOf(n)!==-1).forEach(a=>{a.callback(this,n,r.point,r.distance,r.impulse,r.normal)}))},!this.object){G.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&G.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=Se.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Se),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&&G.Warn("You must affect impostors to children before affecting impostor to parent.")):G.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 hi?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=Ct.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 Ct.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):T.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):T.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):G.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):G.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,a)=>{if(n.callback===t&&n.otherImpostors.length===i.length){const l=n.otherImpostors.every(h=>i.indexOf(h)>-1);return l&&(s=a),l}return!1})?this._onPhysicsCollideCallbacks.splice(s,1):G.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):Se.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 ts(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 Ct(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 Se),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=Ct._TmpVecs[0],a=this.object;if(a.rotationQuaternion)if(r){const l=Ct._TmpQuat;a.rotationQuaternion.multiplyToRef(r,l),e.setRotationQuaternion(l,_i.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,_i.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(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const a=this.object;if(a.rotationQuaternion)if(r){const c=Ct._TmpQuat;e.getRotationQuaternionToRef(_i.WORLD,t,c),c.multiplyToRef(r,a.rotationQuaternion)}else e.getRotationQuaternionToRef(_i.WORLD,t,a.rotationQuaternion);const l=Ct._TmpVecs[0],h=Ct._TmpVecs[1];n||(n=Ct._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),a.setAbsolutePosition(l)}}Ct.DEFAULT_OBJECT_SIZE=new T(1,1,1);Ct.IDENTITY_QUATERNION=Se.Identity();Ct._TmpVecs=js.BuildArray(3,T.Zero);Ct._TmpQuat=Se.Identity();Ct.NoImpostor=0;Ct.SphereImpostor=1;Ct.BoxImpostor=2;Ct.PlaneImpostor=3;Ct.MeshImpostor=4;Ct.CapsuleImpostor=6;Ct.CylinderImpostor=7;Ct.ParticleImpostor=8;Ct.HeightmapImpostor=9;Ct.ConvexHullImpostor=10;Ct.CustomImpostor=100;Ct.RopeImpostor=101;Ct.ClothImpostor=102;Ct.SoftbodyImpostor=103;var Kl;(function(o){o[o.Clean=0]="Clean",o[o.Stop=1]="Stop",o[o.Sync=2]="Sync",o[o.NoSync=3]="NoSync"})(Kl||(Kl={}));class Lt{static get ForceFullSceneLoadingForIncremental(){return nr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nr.ShowLoadingScreen}static set ShowLoadingScreen(e){nr.ShowLoadingScreen=e}static get loggingLevel(){return nr.loggingLevel}static set loggingLevel(e){nr.loggingLevel=e}static get CleanBoneMatrixWeights(){return nr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Lt._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=Lt._RegisteredPlugins[e];return t||(G.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"),Lt.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Lt._RegisteredPlugins){const i=Lt._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Lt._RegisteredPlugins[t]}return Lt.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 Lt._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,a,l){const h=Lt._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=a?Lt._GetPluginForExtension(a):h?Lt._GetPluginForDirectLoad(e.url):Lt._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(Lt.OnPluginActivatedObservable.notifyObservers(u),h&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!ux(e.url))){if(u.directLoad){const S=u.directLoad(t,h);S.then?S.then(b=>{i(u,b)}).catch(b=>{r("Error in directLoad of _loadData: "+b,b)}):i(u,S)}else i(u,h);return u}const d=c.isBinary,f=(S,b)=>{if(t.isDisposed){r("Scene has been disposed");return}i(u,S,b)};let p=null,_=!1;const g=u.onDisposeObservable;g&&g.add(()=>{_=!0,p&&(p.abort(),p=null),n()});const v=()=>{if(_)return;const S=(b,R)=>{r(b==null?void 0:b.statusText,R)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,s,d,S,l):t._loadFile(e.file||e.url,f,s,!0,d,S)},E=t.getEngine();let C=E.enableOfflineSupport;if(C){let S=!1;for(const b of t.disableOfflineSupportExceptionRules)if(b.test(e.url)){S=!0;break}C=!S}return C&&re.OfflineProviderFactory?t.offlineProvider=re.OfflineProviderFactory(e.url,v,E.disableManifestCheck):v(),u}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(!t)i=e,s=fe.GetFilename(e),e=fe.GetFolderPath(e);else if(t.name){const a=t;i=`file:${a.name}`,s=a.name,r=a}else if(ArrayBuffer.isView(t))i="",s="arrayBuffer",n=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const a=t;if(a.substr(0,1)==="/")return fe.Error("Wrong sceneFilename parameter"),null;i=e+a,s=a}return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Lt._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Lt._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;Lt._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{Lt._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=ht.LastCreatedScene,r=null,n=null,a=null,l=null,h=""){if(!s)return G.Error("No scene available to import mesh to"),null;const c=Lt._GetFileInfo(t,i);if(!c)return null;const u={};s.addPendingData(u);const d=()=>{s.removePendingData(u)},f=(g,v)=>{const E=Lt._FormatErrorMessage(c,g,v);a?a(s,E,new Ko(E,rh.SceneLoaderError,v)):G.Error(E),d()},p=n?g=>{try{n(g)}catch(v){f("Error in onProgress callback: "+v,v)}}:void 0,_=(g,v,E,C,S,b,R)=>{if(s.importedMeshesFiles.push(c.url),r)try{r(g,v,E,C,S,b,R)}catch(I){f("Error in onSuccess callback: "+I,I)}s.removePendingData(u)};return Lt._LoadData(c,s,(g,v,E)=>{if(g.rewriteRootURL&&(c.rootUrl=g.rewriteRootURL(c.rootUrl,E)),g.importMesh){const C=g,S=[],b=[],R=[];if(!C.importMesh(e,s,v,c.rootUrl,S,b,R,f))return;s.loadingPluginName=g.name,_(S,b,R,[],[],[],[])}else g.importMeshAsync(e,s,v,c.rootUrl,p,c.name).then(S=>{s.loadingPluginName=g.name,_(S.meshes,S.particleSystems,S.skeletons,S.animationGroups,S.transformNodes,S.geometries,S.lights)}).catch(S=>{f(S.message,S)})},p,f,d,l,h)}static ImportMeshAsync(e,t,i="",s=ht.LastCreatedScene,r=null,n=null,a=""){return new Promise((l,h)=>{Lt.ImportMesh(e,t,i,s,(c,u,d,f,p,_,g)=>{l({meshes:c,particleSystems:u,skeletons:d,animationGroups:f,transformNodes:p,geometries:_,lights:g})},r,(c,u,d)=>{h(d||new Error(u))},n,a)})}static Load(e,t="",i=ht.LastCreatedEngine,s=null,r=null,n=null,a=null,l=""){return i?Lt.Append(e,t,new Qe(i),s,r,n,a,l):(fe.Error("No engine available"),null)}static LoadAsync(e,t="",i=ht.LastCreatedEngine,s=null,r=null,n=""){return new Promise((a,l)=>{Lt.Load(e,t,i,h=>{a(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static Append(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=null,a=null,l=""){if(!i)return G.Error("No scene available to append to"),null;const h=Lt._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};Lt.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const d=(_,g)=>{const v=Lt._FormatErrorMessage(h,_,g);n?n(i,v,new Ko(v,rh.SceneLoaderError,g)):G.Error(v),u()},f=r?_=>{try{r(_)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=()=>{if(s)try{s(i)}catch(_){d("Error in onSuccess callback",_)}i.removePendingData(c)};return Lt._LoadData(h,i,(_,g)=>{if(_.load){if(!_.load(i,g,h.rootUrl,d))return;i.loadingPluginName=_.name,p()}else _.loadAsync(i,g,h.rootUrl,f,h.name).then(()=>{i.loadingPluginName=_.name,p()}).catch(E=>{d(E.message,E)})},f,d,u,a,l)}static AppendAsync(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=""){return new Promise((a,l)=>{Lt.Append(e,t,i,h=>{a(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static LoadAssetContainer(e,t="",i=ht.LastCreatedScene,s=null,r=null,n=null,a=null,l=""){if(!i)return G.Error("No scene available to load asset container to"),null;const h=Lt._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(_,g)=>{const v=Lt._FormatErrorMessage(h,_,g);n?n(i,v,new Ko(v,rh.SceneLoaderError,g)):G.Error(v),u()},f=r?_=>{try{r(_)}catch(g){d("Error in onProgress callback",g)}}:void 0,p=_=>{if(s)try{s(_)}catch(g){d("Error in onSuccess callback",g)}i.removePendingData(c)};return Lt._LoadData(h,i,(_,g)=>{if(_.loadAssetContainer){const E=_.loadAssetContainer(i,g,h.rootUrl,d);if(!E)return;E.populateRootNodes(),i.loadingPluginName=_.name,p(E)}else _.loadAssetContainerAsync?_.loadAssetContainerAsync(i,g,h.rootUrl,f,h.name).then(E=>{E.populateRootNodes(),i.loadingPluginName=_.name,p(E)}).catch(E=>{d(E.message,E)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,u,a,l)}static LoadAssetContainerAsync(e,t="",i=ht.LastCreatedScene,s=null,r=null){return new Promise((n,a)=>{Lt.LoadAssetContainer(e,t,i,l=>{n(l)},s,(l,h,c)=>{a(c||new Error(h))},r)})}static ImportAnimations(e,t="",i=ht.LastCreatedScene,s=!0,r=Kl.Clean,n=null,a=null,l=null,h=null,c=null){if(!i){G.Error("No scene available to load animations to");return}if(s){for(const p of i.animatables)p.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(p=>{p.dispose()}),i.getNodes().forEach(p=>{p.animations&&(p.animations=[])})}else switch(r){case Kl.Clean:i.animationGroups.slice().forEach(f=>{f.dispose()});break;case Kl.Stop:i.animationGroups.forEach(f=>{f.stop()});break;case Kl.Sync:i.animationGroups.forEach(f=>{f.reset(),f.restart()});break;case Kl.NoSync:break;default:G.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),a&&a(i)};this.LoadAssetContainer(e,t,i,d,l,h,c)}static ImportAnimationsAsync(e,t="",i=ht.LastCreatedScene,s=!0,r=Kl.Clean,n=null,a=null,l=null,h=null,c=null){return new Promise((u,d)=>{Lt.ImportAnimations(e,t,i,s,r,n,f=>{u(f)},l,(f,p,_)=>{d(_||new Error(p))},c)})}}Lt.NO_LOGGING=0;Lt.MINIMAL_LOGGING=1;Lt.SUMMARY_LOGGING=2;Lt.DETAILED_LOGGING=3;Lt.OnPluginActivatedObservable=new he;Lt._RegisteredPlugins={};Lt._ShowingLoadingScreen=!1;class ep extends Ie{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new k,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var M;(function(o){o[o.Float=1]="Float",o[o.Int=2]="Int",o[o.Vector2=4]="Vector2",o[o.Vector3=8]="Vector3",o[o.Vector4=16]="Vector4",o[o.Color3=32]="Color3",o[o.Color4=64]="Color4",o[o.Matrix=128]="Matrix",o[o.Object=256]="Object",o[o.AutoDetect=1024]="AutoDetect",o[o.BasedOnInput=2048]="BasedOnInput",o[o.All=4095]="All"})(M||(M={}));var W;(function(o){o[o.Vertex=1]="Vertex",o[o.Fragment=2]="Fragment",o[o.Neutral=4]="Neutral",o[o.VertexAndFragment=3]="VertexAndFragment"})(W||(W={}));class r0{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===W.Fragment;this.compilationString=` ${t?`//Entry point `:""}void main(void) { ${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` @@ -86,7 +86,7 @@ ${t} `: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 lF{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. +`))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}}class uF{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: @@ -117,7 +117,7 @@ ${e}.target = ${this.target}; `,e}}j("BABYLON.TransformBlock",Lv);class v_ extends nt{constructor(e){super(e,W.Vertex,!0),this.registerInput("vector",M.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}}j("BABYLON.VertexOutputBlock",v_);var ut;(function(o){o[o.Boolean=0]="Boolean",o[o.Float=1]="Float",o[o.Int=2]="Int",o[o.Vector2=3]="Vector2",o[o.List=4]="List"})(ut||(ut={}));function ft(o,e=ut.Boolean,t="PROPERTIES",i){return(s,r)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:r,displayName:o,type:e,groupName:t,options:i??{}})}}class Jl extends nt{constructor(e){super(e,W.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb",M.AutoDetect,!0),this.registerInput("a",M.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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&&Me.BindLogDepth(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}); +`),this}}j("BABYLON.VertexOutputBlock",v_);var ut;(function(o){o[o.Boolean=0]="Boolean",o[o.Float=1]="Float",o[o.Int=2]="Int",o[o.Vector2=3]="Vector2",o[o.List=4]="List"})(ut||(ut={}));function ft(o,e=ut.Boolean,t="PROPERTIES",i){return(s,r)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:r,displayName:o,type:e,groupName:t,options:i??{}})}}class eh extends nt{constructor(e){super(e,W.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb",M.AutoDetect,!0),this.registerInput("a",M.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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&&Me.BindLogDepth(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===M.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${n}); `:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${n}); @@ -134,17 +134,17 @@ ${e}.target = ${this.target}; `,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){var s;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=(s=e.useLogarithmicDepth)!==null&&s!==void 0?s:!1}}A([ft("Convert to gamma space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Jl.prototype,"convertToGammaSpace",void 0);A([ft("Convert to linear space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Jl.prototype,"convertToLinearSpace",void 0);A([ft("Use logarithmic depth",ut.Boolean,"PROPERTIES")],Jl.prototype,"useLogarithmicDepth",void 0);j("BABYLON.FragmentOutputBlock",Jl);var $r;(function(o){o[o.Uniform=0]="Uniform",o[o.Attribute=1]="Attribute",o[o.Varying=2]="Varying",o[o.Undefined=3]="Undefined"})($r||($r={}));var Gt;(function(o){o[o.World=1]="World",o[o.View=2]="View",o[o.Projection=3]="Projection",o[o.ViewProjection=4]="ViewProjection",o[o.WorldView=5]="WorldView",o[o.WorldViewProjection=6]="WorldViewProjection",o[o.CameraPosition=7]="CameraPosition",o[o.FogColor=8]="FogColor",o[o.DeltaTime=9]="DeltaTime",o[o.CameraParameters=10]="CameraParameters",o[o.MaterialAlpha=11]="MaterialAlpha"})(Gt||(Gt={}));var Zl;(function(o){o[o.None=0]="None",o[o.Time=1]="Time",o[o.RealTime=2]="RealTime"})(Zl||(Zl={}));const hF={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},hv={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},s0={particle_texturemask:!0};class Bt extends nt{get type(){if(this._type===M.AutoDetect){if(this.isUniform&&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"Color3":return this._type=M.Color3,this._type;case"Color4":return this._type=M.Color4,this._type;case"Matrix":return this._type=M.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=M.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=M.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=M.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=M.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Gt.World:case Gt.WorldView:case Gt.WorldViewProjection:case Gt.View:case Gt.ViewProjection:case Gt.Projection:return this._type=M.Matrix,this._type;case Gt.CameraPosition:return this._type=M.Vector3,this._type;case Gt.FogColor:return this._type=M.Color3,this._type;case Gt.DeltaTime:case Gt.MaterialAlpha:return this._type=M.Float,this._type;case Gt.CameraParameters:return this._type=M.Vector4,this._type}}return this._type}constructor(e,t=W.Vertex,i=M.AutoDetect){super(e,t,!1),this._mode=$r.Undefined,this._animationType=Zl.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new he,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=$r.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===M.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=$r.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=$r.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===$r.Undefined}get isUniform(){return this._mode===$r.Uniform}set isUniform(e){this._mode=e?$r.Uniform:$r.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===$r.Attribute}set isAttribute(e){this._mode=e?$r.Attribute:$r.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===$r.Varying}set isVarying(e){this._mode=e?$r.Varying:$r.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=$r.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Zl.Time:{this.type===M.Float&&(this.value+=e.getAnimationRatio()*.01);break}case Zl.RealTime:{this.type===M.Float&&(this.value=(ar.Now-e.getEngine().startTime)/1e3);break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)} +`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var s;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=(s=e.useLogarithmicDepth)!==null&&s!==void 0?s:!1}}A([ft("Convert to gamma space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],eh.prototype,"convertToGammaSpace",void 0);A([ft("Convert to linear space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],eh.prototype,"convertToLinearSpace",void 0);A([ft("Use logarithmic depth",ut.Boolean,"PROPERTIES")],eh.prototype,"useLogarithmicDepth",void 0);j("BABYLON.FragmentOutputBlock",eh);var $r;(function(o){o[o.Uniform=0]="Uniform",o[o.Attribute=1]="Attribute",o[o.Varying=2]="Varying",o[o.Undefined=3]="Undefined"})($r||($r={}));var Gt;(function(o){o[o.World=1]="World",o[o.View=2]="View",o[o.Projection=3]="Projection",o[o.ViewProjection=4]="ViewProjection",o[o.WorldView=5]="WorldView",o[o.WorldViewProjection=6]="WorldViewProjection",o[o.CameraPosition=7]="CameraPosition",o[o.FogColor=8]="FogColor",o[o.DeltaTime=9]="DeltaTime",o[o.CameraParameters=10]="CameraParameters",o[o.MaterialAlpha=11]="MaterialAlpha"})(Gt||(Gt={}));var Jl;(function(o){o[o.None=0]="None",o[o.Time=1]="Time",o[o.RealTime=2]="RealTime"})(Jl||(Jl={}));const dF={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},hv={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},n0={particle_texturemask:!0};class Vt extends nt{get type(){if(this._type===M.AutoDetect){if(this.isUniform&&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"Color3":return this._type=M.Color3,this._type;case"Color4":return this._type=M.Color4,this._type;case"Matrix":return this._type=M.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=M.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=M.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=M.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=M.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Gt.World:case Gt.WorldView:case Gt.WorldViewProjection:case Gt.View:case Gt.ViewProjection:case Gt.Projection:return this._type=M.Matrix,this._type;case Gt.CameraPosition:return this._type=M.Vector3,this._type;case Gt.FogColor:return this._type=M.Color3,this._type;case Gt.DeltaTime:case Gt.MaterialAlpha:return this._type=M.Float,this._type;case Gt.CameraParameters:return this._type=M.Vector4,this._type}}return this._type}constructor(e,t=W.Vertex,i=M.AutoDetect){super(e,t,!1),this._mode=$r.Undefined,this._animationType=Jl.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new he,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=$r.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===M.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=$r.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=$r.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===$r.Undefined}get isUniform(){return this._mode===$r.Uniform}set isUniform(e){this._mode=e?$r.Uniform:$r.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===$r.Attribute}set isAttribute(e){this._mode=e?$r.Attribute:$r.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===$r.Varying}set isVarying(e){this._mode=e?$r.Varying:$r.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=$r.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Jl.Time:{this.type===M.Float&&(this.value+=e.getAnimationRatio()*.01);break}case Jl.RealTime:{this.type===M.Float&&(this.value=(ar.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 M.Float:this.value=0;break;case M.Vector2:this.value=Re.Zero();break;case M.Vector3:this.value=T.Zero();break;case M.Vector4:this.value=Dt.Zero();break;case M.Color3:this.value=Te.White();break;case M.Color4:this.value=new Ze(1,1,1,1);break;case M.Matrix:this.value=k.Identity();break}}_emitConstant(e){switch(this.type){case M.Float:return`${e._emitFloat(this.value)}`;case M.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case M.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case M.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case M.Color3:return gi.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&gi.Color3[0].toGammaSpaceToRef(gi.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gi.Color3[0].toLinearSpaceToRef(gi.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${gi.Color3[0].r}, ${gi.Color3[0].g}, ${gi.Color3[0].b})`;case M.Color4:return gi.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&gi.Color4[0].toGammaSpaceToRef(gi.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gi.Color4[0].toLinearSpaceToRef(gi.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${gi.Color4[0].r}, ${gi.Color4[0].g}, ${gi.Color4[0].b}, ${gi.Color4[0].a})`}return""}get _noContextSwitch(){return hv[this.name]}_emit(e,t){var i;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 s=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case Gt.WorldView:s.needWorldViewMatrix=!0;break;case Gt.WorldViewProjection:s.needWorldViewProjectionMatrix=!0;break}else this._animationType!==Zl.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=(i=hF[this.name])!==null&&i!==void 0?i:this.name,this.target===W.Vertex&&e._vertexState){hv[this.name]?s0[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),hv[this.name]?s0[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}; +`);const s=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case Gt.WorldView:s.needWorldViewMatrix=!0;break;case Gt.WorldViewProjection:s.needWorldViewProjectionMatrix=!0;break}else this._animationType!==Jl.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=(i=dF[this.name])!==null&&i!==void 0?i:this.name,this.target===W.Vertex&&e._vertexState){hv[this.name]?n0[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),hv[this.name]?n0[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 Gt.World:e.setMatrix(r,t);break;case Gt.WorldView:e.setMatrix(r,i);break;case Gt.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 Gt.World:case Gt.WorldView:case Gt.WorldViewProjection:return;case Gt.View:e.setMatrix(s,t.getViewMatrix());break;case Gt.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case Gt.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case Gt.CameraPosition:t.bindEyePosition(e,s,!0);break;case Gt.FogColor:e.setColor3(s,t.fogColor);break;case Gt.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case Gt.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Gt.MaterialAlpha:e.setFloat(s,i.alpha);break}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(r!==null)switch(this.type){case M.Float:e.setFloat(s,r);break;case M.Int:e.setInt(s,r);break;case M.Color3:gi.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&gi.Color3[0].toGammaSpaceToRef(gi.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gi.Color3[0].toLinearSpaceToRef(gi.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,gi.Color3[0]);break;case M.Color4:gi.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&gi.Color4[0].toGammaSpaceToRef(gi.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&gi.Color4[0].toLinearSpaceToRef(gi.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,gi.Color4[0]);break;case M.Vector2:e.setVector2(s,r);break;case M.Vector3:e.setVector3(s,r);break;case M.Vector4:e.setVector4(s,r);break;case M.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.${Gt[this._systemValue]}); -`;if(this.isUniform){const t=[];let i="";switch(this.type){case M.Float: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;case M.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case M.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 M.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===M.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Zl[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===$r.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===$r.Attribute&&e.type===M.Vector3&&(this._type=M.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const s=Ds(e.valueType);s&&(this._storedValue=s.FromArray(e.value))}}}j("BABYLON.InputBlock",Bt);class bb extends nt{constructor(e){super(e,W.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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?W.VertexAndFragment:W.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; +`;if(this.isUniform){const t=[];let i="";switch(this.type){case M.Float: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;case M.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case M.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 M.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===M.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Jl[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===$r.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===$r.Attribute&&e.type===M.Vector3&&(this._type=M.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const s=Ds(e.valueType);s&&(this._storedValue=s.FromArray(e.value))}}}j("BABYLON.InputBlock",Vt);class Ab extends nt{constructor(e){super(e,W.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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?W.VertexAndFragment:W.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===W.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); `;return}if(this.uv.ownerBlock.target===W.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); `;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); @@ -157,7 +157,7 @@ ${e}.target = ${this.target}; `,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!==W.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=ee.Parse(e.texture,t,i))}}j("BABYLON.CurrentScreenBlock",bb);class yb extends nt{constructor(e){super(e,W.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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 Bt("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}; +`}_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!==W.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=ee.Parse(e.texture,t,i))}}j("BABYLON.CurrentScreenBlock",Ab);class Rb extends nt{constructor(e){super(e,W.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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 Vt("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 @@ -165,7 +165,7 @@ ${e}.target = ${this.target}; `,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); `,e.compilationString+=`#endif `}_buildBlock(e){if(super._buildBlock(e),e.target===W.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=ee.Parse(e.texture,t,i))}}j("BABYLON.ParticleTextureBlock",yb);class Ab extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,W.Fragment),this.registerOutput("rampColor",M.Color4,W.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!==W.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` +`;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=ee.Parse(e.texture,t,i))}}j("BABYLON.ParticleTextureBlock",Rb);class Ib extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,W.Fragment),this.registerOutput("rampColor",M.Color4,W.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!==W.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; @@ -183,7 +183,7 @@ ${e}.target = ${this.target}; #else ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; #endif - `,this}}j("BABYLON.ParticleRampGradientBlock",Ab);class Rb extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,W.Fragment),this.registerInput("alphaTexture",M.Float,!1,W.Fragment),this.registerInput("alphaColor",M.Float,!1,W.Fragment),this.registerOutput("blendColor",M.Color4,W.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!==W.Vertex)return e.compilationString+=` + `,this}}j("BABYLON.ParticleRampGradientBlock",Ib);class Pb extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,W.Fragment),this.registerInput("alphaTexture",M.Float,!1,W.Fragment),this.registerInput("alphaColor",M.Float,!1,W.Fragment),this.registerOutput("blendColor",M.Color4,W.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!==W.Vertex)return e.compilationString+=` #ifdef BLENDMULTIPLYMODE ${this._declareOutput(this.blendColor,e)}; float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; @@ -192,13 +192,13 @@ ${e}.target = ${this.target}; #else ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; #endif - `,this}}j("BABYLON.ParticleBlendMultiplyBlock",Rb);class Jh{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let s=0;s0&&(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;sthis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let s=0;s0&&(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;s0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get texture(){var e,t;return(t=(e=this._textures)===null||e===void 0?void 0:e[0])!==null&&t!==void 0?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,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 a;return(a=this._depthStencilTexture)===null||a===void 0||a.dispose(),this._depthStencilTextureWithStencil=i,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 e,t,i,s,r,n,a,l;let h=null;if(this._isMulti){const c=this.textures;if(c&&c.length>0){let u=!1,d=c.length;const f=c[c.length-1]._source;(f===Vt.Depth||f===Vt.DepthStencil)&&(u=!0,d--);const p=[],_=[],g=[],v=[],E=[],C=[],S=[],b={};for(let N=0;N1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;(t=i<((e=this._textures)===null||e===void 0?void 0:e.length))!==null&&t!==void 0&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)===null||t===void 0||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class dF extends px{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}_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 r,n,a,l;if(!e._hardwareTexture)return;const h=this._framebuffer,c=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(h),this._engine.webGLVersion>1){const u=this._context,d=u["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=(n=i??((r=this.layerIndices)===null||r===void 0?void 0:r[t]))!==null&&n!==void 0?n:0,u.framebufferTextureLayer(u.FRAMEBUFFER,d,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=(l=i??((a=this.faceIndices)===null||a===void 0?void 0:a[t]))!==null&&l!==void 0?l:0,u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const u=this._context,d=u["COLOR_ATTACHMENT"+t+"_WEBGL"],f=i!==void 0?u.TEXTURE_CUBE_MAP_POSITIVE_X+i:u.TEXTURE_2D;u.framebufferTexture2D(u.FRAMEBUFFER,d,f,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(c)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const r=(s=(i=this._attachments)===null||i===void 0?void 0:i.length)!==null&&s!==void 0?s:this.textures.length;for(let n=0;n1&&(n.format===15?u=i.DEPTH_COMPONENT16:n.format===16?u=i.DEPTH_COMPONENT24:n.format===17||n.format===13?u=i.DEPTH24_STENCIL8:n.format===14?u=i.DEPTH_COMPONENT32F:n.format===18&&(u=i.DEPTH32F_STENCIL8)),n.is2DArray?i.texImage3D(r,0,u,n.width,n.height,s,0,c,h,null):i.texImage2D(r,0,u,n.width,n.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(n);const d=t;if(d._depthStencilBuffer){const f=this._currentFramebuffer;this._bindUnboundFramebuffer(d._framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.STENCIL_ATTACHMENT,i.RENDERBUFFER,null),this._bindUnboundFramebuffer(f),i.deleteRenderbuffer(d._depthStencilBuffer),d._depthStencilBuffer=null}return n};We.prototype.updateRenderTargetTextureSampleCount=function(o,e){if(this.webGLVersion<2||!o||!o.texture)return 1;if(o.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),o._depthStencilBuffer&&(t.deleteRenderbuffer(o._depthStencilBuffer),o._depthStencilBuffer=null),o._MSAAFramebuffer&&(t.deleteFramebuffer(o._MSAAFramebuffer),o._MSAAFramebuffer=null);const i=o.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");o._MSAAFramebuffer=s,this._bindUnboundFramebuffer(o._MSAAFramebuffer);const r=this._createRenderBuffer(o.texture.width,o.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(o.texture.type,o.texture.format,o.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(o._framebuffer);return o.texture.samples=e,o._samples=e,o._depthStencilBuffer=this._setupFramebufferDepthAttachments(o._generateStencilBuffer,o._generateDepthBuffer,o.texture.width,o.texture.height,e),this._bindUnboundFramebuffer(null),e};class lt{static RegisterShaderCodeProcessing(e,t){if(!t){delete lt._CustomShaderCodeProcessing[e??""];return}lt._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){var t;return(t=lt._CustomShaderCodeProcessing[e])!==null&&t!==void 0?t:lt._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,a=1,l,h,c=null,u=0,d="postprocess",f,p=!1,_=5,g=is.GLSL){var v,E,C,S,b,R,I,N,O,L,B,V;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 qs(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Re(1,1),this._texelSize=Re.Zero(),this.onActivateObservable=new he,this.onSizeChangedObservable=new he,this.onApplyObservable=new he,this.onBeforeRenderObservable=new he,this.onAfterRenderObservable=new he,this.name=e;let Z=1,ue=null;if(i&&!Array.isArray(i)){const oe=i;i=(v=oe.uniforms)!==null&&v!==void 0?v:null,s=(E=oe.samplers)!==null&&E!==void 0?E:null,Z=(C=oe.size)!==null&&C!==void 0?C:1,n=(S=oe.camera)!==null&&S!==void 0?S:null,a=(b=oe.samplingMode)!==null&&b!==void 0?b:1,l=oe.engine,h=oe.reusable,c=(R=oe.defines)!==null&&R!==void 0?R:null,u=(I=oe.textureType)!==null&&I!==void 0?I:0,d=(N=oe.vertexUrl)!==null&&N!==void 0?N:"postprocess",f=oe.indexParameters,p=(O=oe.blockCompilation)!==null&&O!==void 0?O:!1,_=(L=oe.textureFormat)!==null&&L!==void 0?L:5,g=(B=oe.shaderLanguage)!==null&&B!==void 0?B:is.GLSL,ue=(V=oe.uniformBuffers)!==null&&V!==void 0?V:null}else r&&(typeof r=="number"?Z=r:Z={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=Z,this.renderTargetSamplingMode=a||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=_,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=ue||[],this._indexParameters=f,this._drawWrapper=new Or(this._engine),p||this.updateEffect(c)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new qs(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,a,l){var h,c;const u=lt._GetShaderCodeProcessing(this.name);if(u!=null&&u.defineCustomBindings){const d=(h=t==null?void 0:t.slice())!==null&&h!==void 0?h:[];d.push(...this._parameters);const f=(c=i==null?void 0:i.slice())!==null&&c!==void 0?c:[];f.push(...this._samplers),e=u.defineCustomBindings(this.name,e,d,f),t=d,i=f}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??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:u!=null&&u.processCodeAfterIncludes?(d,f)=>u.processCodeAfterIncludes(this.name,d,f):null,processFinalCode:u!=null&&u.processFinalCode?(d,f)=>u.processFinalCode(this.name,d,f):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let h=0;h{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return p||(p=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/u,c/d),this._engine.bindFramebuffer(p,0,h,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(p,0,void 0,void 0,this.forceFullscreenViewport)),(r=(s=this._engine)._debugInsertMarker)===null||r===void 0||r.call(s,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),p}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!1}apply(){var e,t,i;if(!(!((e=this._drawWrapper.effect)===null||e===void 0)&&e.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 s;return this._shareOutputWithPostProcess?s=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?s=this._forcedOutputTexture:s=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",s==null?void 0:s.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(i=(t=lt._GetShaderCodeProcessing(this.name))===null||t===void 0?void 0:t.bindCustomBindings)===null||i===void 0||i.call(t,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=Xe.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=lt.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=Ds(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 Xe.Parse(()=>new lt(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)}}lt._CustomShaderCodeProcessing={};A([D()],lt.prototype,"uniqueId",void 0);A([D()],lt.prototype,"name",void 0);A([D()],lt.prototype,"width",void 0);A([D()],lt.prototype,"height",void 0);A([D()],lt.prototype,"renderTargetSamplingMode",void 0);A([sx()],lt.prototype,"clearColor",void 0);A([D()],lt.prototype,"autoClear",void 0);A([D()],lt.prototype,"forceAutoClearInAlphaMode",void 0);A([D()],lt.prototype,"alphaMode",void 0);A([D()],lt.prototype,"alphaConstants",void 0);A([D()],lt.prototype,"enablePixelPerfectMode",void 0);A([D()],lt.prototype,"forceFullscreenViewport",void 0);A([D()],lt.prototype,"scaleMode",void 0);A([D()],lt.prototype,"alwaysForcePOT",void 0);A([D("samples")],lt.prototype,"_samples",void 0);A([D()],lt.prototype,"adaptScaleToCurrentViewport",void 0);j("BABYLON.PostProcess",lt);class x_ extends nt{constructor(e){super(e,W.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",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)}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,a=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)}; +}`;ne.ShadersStore[fF]=pF;class mx{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get texture(){var e,t;return(t=(e=this._textures)===null||e===void 0?void 0:e[0])!==null&&t!==void 0?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,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 a;return(a=this._depthStencilTexture)===null||a===void 0||a.dispose(),this._depthStencilTextureWithStencil=i,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 e,t,i,s,r,n,a,l;let h=null;if(this._isMulti){const c=this.textures;if(c&&c.length>0){let u=!1,d=c.length;const f=c[c.length-1]._source;(f===Ut.Depth||f===Ut.DepthStencil)&&(u=!0,d--);const p=[],_=[],g=[],v=[],E=[],C=[],S=[],b={};for(let N=0;N1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;(t=i<((e=this._textures)===null||e===void 0?void 0:e.length))!==null&&t!==void 0&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)===null||t===void 0||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class _F extends mx{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}_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 r,n,a,l;if(!e._hardwareTexture)return;const h=this._framebuffer,c=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(h),this._engine.webGLVersion>1){const u=this._context,d=u["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=(n=i??((r=this.layerIndices)===null||r===void 0?void 0:r[t]))!==null&&n!==void 0?n:0,u.framebufferTextureLayer(u.FRAMEBUFFER,d,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=(l=i??((a=this.faceIndices)===null||a===void 0?void 0:a[t]))!==null&&l!==void 0?l:0,u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):u.framebufferTexture2D(u.FRAMEBUFFER,d,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const u=this._context,d=u["COLOR_ATTACHMENT"+t+"_WEBGL"],f=i!==void 0?u.TEXTURE_CUBE_MAP_POSITIVE_X+i:u.TEXTURE_2D;u.framebufferTexture2D(u.FRAMEBUFFER,d,f,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(c)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const r=(s=(i=this._attachments)===null||i===void 0?void 0:i.length)!==null&&s!==void 0?s:this.textures.length;for(let n=0;n1&&(n.format===15?u=i.DEPTH_COMPONENT16:n.format===16?u=i.DEPTH_COMPONENT24:n.format===17||n.format===13?u=i.DEPTH24_STENCIL8:n.format===14?u=i.DEPTH_COMPONENT32F:n.format===18&&(u=i.DEPTH32F_STENCIL8)),n.is2DArray?i.texImage3D(r,0,u,n.width,n.height,s,0,c,h,null):i.texImage2D(r,0,u,n.width,n.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(n);const d=t;if(d._depthStencilBuffer){const f=this._currentFramebuffer;this._bindUnboundFramebuffer(d._framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.STENCIL_ATTACHMENT,i.RENDERBUFFER,null),this._bindUnboundFramebuffer(f),i.deleteRenderbuffer(d._depthStencilBuffer),d._depthStencilBuffer=null}return n};We.prototype.updateRenderTargetTextureSampleCount=function(o,e){if(this.webGLVersion<2||!o||!o.texture)return 1;if(o.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),o._depthStencilBuffer&&(t.deleteRenderbuffer(o._depthStencilBuffer),o._depthStencilBuffer=null),o._MSAAFramebuffer&&(t.deleteFramebuffer(o._MSAAFramebuffer),o._MSAAFramebuffer=null);const i=o.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");o._MSAAFramebuffer=s,this._bindUnboundFramebuffer(o._MSAAFramebuffer);const r=this._createRenderBuffer(o.texture.width,o.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(o.texture.type,o.texture.format,o.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(o._framebuffer);return o.texture.samples=e,o._samples=e,o._depthStencilBuffer=this._setupFramebufferDepthAttachments(o._generateStencilBuffer,o._generateDepthBuffer,o.texture.width,o.texture.height,e),this._bindUnboundFramebuffer(null),e};class lt{static RegisterShaderCodeProcessing(e,t){if(!t){delete lt._CustomShaderCodeProcessing[e??""];return}lt._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){var t;return(t=lt._CustomShaderCodeProcessing[e])!==null&&t!==void 0?t:lt._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,a=1,l,h,c=null,u=0,d="postprocess",f,p=!1,_=5,g=is.GLSL){var v,E,C,S,b,R,I,N,O,L,B,V;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 qs(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Re(1,1),this._texelSize=Re.Zero(),this.onActivateObservable=new he,this.onSizeChangedObservable=new he,this.onApplyObservable=new he,this.onBeforeRenderObservable=new he,this.onAfterRenderObservable=new he,this.name=e;let Z=1,ue=null;if(i&&!Array.isArray(i)){const oe=i;i=(v=oe.uniforms)!==null&&v!==void 0?v:null,s=(E=oe.samplers)!==null&&E!==void 0?E:null,Z=(C=oe.size)!==null&&C!==void 0?C:1,n=(S=oe.camera)!==null&&S!==void 0?S:null,a=(b=oe.samplingMode)!==null&&b!==void 0?b:1,l=oe.engine,h=oe.reusable,c=(R=oe.defines)!==null&&R!==void 0?R:null,u=(I=oe.textureType)!==null&&I!==void 0?I:0,d=(N=oe.vertexUrl)!==null&&N!==void 0?N:"postprocess",f=oe.indexParameters,p=(O=oe.blockCompilation)!==null&&O!==void 0?O:!1,_=(L=oe.textureFormat)!==null&&L!==void 0?L:5,g=(B=oe.shaderLanguage)!==null&&B!==void 0?B:is.GLSL,ue=(V=oe.uniformBuffers)!==null&&V!==void 0?V:null}else r&&(typeof r=="number"?Z=r:Z={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=Z,this.renderTargetSamplingMode=a||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=_,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=ue||[],this._indexParameters=f,this._drawWrapper=new Or(this._engine),p||this.updateEffect(c)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new qs(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,a,l){var h,c;const u=lt._GetShaderCodeProcessing(this.name);if(u!=null&&u.defineCustomBindings){const d=(h=t==null?void 0:t.slice())!==null&&h!==void 0?h:[];d.push(...this._parameters);const f=(c=i==null?void 0:i.slice())!==null&&c!==void 0?c:[];f.push(...this._samplers),e=u.defineCustomBindings(this.name,e,d,f),t=d,i=f}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??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:u!=null&&u.processCodeAfterIncludes?(d,f)=>u.processCodeAfterIncludes(this.name,d,f):null,processFinalCode:u!=null&&u.processFinalCode?(d,f)=>u.processFinalCode(this.name,d,f):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let h=0;h{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return p||(p=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/u,c/d),this._engine.bindFramebuffer(p,0,h,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(p,0,void 0,void 0,this.forceFullscreenViewport)),(r=(s=this._engine)._debugInsertMarker)===null||r===void 0||r.call(s,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),p}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!1}apply(){var e,t,i;if(!(!((e=this._drawWrapper.effect)===null||e===void 0)&&e.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 s;return this._shareOutputWithPostProcess?s=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?s=this._forcedOutputTexture:s=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",s==null?void 0:s.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(i=(t=lt._GetShaderCodeProcessing(this.name))===null||t===void 0?void 0:t.bindCustomBindings)===null||i===void 0||i.call(t,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=Xe.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=lt.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=Ds(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 Xe.Parse(()=>new lt(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)}}lt._CustomShaderCodeProcessing={};A([D()],lt.prototype,"uniqueId",void 0);A([D()],lt.prototype,"name",void 0);A([D()],lt.prototype,"width",void 0);A([D()],lt.prototype,"height",void 0);A([D()],lt.prototype,"renderTargetSamplingMode",void 0);A([nx()],lt.prototype,"clearColor",void 0);A([D()],lt.prototype,"autoClear",void 0);A([D()],lt.prototype,"forceAutoClearInAlphaMode",void 0);A([D()],lt.prototype,"alphaMode",void 0);A([D()],lt.prototype,"alphaConstants",void 0);A([D()],lt.prototype,"enablePixelPerfectMode",void 0);A([D()],lt.prototype,"forceFullscreenViewport",void 0);A([D()],lt.prototype,"scaleMode",void 0);A([D()],lt.prototype,"alwaysForcePOT",void 0);A([D("samples")],lt.prototype,"_samples",void 0);A([D()],lt.prototype,"adaptScaleToCurrentViewport",void 0);j("BABYLON.PostProcess",lt);class x_ extends nt{constructor(e){super(e,W.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",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)}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,a=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)}; @@ -224,36 +224,36 @@ vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); `,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=Re.FromArray(e.sourceRange),this.targetRange=Re.FromArray(e.targetRange)}}A([ft("From",ut.Vector2)],em.prototype,"sourceRange",void 0);A([ft("To",ut.Vector2)],em.prototype,"targetRange",void 0);j("BABYLON.RemapBlock",em);class Bv extends nt{constructor(e){super(e,W.Neutral),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].acceptedConnectionPointTypes.push(M.Float),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.MultiplyBlock",Bv);var Cn;(function(o){o[o.Material=0]="Material",o[o.PostProcess=1]="PostProcess",o[o.Particle=2]="Particle",o[o.ProceduralTexture=3]="ProceduralTexture"})(Cn||(Cn={}));class zh{constructor(){this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.minEmitBox=new T(-.5,-.5,-.5),this.maxEmitBox=new T(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=ye.RandomRange(this.direction1.x,this.direction2.x),n=ye.RandomRange(this.direction1.y,this.direction2.y),a=ye.RandomRange(this.direction1.z,this.direction2.z);if(s){t.x=r,t.y=n,t.z=a;return}T.TransformNormalFromFloatsToRef(r,n,a,e,t)}startPositionFunction(e,t,i,s){const r=ye.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=ye.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=ye.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(s){t.x=r,t.y=n,t.z=a;return}T.TransformCoordinatesFromFloatsToRef(r,n,a,e,t)}clone(){const e=new zh;return Ur.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),T.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),T.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class tm{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?K.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),K.Vector3[0]).normalize();const r=ye.RandomRange(0,this.directionRandomizer),n=ye.RandomRange(0,this.directionRandomizer),a=ye.RandomRange(0,this.directionRandomizer);t.x=K.Vector3[0].x+r,t.y=K.Vector3[0].y+n,t.z=K.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,s){const r=ye.RandomRange(0,Math.PI*2);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=ye.RandomRange(0,this.heightRange),n=1-n*n);let a=this._radius-ye.RandomRange(0,this._radius*this.radiusRange);a=a*n;const l=a*Math.sin(r),h=a*Math.cos(r),c=n*this._height;if(s){t.x=l,t.y=c,t.z=h;return}T.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new tm(this._radius,this._angle,this.directionRandomizer);return Ur.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+=` +`,this}}j("BABYLON.MultiplyBlock",Bv);var bn;(function(o){o[o.Material=0]="Material",o[o.PostProcess=1]="PostProcess",o[o.Particle=2]="Particle",o[o.ProceduralTexture=3]="ProceduralTexture"})(bn||(bn={}));class Wh{constructor(){this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.minEmitBox=new T(-.5,-.5,-.5),this.maxEmitBox=new T(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=ye.RandomRange(this.direction1.x,this.direction2.x),n=ye.RandomRange(this.direction1.y,this.direction2.y),a=ye.RandomRange(this.direction1.z,this.direction2.z);if(s){t.x=r,t.y=n,t.z=a;return}T.TransformNormalFromFloatsToRef(r,n,a,e,t)}startPositionFunction(e,t,i,s){const r=ye.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=ye.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=ye.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(s){t.x=r,t.y=n,t.z=a;return}T.TransformCoordinatesFromFloatsToRef(r,n,a,e,t)}clone(){const e=new Wh;return Ur.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),T.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),T.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class tm{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?K.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),K.Vector3[0]).normalize();const r=ye.RandomRange(0,this.directionRandomizer),n=ye.RandomRange(0,this.directionRandomizer),a=ye.RandomRange(0,this.directionRandomizer);t.x=K.Vector3[0].x+r,t.y=K.Vector3[0].y+n,t.z=K.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,s){const r=ye.RandomRange(0,Math.PI*2);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=ye.RandomRange(0,this.heightRange),n=1-n*n);let a=this._radius-ye.RandomRange(0,this._radius*this.radiusRange);a=a*n;const l=a*Math.sin(r),h=a*Math.cos(r),c=n*this._height;if(s){t.x=l,t.y=c,t.z=h;return}T.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new tm(this._radius,this._angle,this.directionRandomizer);return Ur.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 tp{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=T.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),T.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=ye.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=ye.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),s){t.copyFrom(this._tempVector);return}T.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=ye.RandomRange(-this.height/2,this.height/2),n=ye.RandomRange(0,2*Math.PI),a=ye.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(a)*this.radius,h=l*Math.cos(n),c=l*Math.sin(n);if(s){t.copyFromFloats(h,r,c);return}T.TransformCoordinatesFromFloatsToRef(h,r,c,e,t)}clone(){const e=new tp(this.radius,this.directionRandomizer);return Ur.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 im extends tp{constructor(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t){const i=ye.RandomRange(this.direction1.x,this.direction2.x),s=ye.RandomRange(this.direction1.y,this.direction2.y),r=ye.RandomRange(this.direction1.z,this.direction2.z);T.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new im(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Ur.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 sm{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=ye.RandomRange(0,this.directionRandomizer),a=ye.RandomRange(0,this.directionRandomizer),l=ye.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=a,r.z+=l,r.normalize(),s){t.copyFrom(r);return}T.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-ye.RandomRange(0,this.radius*this.radiusRange),n=ye.RandomRange(0,1),a=ye.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(a)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(a)*Math.sin(l);if(s){t.copyFromFloats(h,Math.abs(c),u);return}T.TransformCoordinatesFromFloatsToRef(h,Math.abs(c),u,e,t)}clone(){const e=new sm(this.radius,this.directionRandomizer);return Ur.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 rm{constructor(){this.direction1=new T(0,1,0),this.direction2=new T(0,1,0)}startDirectionFunction(e,t,i,s){const r=ye.RandomRange(this.direction1.x,this.direction2.x),n=ye.RandomRange(this.direction1.y,this.direction2.y),a=ye.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,a);return}T.TransformNormalFromFloatsToRef(r,n,a,e,t)}startPositionFunction(e,t,i,s){if(s){t.copyFromFloats(0,0,0);return}T.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new rm;return Ur.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2)}}class ip{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=ye.RandomRange(0,this.directionRandomizer),a=ye.RandomRange(0,this.directionRandomizer),l=ye.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=a,r.z+=l,r.normalize(),s){t.copyFrom(r);return}T.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-ye.RandomRange(0,this.radius*this.radiusRange),n=ye.RandomRange(0,1),a=ye.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(a)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(a)*Math.sin(l);if(s){t.copyFromFloats(h,c,u);return}T.TransformCoordinatesFromFloatsToRef(h,c,u,e,t)}clone(){const e=new ip(this.radius,this.directionRandomizer);return Ur.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 nm extends ip{constructor(e=1,t=new T(0,1,0),i=new T(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=ye.RandomRange(this.direction1.x,this.direction2.x),s=ye.RandomRange(this.direction1.y,this.direction2.y),r=ye.RandomRange(this.direction1.z,this.direction2.z);T.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new nm(this.radius,this.direction1,this.direction2);return Ur.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 Wh{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=K.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const n=K.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}T.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=K.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s){t.copyFrom(r);return}T.TransformCoordinatesToRef(r,e,t)}clone(){const e=new Wh;return Ur.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e}parse(e){}}class _x{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(P.PositionKind),this._normals=e.getVerticesData(P.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=T.Zero(),this._mesh=null,this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals){T.TransformNormalToRef(this._storedNormal,e,t);return}const r=ye.RandomRange(this.direction1.x,this.direction2.x),n=ye.RandomRange(this.direction1.y,this.direction2.y),a=ye.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,a);return}T.TransformNormalFromFloatsToRef(r,n,a,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(),a=Math.random()*(1-n),l=1-n-a,h=this._indices[r],c=this._indices[r+1],u=this._indices[r+2],d=K.Vector3[0],f=K.Vector3[1],p=K.Vector3[2],_=K.Vector3[3];T.FromArrayToRef(this._positions,h*3,d),T.FromArrayToRef(this._positions,c*3,f),T.FromArrayToRef(this._positions,u*3,p),_.x=n*d.x+a*f.x+l*p.x,_.y=n*d.y+a*f.y+l*p.y,_.z=n*d.z+a*f.z+l*p.z,s?t.copyFromFloats(_.x,_.y,_.z):T.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(T.FromArrayToRef(this._normals,h*3,d),T.FromArrayToRef(this._normals,c*3,f),T.FromArrayToRef(this._normals,u*3,p),this._storedNormal.x=n*d.x+a*f.x+l*p.x,this._storedNormal.y=n*d.y+a*f.y+l*p.y,this._storedNormal.z=n*d.z+a*f.z+l*p.z)}clone(){const e=new _x(this.mesh);return Ur.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=(e=this.mesh)===null||e===void 0?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class yo{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:T.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:T.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:T.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:T.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=T.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new T(10,10,10),this.onAnimationEnd=null,this.blendMode=yo.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 Re(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new T(0,0,0),this._useLogarithmicDepth=!1,this.gravity=T.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 Ze(1,1,1,1),this.color2=new Ze(1,1,1,1),this.colorDead=new Ze(0,0,0,1),this.textureMask=new Ze(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Aw,this.id=e,this.name=e}createPointEmitter(e,t){const i=new rm;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new sm(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new ip(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new T(0,1,0),i=new T(0,1,0)){const s=new nm(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=new tp(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){const n=new im(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=new tm(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new zh;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}}yo.BLENDMODE_ONEONE=0;yo.BLENDMODE_STANDARD=1;yo.BLENDMODE_ADD=2;yo.BLENDMODE_MULTIPLY=3;yo.BLENDMODE_MULTIPLYADD=4;class Ib extends nt{constructor(e){super(e,W.Neutral),this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb ",M.Color3,!0),this.registerOutput("rgb",M.Color3),this.registerOutput("r",M.Float),this.registerOutput("g",M.Float),this.registerOutput("b",M.Float),this.registerOutput("a",M.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],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +#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 Hh{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=K.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const n=K.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}T.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=K.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s){t.copyFrom(r);return}T.TransformCoordinatesToRef(r,e,t)}clone(){const e=new Hh;return Ur.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e}parse(e){}}class gx{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(P.PositionKind),this._normals=e.getVerticesData(P.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=T.Zero(),this._mesh=null,this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals){T.TransformNormalToRef(this._storedNormal,e,t);return}const r=ye.RandomRange(this.direction1.x,this.direction2.x),n=ye.RandomRange(this.direction1.y,this.direction2.y),a=ye.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,a);return}T.TransformNormalFromFloatsToRef(r,n,a,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(),a=Math.random()*(1-n),l=1-n-a,h=this._indices[r],c=this._indices[r+1],u=this._indices[r+2],d=K.Vector3[0],f=K.Vector3[1],p=K.Vector3[2],_=K.Vector3[3];T.FromArrayToRef(this._positions,h*3,d),T.FromArrayToRef(this._positions,c*3,f),T.FromArrayToRef(this._positions,u*3,p),_.x=n*d.x+a*f.x+l*p.x,_.y=n*d.y+a*f.y+l*p.y,_.z=n*d.z+a*f.z+l*p.z,s?t.copyFromFloats(_.x,_.y,_.z):T.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(T.FromArrayToRef(this._normals,h*3,d),T.FromArrayToRef(this._normals,c*3,f),T.FromArrayToRef(this._normals,u*3,p),this._storedNormal.x=n*d.x+a*f.x+l*p.x,this._storedNormal.y=n*d.y+a*f.y+l*p.y,this._storedNormal.z=n*d.z+a*f.z+l*p.z)}clone(){const e=new gx(this.mesh);return Ur.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=(e=this.mesh)===null||e===void 0?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class yo{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:T.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:T.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:T.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:T.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=T.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new T(10,10,10),this.onAnimationEnd=null,this.blendMode=yo.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 Re(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new T(0,0,0),this._useLogarithmicDepth=!1,this.gravity=T.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 Ze(1,1,1,1),this.color2=new Ze(1,1,1,1),this.colorDead=new Ze(0,0,0,1),this.textureMask=new Ze(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Pw,this.id=e,this.name=e}createPointEmitter(e,t){const i=new rm;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new sm(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new ip(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new T(0,1,0),i=new T(0,1,0)){const s=new nm(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=new tp(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){const n=new im(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=new tm(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new Wh;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}}yo.BLENDMODE_ONEONE=0;yo.BLENDMODE_STANDARD=1;yo.BLENDMODE_ADD=2;yo.BLENDMODE_MULTIPLY=3;yo.BLENDMODE_MULTIPLYADD=4;class Mb extends nt{constructor(e){super(e,W.Neutral),this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb ",M.Color3,!0),this.registerOutput("rgb",M.Color3),this.registerOutput("r",M.Float),this.registerOutput("g",M.Float),this.registerOutput("b",M.Float),this.registerOutput("a",M.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],a=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; `),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; -`),this}}j("BABYLON.ColorSplitterBlock",Ib);We.prototype.createRenderTargetCubeTexture=function(o,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,o),i=Object.assign({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 Ti(this,Vt.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,G.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),o,o,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,o,o),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=a,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=o,r.height=o,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 cv={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class am{constructor(e,t=cv){var i,s;this._fullscreenViewport=new Na(0,0,1,1);const r=(i=t.positions)!==null&&i!==void 0?i:cv.positions,n=(s=t.indices)!==null&&s!==void 0?s:cv.indices;this.engine=e,this._vertexBuffers={[P.PositionKind]:new P(e,r,P.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(n);for(const a in this._vertexBuffers)this._vertexBuffers[a]._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[P.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[P.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Il{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new he;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 Or(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 ji(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._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Pb="passPixelShader",Mb=`varying vec2 vUV;uniform sampler2D textureSampler; +`),this}}j("BABYLON.ColorSplitterBlock",Mb);We.prototype.createRenderTargetCubeTexture=function(o,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,o),i=Object.assign({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 Ti(this,Ut.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,G.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),o,o,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,o,o),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=a,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=o,r.height=o,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 cv={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class am{constructor(e,t=cv){var i,s;this._fullscreenViewport=new Na(0,0,1,1);const r=(i=t.positions)!==null&&i!==void 0?i:cv.positions,n=(s=t.indices)!==null&&s!==void 0?s:cv.indices;this.engine=e,this._vertexBuffers={[P.PositionKind]:new P(e,r,P.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(n);for(const a in this._vertexBuffers)this._vertexBuffers[a]._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[P.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[P.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Il{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new he;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 Or(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 ji(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._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Db="passPixelShader",Ob=`varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`;ne.ShadersStore[Pb]=Mb;const r0={name:Pb,shader:Mb};class tn{static _CreateDumpRenderer(){if(!tn._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 We(e,!1,i)}catch{e=document.createElement("canvas"),t=new We(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new am(t),r=new Il({engine:t,name:r0.name,fragmentShader:r0.shader,samplerNames:["textureSampler"]});tn._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return tn._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){const l=await i.readPixels(0,0,e,t),h=new Uint8Array(l.buffer);tn.DumpData(e,t,h,s,r,n,!0,void 0,a)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,l){return new Promise(h=>{tn.DumpData(e,t,i,c=>h(c),s,r,n,a,l)})}static DumpData(e,t,i,s,r="image/png",n,a=!1,l=!1,h){const c=tn._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let f=i.length;for(;f--;){const p=i[f];d[f]=Math.round(ye.Clamp(p)*255)}i=d}const u=c.engine.createRawTexture(i,e,t,5,!1,!a,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?fe.ToBlob(c.canvas,d=>{const f=new FileReader;f.onload=p=>{const _=p.target.result;s&&s(_)},f.readAsArrayBuffer(d)},r,h):fe.EncodeScreenshotCanvasData(c.canvas,s,r,n,h),u.dispose()}static Dispose(){tn._DumpToolsEngine&&(tn._DumpToolsEngine.wrapper.dispose(),tn._DumpToolsEngine.renderer.dispose(),tn._DumpToolsEngine.engine.dispose()),tn._DumpToolsEngine=null}}const fF=()=>{fe.DumpData=tn.DumpData,fe.DumpDataAsync=tn.DumpDataAsync,fe.DumpFramebuffer=tn.DumpFramebuffer};fF();class ms extends ee{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=$C(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let s=0;s{var ue;const oe=this._renderList?this._renderList.length:0;(Z===0&&oe>0||oe===0)&&((ue=this.getScene())===null||ue===void 0||ue.meshes.forEach(me=>{me._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new he,this.onAfterUnbindObservable=new he,this.onBeforeRenderObservable=new he,this.onAfterRenderObservable=new he,this.onClearObservable=new he,this.onResizeObservable=new he,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=T.Zero(),i=this.getScene(),!i)return;const B=this.getScene().getEngine();this._gammaSpace=L,this._coordinatesMode=ee.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=B.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new Fr(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:(N=this._format)!==null&&N!==void 0?N:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:p,creationFlags:_,noColorAttachment:g,useSRGBBuffer:v,colorAttachment:O,label:this.name},this.samplingMode===ee.NEAREST_SAMPLINGMODE&&(this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE),f||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ee.INVCUBIC_MODE,this._textureMatrix=k.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,p!==void 0&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14){var n;(n=this._renderTarget)===null||n===void 0||n.createDepthStencilTexture(e,t,i,s,r)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;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 t;const i=this.isCube;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null;const s=this.getScene();s&&(this._processSizeParameter(e,!1),i?this._renderTarget=s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){var s;const r=this.getScene();if(!r)return i;const n=r.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){var n,a,l,h,c,u;const d=this.getScene();if(!d)return;const f=d.getEngine();if((n=f._debugPushGroup)===null||n===void 0||n.call(f,`render to face #${e} layer #${s}`,1),this._prepareFrame(d,e,s,t),this.is2DArray?(f.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(f.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),f.snapshotRendering&&f.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(f):this.skipInitialClear||f.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let _=null;const g=this.renderList?this.renderList:d.getActiveMeshes().data,v=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(_=this.getCustomRenderList(this.is2DArray?s:e,g,v)),_?this._prepareRenderingManager(_,_.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(g,v,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),_=g);for(const C of d._beforeRenderTargetClearStage)C.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(f):this.skipInitialClear||f.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const C of d._beforeRenderTargetDrawStage)C.action(this,e,s);this._renderingManager.render(this.customRenderFunction,_,this.renderParticles,this.renderSprites);for(const C of d._afterRenderTargetDrawStage)C.action(this,e,s);const E=(l=(a=this._texture)===null||a===void 0?void 0:a.generateMipMaps)!==null&&l!==void 0?l:!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(h=this._renderTarget)!==null&&h!==void 0?h:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,(c=this._renderTarget)!==null&&c!==void 0?c:void 0,e);for(const C of d._afterRenderTargetPostProcessStage)C.action(this,e,s);this._texture&&(this._texture.generateMipMaps=E),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&tn.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),f)}this._unbindFrameBuffer(f,e),this._texture&&this.isCube&&e===5&&f.generateMipMapsForCubemap(this._texture),(u=f._debugPopGroup)===null||u===void 0||u.call(f,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 ms(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1);for(const s of t.cameras)i=s.customRenderTargets.indexOf(this),i>=0&&s.customRenderTargets.splice(i,1);(e=this._renderTarget)===null||e===void 0||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===ms.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ms.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}ms.REFRESHRATE_RENDER_ONCE=0;ms.REFRESHRATE_RENDER_ONEVERYFRAME=1;ms.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;ee._CreateRenderTargetTexture=(o,e,t,i,s)=>new ms(o,e,t,i);class pF{constructor(e){this.name=Fe.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(Fe.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){fe.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const _F="proceduralVertexShader",mF=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +{gl_FragColor=texture2D(textureSampler,vUV);}`;ne.ShadersStore[Db]=Ob;const a0={name:Db,shader:Ob};class tn{static _CreateDumpRenderer(){if(!tn._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 We(e,!1,i)}catch{e=document.createElement("canvas"),t=new We(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new am(t),r=new Il({engine:t,name:a0.name,fragmentShader:a0.shader,samplerNames:["textureSampler"]});tn._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return tn._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){const l=await i.readPixels(0,0,e,t),h=new Uint8Array(l.buffer);tn.DumpData(e,t,h,s,r,n,!0,void 0,a)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,l){return new Promise(h=>{tn.DumpData(e,t,i,c=>h(c),s,r,n,a,l)})}static DumpData(e,t,i,s,r="image/png",n,a=!1,l=!1,h){const c=tn._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let f=i.length;for(;f--;){const p=i[f];d[f]=Math.round(ye.Clamp(p)*255)}i=d}const u=c.engine.createRawTexture(i,e,t,5,!1,!a,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?fe.ToBlob(c.canvas,d=>{const f=new FileReader;f.onload=p=>{const _=p.target.result;s&&s(_)},f.readAsArrayBuffer(d)},r,h):fe.EncodeScreenshotCanvasData(c.canvas,s,r,n,h),u.dispose()}static Dispose(){tn._DumpToolsEngine&&(tn._DumpToolsEngine.wrapper.dispose(),tn._DumpToolsEngine.renderer.dispose(),tn._DumpToolsEngine.engine.dispose()),tn._DumpToolsEngine=null}}const mF=()=>{fe.DumpData=tn.DumpData,fe.DumpDataAsync=tn.DumpDataAsync,fe.DumpFramebuffer=tn.DumpFramebuffer};mF();class ms extends ee{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=qC(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;Array.isArray(e)?i=e:i=[e];for(let s=0;s{var ue;const oe=this._renderList?this._renderList.length:0;(Z===0&&oe>0||oe===0)&&((ue=this.getScene())===null||ue===void 0||ue.meshes.forEach(me=>{me._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new he,this.onAfterUnbindObservable=new he,this.onBeforeRenderObservable=new he,this.onAfterRenderObservable=new he,this.onClearObservable=new he,this.onResizeObservable=new he,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=T.Zero(),i=this.getScene(),!i)return;const B=this.getScene().getEngine();this._gammaSpace=L,this._coordinatesMode=ee.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=B.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new Fr(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:(N=this._format)!==null&&N!==void 0?N:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:p,creationFlags:_,noColorAttachment:g,useSRGBBuffer:v,colorAttachment:O,label:this.name},this.samplingMode===ee.NEAREST_SAMPLINGMODE&&(this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE),f||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ee.INVCUBIC_MODE,this._textureMatrix=k.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,p!==void 0&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14){var n;(n=this._renderTarget)===null||n===void 0||n.createDepthStencilTexture(e,t,i,s,r)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;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 t;const i=this.isCube;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null;const s=this.getScene();s&&(this._processSizeParameter(e,!1),i?this._renderTarget=s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){var s;const r=this.getScene();if(!r)return i;const n=r.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){var n,a,l,h,c,u;const d=this.getScene();if(!d)return;const f=d.getEngine();if((n=f._debugPushGroup)===null||n===void 0||n.call(f,`render to face #${e} layer #${s}`,1),this._prepareFrame(d,e,s,t),this.is2DArray?(f.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(f.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),f.snapshotRendering&&f.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(f):this.skipInitialClear||f.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let _=null;const g=this.renderList?this.renderList:d.getActiveMeshes().data,v=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(_=this.getCustomRenderList(this.is2DArray?s:e,g,v)),_?this._prepareRenderingManager(_,_.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(g,v,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),_=g);for(const C of d._beforeRenderTargetClearStage)C.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(f):this.skipInitialClear||f.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const C of d._beforeRenderTargetDrawStage)C.action(this,e,s);this._renderingManager.render(this.customRenderFunction,_,this.renderParticles,this.renderSprites);for(const C of d._afterRenderTargetDrawStage)C.action(this,e,s);const E=(l=(a=this._texture)===null||a===void 0?void 0:a.generateMipMaps)!==null&&l!==void 0?l:!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(h=this._renderTarget)!==null&&h!==void 0?h:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,(c=this._renderTarget)!==null&&c!==void 0?c:void 0,e);for(const C of d._afterRenderTargetPostProcessStage)C.action(this,e,s);this._texture&&(this._texture.generateMipMaps=E),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&tn.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),f)}this._unbindFrameBuffer(f,e),this._texture&&this.isCube&&e===5&&f.generateMipMapsForCubemap(this._texture),(u=f._debugPopGroup)===null||u===void 0||u.call(f,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 ms(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1);for(const s of t.cameras)i=s.customRenderTargets.indexOf(this),i>=0&&s.customRenderTargets.splice(i,1);(e=this._renderTarget)===null||e===void 0||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===ms.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ms.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}ms.REFRESHRATE_RENDER_ONCE=0;ms.REFRESHRATE_RENDER_ONEVERYFRAME=1;ms.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;ee._CreateRenderTargetTexture=(o,e,t,i,s)=>new ms(o,e,t,i);class gF{constructor(e){this.name=Fe.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(Fe.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){fe.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const vF="proceduralVertexShader",xF=`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 -}`;ne.ShadersStore[_F]=mF;class Jo extends ee{constructor(e,t,i,s,r=null,n=!0,a=!1,l=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new he,this.onBeforeGenerationObservable=new he,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,s=this.getScene()||ht.LastCreatedScene;let h=s._getComponent(Fe.NAME_PROCEDURALTEXTURE);h||(h=new pF(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 Or(this._fullEngine),this.setFragment(i),this._fallbackTexture=r;const c=this._createRtWrapper(a,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[P.PositionKind]=new P(this._fullEngine,u,P.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.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s}),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[P.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ms.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ms.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)===null||e===void 0||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,[P.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var s;(s=this._rtWrapper)===null||s===void 0||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 t,i;const s=this.getScene();if(!s)return;const r=this._fullEngine;if(r.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),r.setState(!1),!this.nodeMaterialSource){for(const a in this._textures)this._drawWrapper.effect.setTexture(a,this._textures[a]);for(const a in this._ints)this._drawWrapper.effect.setInt(a,this._ints[a]);for(const a in this._floats)this._drawWrapper.effect.setFloat(a,this._floats[a]);for(const a in this._floatsArrays)this._drawWrapper.effect.setArray(a,this._floatsArrays[a]);for(const a in this._colors3)this._drawWrapper.effect.setColor3(a,this._colors3[a]);for(const a in this._colors4){const l=this._colors4[a];this._drawWrapper.effect.setFloat4(a,l.r,l.g,l.b,l.a)}for(const a in this._vectors2)this._drawWrapper.effect.setVector2(a,this._vectors2[a]);for(const a in this._vectors3)this._drawWrapper.effect.setVector3(a,this._vectors3[a]);for(const a in this._matrices)this._drawWrapper.effect.setMatrix(a,this._matrices[a])}if(!this._texture||!this._rtWrapper)return;(t=r._debugPushGroup)===null||t===void 0||t.call(r,`procedural texture generation for ${this.name}`,1);const n=r.currentViewport;if(this.isCube)for(let a=0;a<6;a++)r.bindFramebuffer(this._rtWrapper,a,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",a),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Ie.TriangleFillMode,0,6);else r.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Ie.TriangleFillMode,0,6);r.unBindFramebuffer(this._rtWrapper,this.isCube),n&&r.setViewport(n),this.isCube&&r.generateMipMapsForCubemap(this._texture),(i=r._debugPopGroup)===null||i===void 0||i.call(r,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Jo(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[P.PositionKind];i&&(i.dispose(),this._vertexBuffers[P.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}A([D()],Jo.prototype,"isEnabled",void 0);A([D()],Jo.prototype,"autoClear",void 0);A([D()],Jo.prototype,"_generateMipMaps",void 0);A([D()],Jo.prototype,"_size",void 0);A([D()],Jo.prototype,"refreshRate",null);j("BABYLON.ProceduralTexture",Jo);var tr;(function(o){o[o.Cos=0]="Cos",o[o.Sin=1]="Sin",o[o.Abs=2]="Abs",o[o.Exp=3]="Exp",o[o.Exp2=4]="Exp2",o[o.Round=5]="Round",o[o.Floor=6]="Floor",o[o.Ceiling=7]="Ceiling",o[o.Sqrt=8]="Sqrt",o[o.Log=9]="Log",o[o.Tan=10]="Tan",o[o.ArcTan=11]="ArcTan",o[o.ArcCos=12]="ArcCos",o[o.ArcSin=13]="ArcSin",o[o.Fract=14]="Fract",o[o.Sign=15]="Sign",o[o.Radians=16]="Radians",o[o.Degrees=17]="Degrees"})(tr||(tr={}));class Db extends nt{constructor(e){super(e,W.Neutral),this.operation=tr.Cos,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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 tr.Cos:{i="cos";break}case tr.Sin:{i="sin";break}case tr.Abs:{i="abs";break}case tr.Exp:{i="exp";break}case tr.Exp2:{i="exp2";break}case tr.Round:{i="round";break}case tr.Floor:{i="floor";break}case tr.Ceiling:{i="ceil";break}case tr.Sqrt:{i="sqrt";break}case tr.Log:{i="log";break}case tr.Tan:{i="tan";break}case tr.ArcTan:{i="atan";break}case tr.ArcCos:{i="acos";break}case tr.ArcSin:{i="asin";break}case tr.Fract:{i="fract";break}case tr.Sign:{i="sign";break}case tr.Radians:{i="radians";break}case tr.Degrees:{i="degrees";break}}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); +}`;ne.ShadersStore[vF]=xF;class Jo extends ee{constructor(e,t,i,s,r=null,n=!0,a=!1,l=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new he,this.onBeforeGenerationObservable=new he,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,s=this.getScene()||ht.LastCreatedScene;let h=s._getComponent(Fe.NAME_PROCEDURALTEXTURE);h||(h=new gF(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 Or(this._fullEngine),this.setFragment(i),this._fallbackTexture=r;const c=this._createRtWrapper(a,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[P.PositionKind]=new P(this._fullEngine,u,P.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.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s}),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[P.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ms.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ms.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)===null||e===void 0||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,[P.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var s;(s=this._rtWrapper)===null||s===void 0||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 t,i;const s=this.getScene();if(!s)return;const r=this._fullEngine;if(r.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),r.setState(!1),!this.nodeMaterialSource){for(const a in this._textures)this._drawWrapper.effect.setTexture(a,this._textures[a]);for(const a in this._ints)this._drawWrapper.effect.setInt(a,this._ints[a]);for(const a in this._floats)this._drawWrapper.effect.setFloat(a,this._floats[a]);for(const a in this._floatsArrays)this._drawWrapper.effect.setArray(a,this._floatsArrays[a]);for(const a in this._colors3)this._drawWrapper.effect.setColor3(a,this._colors3[a]);for(const a in this._colors4){const l=this._colors4[a];this._drawWrapper.effect.setFloat4(a,l.r,l.g,l.b,l.a)}for(const a in this._vectors2)this._drawWrapper.effect.setVector2(a,this._vectors2[a]);for(const a in this._vectors3)this._drawWrapper.effect.setVector3(a,this._vectors3[a]);for(const a in this._matrices)this._drawWrapper.effect.setMatrix(a,this._matrices[a])}if(!this._texture||!this._rtWrapper)return;(t=r._debugPushGroup)===null||t===void 0||t.call(r,`procedural texture generation for ${this.name}`,1);const n=r.currentViewport;if(this.isCube)for(let a=0;a<6;a++)r.bindFramebuffer(this._rtWrapper,a,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",a),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Ie.TriangleFillMode,0,6);else r.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&r.clear(s.clearColor,!0,!1,!1),r.drawElementsType(Ie.TriangleFillMode,0,6);r.unBindFramebuffer(this._rtWrapper,this.isCube),n&&r.setViewport(n),this.isCube&&r.generateMipMapsForCubemap(this._texture),(i=r._debugPopGroup)===null||i===void 0||i.call(r,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Jo(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[P.PositionKind];i&&(i.dispose(),this._vertexBuffers[P.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}A([D()],Jo.prototype,"isEnabled",void 0);A([D()],Jo.prototype,"autoClear",void 0);A([D()],Jo.prototype,"_generateMipMaps",void 0);A([D()],Jo.prototype,"_size",void 0);A([D()],Jo.prototype,"refreshRate",null);j("BABYLON.ProceduralTexture",Jo);var tr;(function(o){o[o.Cos=0]="Cos",o[o.Sin=1]="Sin",o[o.Abs=2]="Abs",o[o.Exp=3]="Exp",o[o.Exp2=4]="Exp2",o[o.Round=5]="Round",o[o.Floor=6]="Floor",o[o.Ceiling=7]="Ceiling",o[o.Sqrt=8]="Sqrt",o[o.Log=9]="Log",o[o.Tan=10]="Tan",o[o.ArcTan=11]="ArcTan",o[o.ArcCos=12]="ArcCos",o[o.ArcSin=13]="ArcSin",o[o.Fract=14]="Fract",o[o.Sign=15]="Sign",o[o.Radians=16]="Radians",o[o.Degrees=17]="Degrees"})(tr||(tr={}));class Nb extends nt{constructor(e){super(e,W.Neutral),this.operation=tr.Cos,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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 tr.Cos:{i="cos";break}case tr.Sin:{i="sin";break}case tr.Abs:{i="abs";break}case tr.Exp:{i="exp";break}case tr.Exp2:{i="exp2";break}case tr.Round:{i="round";break}case tr.Floor:{i="floor";break}case tr.Ceiling:{i="ceil";break}case tr.Sqrt:{i="sqrt";break}case tr.Log:{i="log";break}case tr.Tan:{i="tan";break}case tr.ArcTan:{i="atan";break}case tr.ArcCos:{i="acos";break}case tr.ArcSin:{i="asin";break}case tr.Fract:{i="fract";break}case tr.Sign:{i="sign";break}case tr.Radians:{i="radians";break}case tr.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.${tr[this.operation]}; -`}}j("BABYLON.TrigonometryBlock",Db);const uv={effect:null,subMesh:null};class a_ extends Wn{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 ys extends ep{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||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||ht.LastCreatedScene),this._buildId=ys._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new k,this._cachedWorldViewProjectionMatrix=new k,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new he,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=Cn.Material,this.forceAlphaBlending=!1,this._options=Object.assign({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 fe.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&W.Vertex&&this._addVertexOutputNode(e),e.target&W.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&W.Vertex&&this._removeVertexOutputNode(e),e.target&W.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=W.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=W.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===W.VertexAndFragment||t.target===W.Fragment&&e.target===W.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 a=n.ownerBlock;a!==e&&this._processInitializeOnLink(a,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===W.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===Cn.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 i0,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=W.Vertex,this._fragmentCompilationState=new i0,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=W.Fragment,this._sharedData=new lF,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=[],a=[];for(const c of this._vertexOutputNodes)n.push(c),this._initializeBlock(c,this._vertexCompilationState,a,i);for(const c of this._fragmentOutputNodes)a.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 a)this._resetDualBlocks(c,this._buildId-1);for(const c of a)c.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=ys._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(G.Log("Vertex shader:"),G.Log(this._vertexCompilationState.compilationString),G.Log("Fragment shader:"),G.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(P.NormalKind),t.TANGENT=e.isVerticesDataPresent(P.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(P.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let h=1;h<=6;++h){const c=t["UV"+h];t["UV"+h]=e.isVerticesDataPresent(`uv${h===1?"":h}`),a=a||t["UV"+h]!==c}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Me.PrepareDefinesForPrePass(this.getScene(),t,!l),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||a)&&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,a=5){return this.mode!==Cn.PostProcess?(G.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,a=0,l=5){let h=this.name+this._buildId;const c=new a_,u=new hi(h+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(u,c),ji.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 lt(this.name+"PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,c.toString(),a,h,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete ji.ShadersStore[h+"VertexShader"],delete ji.ShadersStore[h+"PixelShader"],h=this.name+this._buildId,c.markAllAsDirty(),d=this._buildId),this._processDefines(u,c)&&(ji.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Qc.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!==Cn.ProceduralTexture)return G.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new Jo(i,e,null,t),r=new hi(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new a_,a=this._processDefines(r,n);ji.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),a==null?void 0:a.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(l);let h=this._buildId;return s.onBeforeGenerationObservable.add(()=>{h!==this._buildId&&(delete ji.ShadersStore[i+"VertexShader"],delete ji.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),h=this._buildId);const c=this._processDefines(r,n);c&&(ji.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Qc.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.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,a,l=""){let h=this.name+this._buildId+"_"+t;n||(n=new a_),a||(a=this.getScene().getMeshByName(this.name+"Particle"),a||(a=new hi(this.name+"Particle",this.getScene()),a.reservedDataStore={hidden:!0}));let c=this._buildId;const u=[];let d=l;if(!r){const f=this._processDefines(a,n);ji.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),d=u.join(` +`}}j("BABYLON.TrigonometryBlock",Nb);const uv={effect:null,subMesh:null};class a_ extends Wn{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 ys extends ep{static _BlockIsTextureBlock(e){return e.getClassName()==="TextureBlock"||e.getClassName()==="ReflectionTextureBaseBlock"||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||ht.LastCreatedScene),this._buildId=ys._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new k,this._cachedWorldViewProjectionMatrix=new k,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new he,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=bn.Material,this.forceAlphaBlending=!1,this._options=Object.assign({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 fe.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&W.Vertex&&this._addVertexOutputNode(e),e.target&W.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&W.Vertex&&this._removeVertexOutputNode(e),e.target&W.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=W.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=W.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===W.VertexAndFragment||t.target===W.Fragment&&e.target===W.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 a=n.ownerBlock;a!==e&&this._processInitializeOnLink(a,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===W.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===bn.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 r0,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=W.Vertex,this._fragmentCompilationState=new r0,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=W.Fragment,this._sharedData=new uF,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=[],a=[];for(const c of this._vertexOutputNodes)n.push(c),this._initializeBlock(c,this._vertexCompilationState,a,i);for(const c of this._fragmentOutputNodes)a.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 a)this._resetDualBlocks(c,this._buildId-1);for(const c of a)c.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=ys._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(G.Log("Vertex shader:"),G.Log(this._vertexCompilationState.compilationString),G.Log("Fragment shader:"),G.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(P.NormalKind),t.TANGENT=e.isVerticesDataPresent(P.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(P.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let h=1;h<=6;++h){const c=t["UV"+h];t["UV"+h]=e.isVerticesDataPresent(`uv${h===1?"":h}`),a=a||t["UV"+h]!==c}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Me.PrepareDefinesForPrePass(this.getScene(),t,!l),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||a)&&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,a=5){return this.mode!==bn.PostProcess?(G.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,a=0,l=5){let h=this.name+this._buildId;const c=new a_,u=new hi(h+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(u,c),ji.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 lt(this.name+"PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,c.toString(),a,h,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete ji.ShadersStore[h+"VertexShader"],delete ji.ShadersStore[h+"PixelShader"],h=this.name+this._buildId,c.markAllAsDirty(),d=this._buildId),this._processDefines(u,c)&&(ji.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Qc.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!==bn.ProceduralTexture)return G.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new Jo(i,e,null,t),r=new hi(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new a_,a=this._processDefines(r,n);ji.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),a==null?void 0:a.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(l);let h=this._buildId;return s.onBeforeGenerationObservable.add(()=>{h!==this._buildId&&(delete ji.ShadersStore[i+"VertexShader"],delete ji.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),h=this._buildId);const c=this._processDefines(r,n);c&&(ji.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Qc.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.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,a,l=""){let h=this.name+this._buildId+"_"+t;n||(n=new a_),a||(a=this.getScene().getMeshByName(this.name+"Particle"),a||(a=new hi(this.name+"Particle",this.getScene()),a.reservedDataStore={hidden:!0}));let c=this._buildId;const u=[];let d=l;if(!r){const f=this._processDefines(a,n);ji.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 ji.ShadersStore[h+"PixelShader"],h=this.name+this._buildId+"_"+t,n.markAllAsDirty(),c=this._buildId),u.length=0,e.fillDefines(u,t);const p=u.join(` `);p!==d&&(n.markAllAsDirty(),d=p);const _=this._processDefines(a,n);if(_){ji.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),f=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+` -`+d,_==null?void 0:_.fallbacks,i,s,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,s,f,n,a,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!==Cn.Particle){G.Log("Incompatible material mode");return}this._createEffectForParticles(e,yo.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,yo.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==Cn.Material){G.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(Me.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(a=>{a.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(a=>{a.prepareDefines(e,this,t,i,s)}),t.isDirty){const a=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 Jh;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,u)}),r={lightDisposed:a,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 l=s.getFrameId();if(this._animationFrame!==l){for(const h of this._sharedData.animatedInputs)h.animate(s);this._animationFrame=l}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new a_);const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(this._prepareDefinesForAttributes(e,r),this._sharedData.blockingBlocks.some(l=>!l.isReady(e,this,r,i)))return!1;const a=this._processDefines(e,r,i,t);if(a){const l=t.effect,h=r.toString();let c=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:h,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:r.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS}},n);if(c)if(this._onEffectCreatedObservable&&(uv.effect=c,uv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(uv)),this.allowShaderHotSwapping&&l&&!c.isReady()){if(c=l,r.markAsUnprocessed(),a.lightDisposed)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(c,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader +`+d,_==null?void 0:_.fallbacks,i,s,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,s,f,n,a,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!==bn.Particle){G.Log("Incompatible material mode");return}this._createEffectForParticles(e,yo.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,yo.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==bn.Material){G.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(Me.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(a=>{a.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(a=>{a.prepareDefines(e,this,t,i,s)}),t.isDirty){const a=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 ec;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,u)}),r={lightDisposed:a,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 l=s.getFrameId();if(this._animationFrame!==l){for(const h of this._sharedData.animatedInputs)h.animate(s);this._animationFrame=l}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new a_);const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(this._prepareDefinesForAttributes(e,r),this._sharedData.blockingBlocks.some(l=>!l.isReady(e,this,r,i)))return!1;const a=this._processDefines(e,r,i,t);if(a){const l=t.effect,h=r.toString();let c=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:h,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:r.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS}},n);if(c)if(this._onEffectCreatedObservable&&(uv.effect=c,uv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(uv)),this.allowShaderHotSwapping&&l&&!c.isReady()){if(c=l,r.markAsUnprocessed(),a.lightDisposed)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(c,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._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,t.visibility),a=this._sharedData;if(n){for(const l of a.bindableBlocks)l.bind(r,this,t,i);for(const l of a.forcedBindableBlocks)l.bind(r,this,t,i);for(const l of a.inputBlocks)l._transmit(r,s,this)}else if(!this.isFrozen)for(const l of a.forcedBindableBlocks)l.bind(r,this,t,i);this._afterBind(t,this._activeEffect)}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)ys._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=Object.assign({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:ys.EditorURL;fe.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 Bt("Position");e.setAsAttribute("position");const t=new Bt("World");t.setAsSystemValue(Gt.World);const i=new Lv("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Bt("ViewProjection");s.setAsSystemValue(Gt.ViewProjection);const r=new Lv("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new v_("VertexOutput");r.connectTo(n);const a=new Bt("color");a.value=new Ze(.8,.8,.8,1);const l=new Jl("FragmentOutput");a.connectTo(l),this.addOutputNode(n),this.addOutputNode(l),this._mode=Cn.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new x_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new v_("VertexOutput");i.connectTo(s);const r=new Bt("Scale");r.visibleInInspector=!0,r.value=new Re(1,1);const n=new em("uv0");e.connectTo(n);const a=new Bv("UV scale");n.connectTo(a),r.connectTo(a);const l=new bb("CurrentScreen");a.connectTo(l),l.texture=new ee("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new Jl("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(h),this._mode=Cn.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new x_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new v_("VertexOutput");i.connectTo(s);const r=new Bt("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Zl.Time,r.isConstant=!1;const n=new Bt("Color3");n.value=new Te(1,1,1),n.isConstant=!1;const a=new Jl("FragmentOutput"),l=new x_("VectorMerger");l.visibleInInspector=!1;const h=new Db("Cos");h.operation=tr.Cos,e.connectTo(l),r.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(a.rgb),this.addOutputNode(s),this.addOutputNode(a),this._mode=Cn.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Bt("uv");e.setAsAttribute("particle_uv");const t=new yb("ParticleTexture");e.connectTo(t);const i=new Bt("Color");i.setAsAttribute("particle_color");const s=new Bv("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ab("ParticleRampGradient");s.connectTo(r);const n=new Ib("ColorSplitter");i.connectTo(n);const a=new Rb("ParticleBlendMultiply");r.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});const l=new Jl("FragmentOutput");a.connectTo(l),this.addOutputNode(l),this._mode=Cn.Particle}async loadAsync(e,t=""){return ys.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.${Cn[this.mode]}; +${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,t.visibility),a=this._sharedData;if(n){for(const l of a.bindableBlocks)l.bind(r,this,t,i);for(const l of a.forcedBindableBlocks)l.bind(r,this,t,i);for(const l of a.inputBlocks)l._transmit(r,s,this)}else if(!this.isFrozen)for(const l of a.forcedBindableBlocks)l.bind(r,this,t,i);this._afterBind(t,this._activeEffect)}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)ys._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=Object.assign({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:ys.EditorURL;fe.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 Vt("Position");e.setAsAttribute("position");const t=new Vt("World");t.setAsSystemValue(Gt.World);const i=new Lv("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Vt("ViewProjection");s.setAsSystemValue(Gt.ViewProjection);const r=new Lv("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new v_("VertexOutput");r.connectTo(n);const a=new Vt("color");a.value=new Ze(.8,.8,.8,1);const l=new eh("FragmentOutput");a.connectTo(l),this.addOutputNode(n),this.addOutputNode(l),this._mode=bn.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Vt("Position");e.setAsAttribute("position2d");const t=new Vt("Constant1");t.isConstant=!0,t.value=1;const i=new x_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new v_("VertexOutput");i.connectTo(s);const r=new Vt("Scale");r.visibleInInspector=!0,r.value=new Re(1,1);const n=new em("uv0");e.connectTo(n);const a=new Bv("UV scale");n.connectTo(a),r.connectTo(a);const l=new Ab("CurrentScreen");a.connectTo(l),l.texture=new ee("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new eh("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(h),this._mode=bn.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Vt("Position");e.setAsAttribute("position2d");const t=new Vt("Constant1");t.isConstant=!0,t.value=1;const i=new x_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new v_("VertexOutput");i.connectTo(s);const r=new Vt("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Jl.Time,r.isConstant=!1;const n=new Vt("Color3");n.value=new Te(1,1,1),n.isConstant=!1;const a=new eh("FragmentOutput"),l=new x_("VectorMerger");l.visibleInInspector=!1;const h=new Nb("Cos");h.operation=tr.Cos,e.connectTo(l),r.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(a.rgb),this.addOutputNode(s),this.addOutputNode(a),this._mode=bn.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Vt("uv");e.setAsAttribute("particle_uv");const t=new Rb("ParticleTexture");e.connectTo(t);const i=new Vt("Color");i.setAsAttribute("particle_color");const s=new Bv("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ib("ParticleRampGradient");s.connectTo(r);const n=new Mb("ColorSplitter");i.connectTo(n);const a=new Pb("ParticleBlendMultiply");r.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});const l=new eh("FragmentOutput");a.connectTo(l),this.addOutputNode(l),this._mode=bn.Particle}async loadAsync(e,t=""){return ys.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.${bn[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+=` @@ -261,7 +261,7 @@ ${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){cons `;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?{}:Xe.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 a of r.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===s.name){const l=n.getInputByName(a.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var s;i||this.clear();const r={};for(const n of e.blocks){const a=Ds(n.customType);if(a){const l=new a;l._deserialize(n,this.getScene(),t),r[n.id]=l,this.attachedBlocks.push(l)}}for(const n of this.attachedBlocks)if(n.isTeleportOut){const a=n,l=a._tempEntryPointUniqueId;l&&r[l].attachToEndpoint(a)}for(let n=0;nnew ys(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=Xe.Parse(()=>new ys(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 a=n??new ys(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s),r||a.build(),a}static ParseFromSnippetAsync(e,t=ht.LastCreatedScene,i="",s,r=!1,n=!1){return e==="_BLANK"?Promise.resolve(ys.CreateDefault("blank",t)):new Promise((a,l)=>{const h=new Hs;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=Xe.Parse(()=>new ys(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(()=>{a(s)}).catch(d=>{l(d)}):a(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 ys(e,t);return i.setToDefault(),i.build(),i}}ys._BuildIdGenerator=0;ys.EditorURL=`${fe._DefaultCdnUrl}/v${re.Version}/nodeEditor/babylon.nodeEditor.js`;ys.SnippetUrl="https://snippet.babylonjs.com";ys.IgnoreTexturesAtLoadTime=!1;A([D()],ys.prototype,"ignoreAlpha",void 0);A([D()],ys.prototype,"maxSimultaneousLights",void 0);A([D("mode")],ys.prototype,"_mode",void 0);A([D("comment")],ys.prototype,"comment",void 0);A([D()],ys.prototype,"forceAlphaBlending",void 0);j("BABYLON.NodeMaterial",ys);function mx(o){const e=o.sideOrientation||De.DEFAULTSIDE,t=o.radius||1,i=o.flat===void 0?!0:o.flat,s=(o.subdivisions||4)|0,r=o.radiusX||t,n=o.radiusY||t,a=o.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,p=239/1024,_=60/1024,g=26/1024,v=-40/1024,E=20/1024,C=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],b=[],R=[],I=[];let N=0;const O=new Array(3),L=new Array(3);let B;for(B=0;B<3;B++)O[B]=T.Zero(),L[B]=Re.Zero();for(let Z=0;Z<20;Z++){for(B=0;B<3;B++){const oe=c[3*Z+B];O[B].copyFromFloats(h[3*u[oe]],h[3*u[oe]+1],h[3*u[oe]+2]),O[B].normalize(),L[B].copyFromFloats(d[2*oe]*f+_+C[Z]*v,d[2*oe+1]*p+g+C[Z]*E)}const ue=(oe,me,le,ae)=>{const ce=T.Lerp(O[0],O[2],me/s),ie=T.Lerp(O[1],O[2],me/s),w=s===me?O[2]:T.Lerp(ce,ie,oe/(s-me));w.normalize();let H;if(i){const _e=T.Lerp(O[0],O[2],ae/s),q=T.Lerp(O[1],O[2],ae/s);H=T.Lerp(_e,q,le/(s-ae))}else H=new T(w.x,w.y,w.z);H.x/=r,H.y/=n,H.z/=a,H.normalize();const X=Re.Lerp(L[0],L[2],me/s),te=Re.Lerp(L[1],L[2],me/s),Q=s===me?L[2]:Re.Lerp(X,te,oe/(s-me));b.push(w.x*r,w.y*n,w.z*a),R.push(H.x,H.y,H.z),I.push(Q.x,pi.UseOpenGLOrientationForUV?1-Q.y:Q.y),S.push(N),N++};for(let oe=0;oegx(o,e,t);var Kl;(function(o){o.WRIST="wrist",o.THUMB="thumb",o.INDEX="index",o.MIDDLE="middle",o.RING="ring",o.LITTLE="little"})(Kl||(Kl={}));var yt;(function(o){o.WRIST="wrist",o.THUMB_METACARPAL="thumb-metacarpal",o.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",o.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",o.THUMB_TIP="thumb-tip",o.INDEX_FINGER_METACARPAL="index-finger-metacarpal",o.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",o.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",o.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",o.INDEX_FINGER_TIP="index-finger-tip",o.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",o.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",o.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",o.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",o.MIDDLE_FINGER_TIP="middle-finger-tip",o.RING_FINGER_METACARPAL="ring-finger-metacarpal",o.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",o.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",o.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",o.RING_FINGER_TIP="ring-finger-tip",o.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",o.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",o.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",o.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",o.PINKY_FINGER_TIP="pinky-finger-tip"})(yt||(yt={}));const mo=[yt.WRIST,yt.THUMB_METACARPAL,yt.THUMB_PHALANX_PROXIMAL,yt.THUMB_PHALANX_DISTAL,yt.THUMB_TIP,yt.INDEX_FINGER_METACARPAL,yt.INDEX_FINGER_PHALANX_PROXIMAL,yt.INDEX_FINGER_PHALANX_INTERMEDIATE,yt.INDEX_FINGER_PHALANX_DISTAL,yt.INDEX_FINGER_TIP,yt.MIDDLE_FINGER_METACARPAL,yt.MIDDLE_FINGER_PHALANX_PROXIMAL,yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE,yt.MIDDLE_FINGER_PHALANX_DISTAL,yt.MIDDLE_FINGER_TIP,yt.RING_FINGER_METACARPAL,yt.RING_FINGER_PHALANX_PROXIMAL,yt.RING_FINGER_PHALANX_INTERMEDIATE,yt.RING_FINGER_PHALANX_DISTAL,yt.RING_FINGER_TIP,yt.PINKY_FINGER_METACARPAL,yt.PINKY_FINGER_PHALANX_PROXIMAL,yt.PINKY_FINGER_PHALANX_INTERMEDIATE,yt.PINKY_FINGER_PHALANX_DISTAL,yt.PINKY_FINGER_TIP],gF={[Kl.WRIST]:[yt.WRIST],[Kl.THUMB]:[yt.THUMB_METACARPAL,yt.THUMB_PHALANX_PROXIMAL,yt.THUMB_PHALANX_DISTAL,yt.THUMB_TIP],[Kl.INDEX]:[yt.INDEX_FINGER_METACARPAL,yt.INDEX_FINGER_PHALANX_PROXIMAL,yt.INDEX_FINGER_PHALANX_INTERMEDIATE,yt.INDEX_FINGER_PHALANX_DISTAL,yt.INDEX_FINGER_TIP],[Kl.MIDDLE]:[yt.MIDDLE_FINGER_METACARPAL,yt.MIDDLE_FINGER_PHALANX_PROXIMAL,yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE,yt.MIDDLE_FINGER_PHALANX_DISTAL,yt.MIDDLE_FINGER_TIP],[Kl.RING]:[yt.RING_FINGER_METACARPAL,yt.RING_FINGER_PHALANX_PROXIMAL,yt.RING_FINGER_PHALANX_INTERMEDIATE,yt.RING_FINGER_PHALANX_DISTAL,yt.RING_FINGER_TIP],[Kl.LITTLE]:[yt.PINKY_FINGER_METACARPAL,yt.PINKY_FINGER_PHALANX_PROXIMAL,yt.PINKY_FINGER_PHALANX_INTERMEDIATE,yt.PINKY_FINGER_PHALANX_DISTAL,yt.PINKY_FINGER_TIP]};class vF{get handMesh(){return this._handMesh}getHandPartMeshes(e){return gF[e].map(t=>this._jointMeshes[mo.indexOf(t)])}getJointMesh(e){return this._jointMeshes[mo.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=new Array(mo.length),this._jointTransformMatrices=new Float32Array(mo.length*16),this._tempJointMatrix=new k,this._jointRadii=new Float32Array(mo.length),this._scene=t[0].getScene();for(let l=0;l{l.rootMesh&&l.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(l=>{l.onModelLoadedObservable.add(h=>{h.rootMesh&&h.rootMesh.setEnabled(!1)}),l.rootMesh&&l.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(i=>i.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){const i=this._handMesh.skeleton;mo.forEach((s,r)=>{const n=i.getBoneIndexByName(t?t[s]:s);n!==-1&&i.bones[n].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=mo.map(a=>s[a]||i.get(a));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 a=0;a{const h=this._jointTransforms[l];k.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(){this._handMesh&&(this._handMesh.isVisible=!1)}}class Gi extends Cr{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var s,r,n,a,l;const h=[],c=((s=e.jointMeshes)===null||s===void 0?void 0:s.sourceMesh)||gx("jointParent",Gi._ICOSPHERE_PARAMS);c.isVisible=!!(!((r=e.jointMeshes)===null||r===void 0)&&r.keepOriginalVisible);for(let u=0;u{var s,r,n,a,l;const h={};!((r=(s=Gi._RightHandGLB)===null||s===void 0?void 0:s.meshes[1])===null||r===void 0)&&r.isDisposed()&&(Gi._RightHandGLB=null),!((a=(n=Gi._LeftHandGLB)===null||n===void 0?void 0:n.meshes[1])===null||a===void 0)&&a.isDisposed()&&(Gi._LeftHandGLB=null);const c=!!(Gi._RightHandGLB&&Gi._LeftHandGLB),u=await Promise.all([Gi._RightHandGLB||Ft.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Gi._LeftHandGLB||Ft.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Gi._RightHandGLB=u[0],Gi._LeftHandGLB=u[1];const d=new ys("handShader",e,{emitComments:!1});await d.loadAsync(Gi.DEFAULT_HAND_MODEL_SHADER_URL),d.needDepthPrePass=!0,d.transparencyMode=Ie.MATERIAL_ALPHABLEND,d.alphaMode=2,d.build(!1);const f=Object.assign({base:Te.FromInts(116,63,203),fresnel:Te.FromInts(149,102,229),fingerColor:Te.FromInts(177,130,255),tipFresnel:Te.FromInts(220,200,255)},(l=t==null?void 0:t.handMeshes)===null||l===void 0?void 0:l.customColors),p={base:d.getBlockByName("baseColor"),fresnel:d.getBlockByName("fresnelColor"),fingerColor:d.getBlockByName("fingerColor"),tipFresnel:d.getBlockByName("tipFresnelColor")};p.base.value=f.base,p.fresnel.value=f.fresnel,p.fingerColor.value=f.fingerColor,p.tipFresnel.value=f.tipFresnel,["left","right"].forEach(_=>{const g=_=="left"?Gi._LeftHandGLB:Gi._RightHandGLB;if(!g)throw new Error("Could not load hand model");const v=g.meshes[1];v._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,v.material=d.clone(`${_}HandShaderClone`,!0),v.isVisible=!1,h[_]=v,!c&&!e.useRightHandedSystem&&g.meshes[1].rotate(an.Y,Math.PI)}),d.dispose(),i({left:h.left,right:h.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[yt.WRIST]:`wrist_${t}`,[yt.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[yt.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[yt.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[yt.THUMB_TIP]:`thumb_tip_${t}`,[yt.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[yt.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[yt.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[yt.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[yt.INDEX_FINGER_TIP]:`index_tip_${t}`,[yt.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[yt.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[yt.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[yt.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[yt.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[yt.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[yt.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[yt.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[yt.RING_FINGER_TIP]:`ring_tip_${t}`,[yt.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[yt.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[yt.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[yt.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[yt.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.onHandAddedObservable=new he,this.onHandRemovedObservable=new he,this._attachHand=r=>{var n,a,l;if(!r.inputSource.hand||r.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const h=r.inputSource.handedness,c=new vF(r,this._handResources.jointMeshes[h],this._handResources.handMeshes&&this._handResources.handMeshes[h],this._handResources.rigMappings&&this._handResources.rigMappings[h],(n=this.options.handMeshes)===null||n===void 0?void 0:n.meshesUseLeftHandedCoordinates,(a=this.options.jointMeshes)===null||a===void 0?void 0:a.invisible,(l=this.options.jointMeshes)===null||l===void 0?void 0:l.scaleFactor);this._attachedHands[r.uniqueId]=c,this._trackingHands[h]=c,this.onHandAddedObservable.notifyObservers(c)},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(a=>{const l=a[0],h=a[1];l.forEach((c,u)=>{h[mo[u]]=c})}),t.handMeshes.customRigMappings={left:r,right:n}}}attach(){var e,t,i,s;return super.attach()?(this._handResources={jointMeshes:Gi._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)===null||e===void 0?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)===null||t===void 0?void 0:t.customRigMappings)||null},!(!((i=this.options.handMeshes)===null||i===void 0)&&i.customMeshes)&&!(!((s=this.options.handMeshes)===null||s===void 0)&&s.disableDefaultMeshes)&&Gi._GenerateDefaultHandMeshesAsync(ht.LastCreatedScene,this.options).then(r=>{var n,a;this._handResources.handMeshes=r,this._handResources.rigMappings={left:Gi._GenerateDefaultHandMeshRigMapping("left"),right:Gi._GenerateDefaultHandMeshRigMapping("right")},(n=this._trackingHands.left)===null||n===void 0||n.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),(a=this._trackingHands.right)===null||a===void 0||a.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),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===void 0||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)===null||i===void 0||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const s=i.xrController.inputSource.handedness=="left"?"left":"right";((t=this._trackingHands[s])===null||t===void 0?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return super.detach()?(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(!((e=this.options.handMeshes)===null||e===void 0)&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Gi._RightHandGLB=null,Gi._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}Gi.Name=oi.HAND_TRACKING;Gi.Version=1;Gi.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";Gi.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";Gi._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};Gi._RightHandGLB=null;Gi._LeftHandGLB=null;_s.AddWebXRFeature(Gi.Name,(o,e)=>()=>new Gi(o,e),Gi.Version,!1);var n0;(function(o){o[o.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",o[o.RADIAL_SIDE=1]="RADIAL_SIDE",o[o.ULNAR_SIDE=2]="ULNAR_SIDE",o[o.BELOW_WRIST=3]="BELOW_WRIST"})(n0||(n0={}));var a0;(function(o){o[o.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",o[o.HAND_ROTATION=1]="HAND_ROTATION"})(a0||(a0={}));var o0;(function(o){o[o.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",o[o.PALM_UP=1]="PALM_UP",o[o.GAZE_FOCUS=2]="GAZE_FOCUS",o[o.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(o0||(o0={}));T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero();Se.Identity();k.Identity(),k.Identity();js.BuildArray(10,T.Zero);Se.Identity();js.BuildArray(5,k.Identity);class Rd{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=k.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 he,this.bones=[],this._scene=i||ht.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){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),this._transformMatrices)}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let 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-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){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,K.Matrix[1]),r._updateAbsoluteBindMatrices(K.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=Ws.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=Ws.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{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 e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=s.animations[0].serialize()),t.ranges=[];for(const a in this._ranges){const l=this._ranges[a];if(!l)continue;const h={};h.name=a,h.from=l.from,h.to=l.to,t.ranges.push(h)}}return t}static Parse(e,t){const i=new Rd(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=T.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let s;for(s=0;s-1&&(a=i.bones[r.parentBoneIndex]);const l=r.rest?k.FromArray(r.rest):null,h=new rs(r.name,i,a,k.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(Ee.Parse(r.animation)),r.linkedTransformNodeId!==void 0&&r.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,h._waitingTransformNodeId=r.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class xF{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 Ku=(()=>{const o=new Uint8Array(4),e=new Uint32Array(o.buffer);return!!((e[0]=1)&o[0])})();Object.defineProperty(P.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});P.prototype._rebuild=function(){var o,e;(o=this._buffer)===null||o===void 0||o._rebuild(),(e=this._alignedBuffer)===null||e===void 0||e._rebuild()};P.prototype.dispose=function(){var o;this._ownsBuffer&&this._buffer.dispose(),(o=this._alignedBuffer)===null||o===void 0||o.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};P.prototype._alignBuffer=function(){var o,e;const t=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4===0||!t)return;const i=P.GetTypeByteLength(this.type),s=this.byteStride+3&-4,r=s/i,n=this.totalVertices,l=n*s/i;let h;if(Array.isArray(t)){const f=new Float32Array(t);h=new DataView(f.buffer,f.byteOffset,f.byteLength)}else t instanceof ArrayBuffer?h=new DataView(t,0,t.byteLength):h=new DataView(t.buffer,t.byteOffset,t.byteLength);let c;this.type===P.BYTE?c=new Int8Array(l):this.type===P.UNSIGNED_BYTE?c=new Uint8Array(l):this.type===P.SHORT?c=new Int16Array(l):this.type===P.UNSIGNED_SHORT?c=new Uint16Array(l):this.type===P.INT?c=new Int32Array(l):this.type===P.UNSIGNED_INT?c=new Uint32Array(l):c=new Float32Array(l);const u=this.getSize();let d=this.byteOffset;for(let f=0;f{if(t.type!==rt.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===fu.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,rt.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"}}A([D()],om.prototype,"wheelPrecisionX",void 0);A([D()],om.prototype,"wheelPrecisionY",void 0);A([D()],om.prototype,"wheelPrecisionZ",void 0);class vx{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=fe.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=a=>{var l,h;const c=a.event,u=c.pointerType==="touch";if(a.type!==rt.POINTERMOVE&&this.buttons.indexOf(c.button)===-1)return;const d=c.target;if(this._altKey=c.altKey,this._ctrlKey=c.ctrlKey,this._metaKey=c.metaKey,this._shiftKey=c.shiftKey,this._buttonsPressed=c.buttons,t.isPointerLock){const f=c.movementX,p=c.movementY;this.onTouch(null,f,p),this._pointA=null,this._pointB=null}else{if(a.type!==rt.POINTERDOWN&&u&&((l=this._pointA)===null||l===void 0?void 0:l.pointerId)!==c.pointerId&&((h=this._pointB)===null||h===void 0?void 0:h.pointerId)!==c.pointerId)return;if(a.type===rt.POINTERDOWN&&(this._currentActiveButton===-1||u)){try{d==null||d.setPointerCapture(c.pointerId)}catch{}if(this._pointA===null)this._pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else if(this._pointB===null)this._pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else return;this._currentActiveButton===-1&&!u&&(this._currentActiveButton=c.button),this.onButtonDown(c),e||(c.preventDefault(),i&&i.focus())}else if(a.type===rt.POINTERDOUBLETAP)this.onDoubleTap(c.pointerType);else if(a.type===rt.POINTERUP&&(this._currentActiveButton===c.button||u)){try{d==null||d.releasePointerCapture(c.pointerId)}catch{}u||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==c.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==c.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(c),e||c.preventDefault()}else if(a.type===rt.POINTERMOVE){if(e||c.preventDefault(),this._pointA&&this._pointB===null){const f=c.clientX-this._pointA.x,p=c.clientY-this._pointA.y;this.onTouch(this._pointA,f,p),this._pointA.x=c.clientX,this._pointA.y=c.clientY}else if(this._pointA&&this._pointB){const f=this._pointA.pointerId===c.pointerId?this._pointA:this._pointB;f.x=c.clientX,f.y=c.clientY;const p=this._pointA.x-this._pointB.x,_=this._pointA.y-this._pointB.y,g=p*p+_*_,v={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:c.pointerId,type:a.type};this.onMultiTouch(this._pointA,this._pointB,s,g,r,v),r=v,s=g}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,rt.POINTERDOWN|rt.POINTERUP|rt.POINTERMOVE|rt.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=a=>this.onContextMenu(a),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&fe.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&fe.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(){}}A([D()],vx.prototype,"buttons",void 0);var qr={};class lm{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){G.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=et.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=Xe.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=qr[i];if(s){const r=t[i],n=Xe.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=qr[this.attached[i].getClassName()];if(s){const r=Xe.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class xr{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=xr.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}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(){}}xr.GAMEPAD=0;xr.GENERIC=1;xr.XBOX=2;xr.POSE_ENABLED=3;xr.DUALSHOCK=4;class TF extends xr{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new he,this.onButtonUpObservable=new he,this.type=xr.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{t.type!==xr.POSE_ENABLED&&(!this.gamepad||t.type===xr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(xr.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(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"}}A([D()],hm.prototype,"gamepadRotationSensibility",void 0);A([D()],hm.prototype,"gamepadMoveSensibility",void 0);qr.ArcRotateCameraGamepadInput=hm;class Ro{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=fe.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===uh.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?i=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==rt.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===fu.DOM_DELTA_LINE?EF: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 a=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)a-=l,l*=this.camera.inertia;a=ye.Clamp(a,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,a)}}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,rt.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=An.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),s=i.createPickingRay(i.pointerX,i.pointerY,k.Identity(),t,!1);(t.targetScreenOffset.x!==0||t.targetScreenOffset.y!==0)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=T.TransformNormal(this._viewOffset,t._cameraTransformMatrix),s.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(e=s.intersectsPlane(this._hitPlane))!==null&&e!==void 0?e:0),s.origin.addInPlace(s.direction.scaleInPlace(r))}_zoomToMouse(e){var t,i;const s=this.camera,r=1-s.inertia;if(s.lowerRadiusLimit){const c=(t=s.lowerRadiusLimit)!==null&&t!==void 0?t:0;s.radius-(s.inertialRadiusOffset+e)/rc&&(e=(s.radius-c)*r-s.inertialRadiusOffset)}const a=e/r/s.radius,l=this._getPosition(),h=K.Vector3[6];l.subtractToRef(s.target,h),h.scaleInPlace(a),h.scaleInPlace(r),this._inertialPanning.addInPlace(h),s.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<$t&&(e.x=0),Math.abs(e.y)<$t&&(e.y=0),Math.abs(e.z)<$t&&(e.z=0)}}A([D()],sp.prototype,"wheelPrecision",void 0);A([D()],sp.prototype,"zoomToMouseLocation",void 0);A([D()],sp.prototype,"wheelDeltaPercentage",void 0);qr.ArcRotateCameraMouseWheelInput=sp;class Hn extends vx{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||Hn.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}}Hn.MinimumRadiusForPinch=.001;A([D()],Hn.prototype,"buttons",void 0);A([D()],Hn.prototype,"angularSensibilityX",void 0);A([D()],Hn.prototype,"angularSensibilityY",void 0);A([D()],Hn.prototype,"pinchPrecision",void 0);A([D()],Hn.prototype,"pinchDeltaPercentage",void 0);A([D()],Hn.prototype,"useNaturalPinchZoom",void 0);A([D()],Hn.prototype,"pinchZoom",void 0);A([D()],Hn.prototype,"panningSensibility",void 0);A([D()],Hn.prototype,"multiTouchPanning",void 0);A([D()],Hn.prototype,"multiTouchPanAndZoom",void 0);qr.ArcRotateCameraPointersInput=Hn;class xx extends lm{constructor(e){super(e)}addMouseWheel(){return this.add(new sp),this}addPointers(){return this.add(new Hn),this}addKeyboard(){return this.add(new Ro),this}}xx.prototype.addVRDeviceOrientation=function(){return this.add(new Ob),this};class Ob{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=fe.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):fe.Warn("Permission not granted.")}).catch(i=>{fe.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"}}qr.ArcRotateCameraVRDeviceOrientationInput=Ob;class xh{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=fe.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===uh.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._pointerInput(t)},rt.POINTERDOWN|rt.POINTERUP|rt.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!==rt.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const r=t.target;if(e.type===rt.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===rt.POINTERUP){try{r==null||r.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===rt.POINTERMOVE){if(!this._previousPosition){s.isPointerLock&&this._onMouseMove(e.event);return}const n=t.clientX-this._previousPosition.x,a=t.clientY-this._previousPosition.y;this._rotateCamera(n,a),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,a=Se.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(h=>h===this.activeButton)&&(l=Se.RotationAxis(an.X,n),a.multiplyInPlace(l)),this.buttonsYaw.some(h=>h===this.activeButton)){l=Se.RotationAxis(an.Y,r),a.multiplyInPlace(l);const h=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-hh===this.activeButton)&&(l=Se.RotationAxis(an.Z,-r),i._trackRoll-=r,a.multiplyInPlace(l)),a.toEulerAnglesToRef(i.rotation)}}A([D()],cm.prototype,"buttons",void 0);A([D()],cm.prototype,"angularSensibility",void 0);qr.FlyCameraMouseInput=cm;class Gr{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=fe.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===uh.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}}A([D()],Gr.prototype,"keysHeightOffsetIncr",void 0);A([D()],Gr.prototype,"keysHeightOffsetDecr",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierAlt",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierCtrl",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierShift",void 0);A([D()],Gr.prototype,"keysRotationOffsetIncr",void 0);A([D()],Gr.prototype,"keysRotationOffsetDecr",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierAlt",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierCtrl",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierShift",void 0);A([D()],Gr.prototype,"keysRadiusIncr",void 0);A([D()],Gr.prototype,"keysRadiusDecr",void 0);A([D()],Gr.prototype,"keysRadiusModifierAlt",void 0);A([D()],Gr.prototype,"keysRadiusModifierCtrl",void 0);A([D()],Gr.prototype,"keysRadiusModifierShift",void 0);A([D()],Gr.prototype,"heightSensibility",void 0);A([D()],Gr.prototype,"rotationSensibility",void 0);A([D()],Gr.prototype,"radiusSensibility",void 0);qr.FollowCameraKeyboardMoveInput=Gr;class ec{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==rt.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&&G.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,rt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}A([D()],ec.prototype,"axisControlRadius",void 0);A([D()],ec.prototype,"axisControlHeight",void 0);A([D()],ec.prototype,"axisControlRotation",void 0);A([D()],ec.prototype,"wheelPrecision",void 0);A([D()],ec.prototype,"wheelDeltaPercentage",void 0);qr.FollowCameraMouseWheelInput=ec;class Xn extends vx{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 a=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_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&&G.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&G.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&G.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}A([D()],Xn.prototype,"angularSensibilityX",void 0);A([D()],Xn.prototype,"angularSensibilityY",void 0);A([D()],Xn.prototype,"pinchPrecision",void 0);A([D()],Xn.prototype,"pinchDeltaPercentage",void 0);A([D()],Xn.prototype,"axisXControlRadius",void 0);A([D()],Xn.prototype,"axisXControlHeight",void 0);A([D()],Xn.prototype,"axisXControlRotation",void 0);A([D()],Xn.prototype,"axisYControlRadius",void 0);A([D()],Xn.prototype,"axisYControlHeight",void 0);A([D()],Xn.prototype,"axisYControlRotation",void 0);A([D()],Xn.prototype,"axisPinchControlRadius",void 0);A([D()],Xn.prototype,"axisPinchControlHeight",void 0);A([D()],Xn.prototype,"axisPinchControlRotation",void 0);qr.FollowCameraPointersInput=Xn;class La{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=fe.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===uh.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{const r=s.event,n=r.pointerType==="touch";if(!this.touchEnabled&&n||s.type!==rt.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const a=r.target;if(s.type===rt.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{a==null||a.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===rt.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{a==null||a.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===rt.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 a=s.movementY;this.camera.cameraRotation.x+=a/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,rt.POINTERDOWN|rt.POINTERUP|rt.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"}}A([D()],um.prototype,"buttons",void 0);A([D()],um.prototype,"angularSensibility",void 0);qr.FreeCameraMouseInput=um;var Zi;(function(o){o[o.MoveRelative=0]="MoveRelative",o[o.RotateRelative=1]="RotateRelative",o[o.MoveScene=2]="MoveScene"})(Zi||(Zi={}));class Io extends om{constructor(){super(...arguments),this._moveRelative=T.Zero(),this._rotateRelative=T.Zero(),this._moveScene=T.Zero(),this._wheelXAction=Zi.MoveRelative,this._wheelXActionCoordinate=wh.X,this._wheelYAction=Zi.MoveRelative,this._wheelYActionCoordinate=wh.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Zi.MoveRelative||(this._wheelXAction=Zi.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Zi.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Zi.MoveRelative||(this._wheelYAction=Zi.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Zi.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Zi.MoveRelative||(this._wheelZAction=Zi.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Zi.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Zi.RotateRelative||(this._wheelXAction=Zi.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Zi.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Zi.RotateRelative||(this._wheelYAction=Zi.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Zi.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Zi.RotateRelative||(this._wheelZAction=Zi.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Zi.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Zi.MoveScene||(this._wheelXAction=Zi.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Zi.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Zi.MoveScene||(this._wheelYAction=Zi.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Zi.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Zi.MoveScene||(this._wheelZAction=Zi.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Zi.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=k.Zero();this.camera.getViewMatrix().invertToRef(e);const t=T.Zero();T.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 Zi.MoveRelative:s=this._moveRelative;break;case Zi.RotateRelative:s=this._rotateRelative;break;case Zi.MoveScene:s=this._moveScene;break}switch(i){case wh.X:s.set(e,0,0);break;case wh.Y:s.set(0,e,0);break;case wh.Z:s.set(0,0,e);break}}}A([D()],Io.prototype,"wheelXMoveRelative",null);A([D()],Io.prototype,"wheelYMoveRelative",null);A([D()],Io.prototype,"wheelZMoveRelative",null);A([D()],Io.prototype,"wheelXRotateRelative",null);A([D()],Io.prototype,"wheelYRotateRelative",null);A([D()],Io.prototype,"wheelZRotateRelative",null);A([D()],Io.prototype,"wheelXMoveScene",null);A([D()],Io.prototype,"wheelYMoveScene",null);A([D()],Io.prototype,"wheelZMoveScene",null);qr.FreeCameraMouseWheelInput=Io;class dm{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=fe.IsSafari()}attachControl(e){e=fe.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===rt.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===rt.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===rt.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,rt.POINTERDOWN|rt.POINTERUP|rt.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 T(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);k.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(T.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}A([D()],dm.prototype,"touchAngularSensibility",void 0);A([D()],dm.prototype,"touchMoveSensibility",void 0);qr.FreeCameraTouchInput=dm;class fm extends lm{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new La),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new um(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Io,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new dm),this}clear(){super.clear(),this._mouseInput=null}}fm.prototype.addDeviceOrientation=function(o){return this._deviceOrientationInput||(this._deviceOrientationInput=new Nb,o&&(this._deviceOrientationInput.smoothFactor=o),this.add(this._deviceOrientationInput)),this};class Nb{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):fe.Warn("Permission not granted.")}).catch(n=>{fe.Error(n)}):window.addEventListener("deviceorientation",r)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new Se,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new he,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-fe.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?fe.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?fe.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?fe.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 Se(-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 Se),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():fe.Warn("Permission not granted.")}).catch(i=>{fe.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(Se.RotationYawPitchRollToRef(fe.ToRadians(this._alpha),fe.ToRadians(this._beta),-fe.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"}}qr.FreeCameraDeviceOrientationInput=Nb;class pm{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=k.Identity(),this._deltaTransform=T.Zero(),this._vector3=T.Zero(),this._vector2=Re.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!==xr.POSE_ENABLED&&(!this.gamepad||t.type===xr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(xr.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):k.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),T.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"}}A([D()],pm.prototype,"gamepadAngularSensibility",void 0);A([D()],pm.prototype,"gamepadMoveSensibility",void 0);qr.FreeCameraGamepadInput=pm;var fr;(function(o){o[o.X=0]="X",o[o.Y=1]="Y",o[o.Z=2]="Z"})(fr||(fr={}));class dt{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=Object.assign(Object.assign({},dt._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,dt._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=fr.X,this._axisTargetedByUpAndDown=fr.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Ov,this.deltaPosition=T.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{dt._VJCanvasWidth=window.innerWidth,dt._VJCanvasHeight=window.innerHeight,dt.Canvas&&(dt.Canvas.width=dt._VJCanvasWidth,dt.Canvas.height=dt._VJCanvasHeight),dt._HalfWidth=dt._VJCanvasWidth/2},!dt.Canvas){window.addEventListener("resize",this._onResize,!1),dt.Canvas=document.createElement("canvas"),dt._VJCanvasWidth=window.innerWidth,dt._VJCanvasHeight=window.innerHeight,dt.Canvas.width=window.innerWidth,dt.Canvas.height=window.innerHeight,dt.Canvas.style.width="100%",dt.Canvas.style.height="100%",dt.Canvas.style.position="absolute",dt.Canvas.style.backgroundColor="transparent",dt.Canvas.style.top="0px",dt.Canvas.style.left="0px",dt.Canvas.style.zIndex="5",dt.Canvas.style.touchAction="none",dt.Canvas.setAttribute("touch-action","none");const s=dt.Canvas.getContext("2d");if(!s)throw new Error("Unable to create canvas for virtual joystick");dt._VJCanvasContext=s,dt._VJCanvasContext.strokeStyle="#ffffff",dt._VJCanvasContext.lineWidth=2,document.body.appendChild(dt.Canvas)}dt._HalfWidth=dt.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&&dt._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Re(0,0),this._joystickPreviousPointerPos=new Re(0,0),this._joystickPointerStartPos=new Re(0,0),this._deltaJoystickVector=new Re(0,0),this._onPointerDownHandlerRef=s=>{this._onPointerDown(s)},this._onPointerMoveHandlerRef=s=>{this._onPointerMove(s)},this._onPointerUpHandlerRef=s=>{this._onPointerUp(s)},dt.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),dt.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),dt.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),dt.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),dt.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.clientXdt._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)):dt._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 Re(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),a=n.length();a>this.containerSize&&n.scaleInPlace(this.containerSize/a),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),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?dt._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.lineWidth=2,dt._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath(),dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.lineWidth=6,dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?dt._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.lineWidth=2,dt._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._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()):(dt._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.fillStyle="white",dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle="red",dt._VJCanvasContext.lineWidth=6,dt._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){dt.Canvas&&(dt.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),dt.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),dt.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),dt.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(dt.Canvas),dt.Canvas=null),this._released=!0}}dt._GlobalJoystickIndex=0;dt._AlwaysVisibleSticks=0;fm.prototype.addVirtualJoystick=function(){return this.add(new wb),this};class wb{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=k.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=T.TransformCoordinates(new T(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 dt(!0),this._leftjoystick.setAxisForUpDown(fr.Z),this._leftjoystick.setAxisForLeftRight(fr.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new dt(!1),this._rightjoystick.setAxisForUpDown(fr.X),this._rightjoystick.setAxisForLeftRight(fr.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"}}qr.FreeCameraVirtualJoystickInput=wb;class Us extends et{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=T.Zero(),this._tmpTargetVector=T.Zero(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new Re(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new Se,this.rotation=new T(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=T.Zero(),this._initialFocalDistance=1,this._viewMatrix=k.Zero(),this._camMatrix=k.Zero(),this._cameraTransformMatrix=k.Zero(),this._cameraRotationMatrix=k.Zero(),this._referencePoint=new T(0,0,1),this._transformedReferencePoint=T.Zero(),this._deferredPositionUpdate=new T,this._deferredRotationQuaternionUpdate=new Se,this._deferredRotationUpdate=new T,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=T.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 T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Se(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+=$t),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),k.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&&Se.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(K.Matrix[0]),T.TransformNormalToRef(this.cameraDirection,K.Matrix[0],K.Vector3[0]),this._deferredPositionUpdate.addInPlace(K.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()&&(Se.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._newPosition.copyFrom(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>re.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&a&&this.onCollide(a))},this.inputs=new fm(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=fe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new Re(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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=T.Zero(),this._transformedDirection=T.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"}}A([kr()],zn.prototype,"ellipsoid",void 0);A([kr()],zn.prototype,"ellipsoidOffset",void 0);A([D()],zn.prototype,"checkCollisions",void 0);A([D()],zn.prototype,"applyGravity",void 0);Mi.AddNodeConstructor("TouchCamera",(o,e)=>()=>new Fb(o,T.Zero(),e));class Fb extends zn{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Mi.AddNodeConstructor("ArcRotateCamera",(o,e)=>()=>new Ji(o,0,0,1,T.Zero(),e));class Ji extends Us{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 k,this._upToYMatrix=new k,this._upVector=T.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){k.RotationAlignToRef(T.UpReadOnly,this._upVector,this._yToUpMatrix),k.RotationAlignToRef(this._upVector,T.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 Gh,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 Un,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 oF,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,a=!0){super(e,T.Zero(),n,a),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=T.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Re.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new k,this.panningAxis=new T(1,1,0),this._transformedDirection=new T,this.mapPanning=!1,this.onMeshTargetChangedObservable=new he,this.checkCollisions=!1,this.collisionRadius=new T(.5,.5,.5),this._previousPosition=T.Zero(),this._collisionVelocity=T.Zero(),this._newPosition=T.Zero(),this._computationVector=T.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 p=Math.sin(this.beta);p===0&&(p=1e-4);const _=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*p,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,_,g),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=T.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new xx(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new T(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=Re.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=fe.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)<$t&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<$t&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&T.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){var r;if(s=(r=this.overrideCloneAlphaBetaRadius)!==null&&r!==void 0?r:s,e.getBoundingInfo)t?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 n=e,a=this._getTargetPosition();if(a&&!i&&a.equals(n))return;this._targetHost=null,this._target=n,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)&&T.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=se.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=se.MinMax(r),s=T.Distance(i.min,i.max)}else{const r=e;i=r,s=r.distance}this._target=se.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case et.RIG_MODE_STEREOSCOPIC_INTERLACED:case et.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new Ji(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 et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case et.RIG_MODE_STEREOSCOPIC_INTERLACED:case et.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case et.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=T.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),a=Math.tan(this.fov/2),l=a*n,c=s*.5*i,u=c*Math.sqrt(1+1/(l*l)),d=c*Math.sqrt(1+1/(a*a));return Math.max(u,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}A([D()],Ji.prototype,"alpha",void 0);A([D()],Ji.prototype,"beta",void 0);A([D()],Ji.prototype,"radius",void 0);A([D()],Ji.prototype,"overrideCloneAlphaBetaRadius",void 0);A([kr("target")],Ji.prototype,"_target",void 0);A([Qf("targetHost")],Ji.prototype,"_targetHost",void 0);A([D()],Ji.prototype,"inertialAlphaOffset",void 0);A([D()],Ji.prototype,"inertialBetaOffset",void 0);A([D()],Ji.prototype,"inertialRadiusOffset",void 0);A([D()],Ji.prototype,"lowerAlphaLimit",void 0);A([D()],Ji.prototype,"upperAlphaLimit",void 0);A([D()],Ji.prototype,"lowerBetaLimit",void 0);A([D()],Ji.prototype,"upperBetaLimit",void 0);A([D()],Ji.prototype,"lowerRadiusLimit",void 0);A([D()],Ji.prototype,"upperRadiusLimit",void 0);A([D()],Ji.prototype,"inertialPanningX",void 0);A([D()],Ji.prototype,"inertialPanningY",void 0);A([D()],Ji.prototype,"pinchToPanMaxDistance",void 0);A([D()],Ji.prototype,"panningDistanceLimit",void 0);A([kr()],Ji.prototype,"panningOriginTarget",void 0);A([D()],Ji.prototype,"panningInertia",void 0);A([D()],Ji.prototype,"zoomToMouseLocation",null);A([D()],Ji.prototype,"zoomOnFactor",void 0);A([ix()],Ji.prototype,"targetScreenOffset",void 0);A([D()],Ji.prototype,"allowUpsideDown",void 0);A([D()],Ji.prototype,"useInputToRestoreState",void 0);Mi.AddNodeConstructor("DeviceOrientationCamera",(o,e)=>()=>new Tx(o,T.Zero(),e));class Tx extends zn{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new Se,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new Se,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 Se),Se.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=an.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Se),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 SF extends lm{constructor(e){super(e)}addKeyboard(){return this.add(new xh),this}addMouse(){return this.add(new cm),this}}class _m extends Us{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 T(1,1,1),this.ellipsoidOffset=new T(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=T.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=T.Zero(),this._diffPosition=T.Zero(),this._newPosition=T.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,a=null)=>{(h=>{this._newPosition.copyFrom(h),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>re.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&a&&this.onCollide(a))})(n)},this.inputs=new SF(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=fe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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=T.Zero(),this._transformedDirection=T.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"}}A([kr()],_m.prototype,"ellipsoid",void 0);A([kr()],_m.prototype,"ellipsoidOffset",void 0);A([D()],_m.prototype,"checkCollisions",void 0);A([D()],_m.prototype,"applyGravity",void 0);class CF extends lm{constructor(e){super(e)}addKeyboard(){return this.add(new Gr),this}addMouseWheel(){return this.add(new ec),this}addPointers(){return this.add(new Xn),this}addVRDeviceOrientation(){return G.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Mi.AddNodeConstructor("FollowCamera",(o,e)=>()=>new Ba(o,T.Zero(),e));Mi.AddNodeConstructor("ArcFollowCamera",(o,e)=>()=>new bF(o,0,0,1,null,e));class Ba extends Us{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 CF(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=K.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=fe.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,a=r.z+Math.cos(s)*this.radius,l=n-this.position.x,h=r.y+this.heightOffset-this.position.y,c=a-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 T(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(r)}attachControl(e,t){t=fe.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.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}A([D()],Ba.prototype,"radius",void 0);A([D()],Ba.prototype,"lowerRadiusLimit",void 0);A([D()],Ba.prototype,"upperRadiusLimit",void 0);A([D()],Ba.prototype,"rotationOffset",void 0);A([D()],Ba.prototype,"lowerRotationOffsetLimit",void 0);A([D()],Ba.prototype,"upperRotationOffsetLimit",void 0);A([D()],Ba.prototype,"heightOffset",void 0);A([D()],Ba.prototype,"lowerHeightOffsetLimit",void 0);A([D()],Ba.prototype,"upperHeightOffsetLimit",void 0);A([D()],Ba.prototype,"cameraAcceleration",void 0);A([D()],Ba.prototype,"maxCameraSpeed",void 0);A([Qf("lockedTargetId")],Ba.prototype,"lockedTarget",void 0);class bF extends Us{constructor(e,t,i,s,r,n){super(e,T.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=T.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 ia;(function(o){o[o.A=0]="A",o[o.B=1]="B",o[o.X=2]="X",o[o.Y=3]="Y",o[o.LB=4]="LB",o[o.RB=5]="RB",o[o.Back=8]="Back",o[o.Start=9]="Start",o[o.LeftStick=10]="LeftStick",o[o.RightStick=11]="RightStick"})(ia||(ia={}));var Mc;(function(o){o[o.Up=12]="Up",o[o.Down=13]="Down",o[o.Left=14]="Left",o[o.Right=15]="Right"})(Mc||(Mc={}));class yF extends xr{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new he,this.onButtonUpObservable=new he,this.onPadDownObservable=new he,this.onPadUpObservable=new he,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=xr.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,ia.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,ia.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,ia.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,ia.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,ia.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,ia.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,ia.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,ia.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,ia.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,ia.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Mc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Mc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Mc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Mc.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 Qa;(function(o){o[o.Cross=0]="Cross",o[o.Circle=1]="Circle",o[o.Square=2]="Square",o[o.Triangle=3]="Triangle",o[o.L1=4]="L1",o[o.R1=5]="R1",o[o.Share=8]="Share",o[o.Options=9]="Options",o[o.LeftStick=10]="LeftStick",o[o.RightStick=11]="RightStick"})(Qa||(Qa={}));var Dc;(function(o){o[o.Up=12]="Up",o[o.Down=13]="Down",o[o.Left=14]="Left",o[o.Right=15]="Right"})(Dc||(Dc={}));class AF extends xr{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 he,this.onButtonUpObservable=new he,this.onPadDownObservable=new he,this.onPadUpObservable=new he,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=xr.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,Qa.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Qa.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Qa.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Qa.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Qa.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Qa.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Qa.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Qa.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Qa.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Qa.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Dc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Dc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Dc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Dc.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 RF{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new he,gr()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new he(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=xr.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 yF(e.id,e.index,e,s):i?t=new AF(e.id,e.index,e):t=new TF(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&&(fe.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&re.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new _u(o,T.Zero(),e));class _u extends Fb{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"}}et._CreateDefaultParsedCamera=(o,e)=>new _u(o,T.Zero(),e);Mi.AddNodeConstructor("GamepadCamera",(o,e)=>()=>new Ex(o,T.Zero(),e));class Ex extends _u{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const PF="passCubePixelShader",MF=`varying vec2 vUV;uniform samplerCube textureSampler; +`,r}serialize(e){const t=e?{}:Xe.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 a of r.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===s.name){const l=n.getInputByName(a.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var s;i||this.clear();const r={};for(const n of e.blocks){const a=Ds(n.customType);if(a){const l=new a;l._deserialize(n,this.getScene(),t),r[n.id]=l,this.attachedBlocks.push(l)}}for(const n of this.attachedBlocks)if(n.isTeleportOut){const a=n,l=a._tempEntryPointUniqueId;l&&r[l].attachToEndpoint(a)}for(let n=0;nnew ys(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=Xe.Parse(()=>new ys(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 a=n??new ys(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s),r||a.build(),a}static ParseFromSnippetAsync(e,t=ht.LastCreatedScene,i="",s,r=!1,n=!1){return e==="_BLANK"?Promise.resolve(ys.CreateDefault("blank",t)):new Promise((a,l)=>{const h=new Hs;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=Xe.Parse(()=>new ys(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(()=>{a(s)}).catch(d=>{l(d)}):a(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 ys(e,t);return i.setToDefault(),i.build(),i}}ys._BuildIdGenerator=0;ys.EditorURL=`${fe._DefaultCdnUrl}/v${re.Version}/nodeEditor/babylon.nodeEditor.js`;ys.SnippetUrl="https://snippet.babylonjs.com";ys.IgnoreTexturesAtLoadTime=!1;A([D()],ys.prototype,"ignoreAlpha",void 0);A([D()],ys.prototype,"maxSimultaneousLights",void 0);A([D("mode")],ys.prototype,"_mode",void 0);A([D("comment")],ys.prototype,"comment",void 0);A([D()],ys.prototype,"forceAlphaBlending",void 0);j("BABYLON.NodeMaterial",ys);function vx(o){const e=o.sideOrientation||Oe.DEFAULTSIDE,t=o.radius||1,i=o.flat===void 0?!0:o.flat,s=(o.subdivisions||4)|0,r=o.radiusX||t,n=o.radiusY||t,a=o.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,p=239/1024,_=60/1024,g=26/1024,v=-40/1024,E=20/1024,C=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],b=[],R=[],I=[];let N=0;const O=new Array(3),L=new Array(3);let B;for(B=0;B<3;B++)O[B]=T.Zero(),L[B]=Re.Zero();for(let Z=0;Z<20;Z++){for(B=0;B<3;B++){const oe=c[3*Z+B];O[B].copyFromFloats(h[3*u[oe]],h[3*u[oe]+1],h[3*u[oe]+2]),O[B].normalize(),L[B].copyFromFloats(d[2*oe]*f+_+C[Z]*v,d[2*oe+1]*p+g+C[Z]*E)}const ue=(oe,me,le,ae)=>{const ce=T.Lerp(O[0],O[2],me/s),ie=T.Lerp(O[1],O[2],me/s),w=s===me?O[2]:T.Lerp(ce,ie,oe/(s-me));w.normalize();let H;if(i){const _e=T.Lerp(O[0],O[2],ae/s),q=T.Lerp(O[1],O[2],ae/s);H=T.Lerp(_e,q,le/(s-ae))}else H=new T(w.x,w.y,w.z);H.x/=r,H.y/=n,H.z/=a,H.normalize();const X=Re.Lerp(L[0],L[2],me/s),te=Re.Lerp(L[1],L[2],me/s),Q=s===me?L[2]:Re.Lerp(X,te,oe/(s-me));b.push(w.x*r,w.y*n,w.z*a),R.push(H.x,H.y,H.z),I.push(Q.x,pi.UseOpenGLOrientationForUV?1-Q.y:Q.y),S.push(N),N++};for(let oe=0;oexx(o,e,t);var ql;(function(o){o.WRIST="wrist",o.THUMB="thumb",o.INDEX="index",o.MIDDLE="middle",o.RING="ring",o.LITTLE="little"})(ql||(ql={}));var yt;(function(o){o.WRIST="wrist",o.THUMB_METACARPAL="thumb-metacarpal",o.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",o.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",o.THUMB_TIP="thumb-tip",o.INDEX_FINGER_METACARPAL="index-finger-metacarpal",o.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",o.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",o.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",o.INDEX_FINGER_TIP="index-finger-tip",o.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",o.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",o.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",o.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",o.MIDDLE_FINGER_TIP="middle-finger-tip",o.RING_FINGER_METACARPAL="ring-finger-metacarpal",o.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",o.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",o.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",o.RING_FINGER_TIP="ring-finger-tip",o.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",o.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",o.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",o.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",o.PINKY_FINGER_TIP="pinky-finger-tip"})(yt||(yt={}));const mo=[yt.WRIST,yt.THUMB_METACARPAL,yt.THUMB_PHALANX_PROXIMAL,yt.THUMB_PHALANX_DISTAL,yt.THUMB_TIP,yt.INDEX_FINGER_METACARPAL,yt.INDEX_FINGER_PHALANX_PROXIMAL,yt.INDEX_FINGER_PHALANX_INTERMEDIATE,yt.INDEX_FINGER_PHALANX_DISTAL,yt.INDEX_FINGER_TIP,yt.MIDDLE_FINGER_METACARPAL,yt.MIDDLE_FINGER_PHALANX_PROXIMAL,yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE,yt.MIDDLE_FINGER_PHALANX_DISTAL,yt.MIDDLE_FINGER_TIP,yt.RING_FINGER_METACARPAL,yt.RING_FINGER_PHALANX_PROXIMAL,yt.RING_FINGER_PHALANX_INTERMEDIATE,yt.RING_FINGER_PHALANX_DISTAL,yt.RING_FINGER_TIP,yt.PINKY_FINGER_METACARPAL,yt.PINKY_FINGER_PHALANX_PROXIMAL,yt.PINKY_FINGER_PHALANX_INTERMEDIATE,yt.PINKY_FINGER_PHALANX_DISTAL,yt.PINKY_FINGER_TIP],TF={[ql.WRIST]:[yt.WRIST],[ql.THUMB]:[yt.THUMB_METACARPAL,yt.THUMB_PHALANX_PROXIMAL,yt.THUMB_PHALANX_DISTAL,yt.THUMB_TIP],[ql.INDEX]:[yt.INDEX_FINGER_METACARPAL,yt.INDEX_FINGER_PHALANX_PROXIMAL,yt.INDEX_FINGER_PHALANX_INTERMEDIATE,yt.INDEX_FINGER_PHALANX_DISTAL,yt.INDEX_FINGER_TIP],[ql.MIDDLE]:[yt.MIDDLE_FINGER_METACARPAL,yt.MIDDLE_FINGER_PHALANX_PROXIMAL,yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE,yt.MIDDLE_FINGER_PHALANX_DISTAL,yt.MIDDLE_FINGER_TIP],[ql.RING]:[yt.RING_FINGER_METACARPAL,yt.RING_FINGER_PHALANX_PROXIMAL,yt.RING_FINGER_PHALANX_INTERMEDIATE,yt.RING_FINGER_PHALANX_DISTAL,yt.RING_FINGER_TIP],[ql.LITTLE]:[yt.PINKY_FINGER_METACARPAL,yt.PINKY_FINGER_PHALANX_PROXIMAL,yt.PINKY_FINGER_PHALANX_INTERMEDIATE,yt.PINKY_FINGER_PHALANX_DISTAL,yt.PINKY_FINGER_TIP]};class EF{get handMesh(){return this._handMesh}getHandPartMeshes(e){return TF[e].map(t=>this._jointMeshes[mo.indexOf(t)])}getJointMesh(e){return this._jointMeshes[mo.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=new Array(mo.length),this._jointTransformMatrices=new Float32Array(mo.length*16),this._tempJointMatrix=new k,this._jointRadii=new Float32Array(mo.length),this._scene=t[0].getScene();for(let l=0;l{l.rootMesh&&l.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(l=>{l.onModelLoadedObservable.add(h=>{h.rootMesh&&h.rootMesh.setEnabled(!1)}),l.rootMesh&&l.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(i=>i.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){const i=this._handMesh.skeleton;mo.forEach((s,r)=>{const n=i.getBoneIndexByName(t?t[s]:s);n!==-1&&i.bones[n].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=mo.map(a=>s[a]||i.get(a));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 a=0;a{const h=this._jointTransforms[l];k.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(){this._handMesh&&(this._handMesh.isVisible=!1)}}class Gi extends Cr{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var s,r,n,a,l;const h=[],c=((s=e.jointMeshes)===null||s===void 0?void 0:s.sourceMesh)||xx("jointParent",Gi._ICOSPHERE_PARAMS);c.isVisible=!!(!((r=e.jointMeshes)===null||r===void 0)&&r.keepOriginalVisible);for(let u=0;u{var s,r,n,a,l;const h={};!((r=(s=Gi._RightHandGLB)===null||s===void 0?void 0:s.meshes[1])===null||r===void 0)&&r.isDisposed()&&(Gi._RightHandGLB=null),!((a=(n=Gi._LeftHandGLB)===null||n===void 0?void 0:n.meshes[1])===null||a===void 0)&&a.isDisposed()&&(Gi._LeftHandGLB=null);const c=!!(Gi._RightHandGLB&&Gi._LeftHandGLB),u=await Promise.all([Gi._RightHandGLB||Lt.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Gi._LeftHandGLB||Lt.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Gi._RightHandGLB=u[0],Gi._LeftHandGLB=u[1];const d=new ys("handShader",e,{emitComments:!1});await d.loadAsync(Gi.DEFAULT_HAND_MODEL_SHADER_URL),d.needDepthPrePass=!0,d.transparencyMode=Ie.MATERIAL_ALPHABLEND,d.alphaMode=2,d.build(!1);const f=Object.assign({base:Te.FromInts(116,63,203),fresnel:Te.FromInts(149,102,229),fingerColor:Te.FromInts(177,130,255),tipFresnel:Te.FromInts(220,200,255)},(l=t==null?void 0:t.handMeshes)===null||l===void 0?void 0:l.customColors),p={base:d.getBlockByName("baseColor"),fresnel:d.getBlockByName("fresnelColor"),fingerColor:d.getBlockByName("fingerColor"),tipFresnel:d.getBlockByName("tipFresnelColor")};p.base.value=f.base,p.fresnel.value=f.fresnel,p.fingerColor.value=f.fingerColor,p.tipFresnel.value=f.tipFresnel,["left","right"].forEach(_=>{const g=_=="left"?Gi._LeftHandGLB:Gi._RightHandGLB;if(!g)throw new Error("Could not load hand model");const v=g.meshes[1];v._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,v.material=d.clone(`${_}HandShaderClone`,!0),v.isVisible=!1,h[_]=v,!c&&!e.useRightHandedSystem&&g.meshes[1].rotate(an.Y,Math.PI)}),d.dispose(),i({left:h.left,right:h.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[yt.WRIST]:`wrist_${t}`,[yt.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[yt.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[yt.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[yt.THUMB_TIP]:`thumb_tip_${t}`,[yt.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[yt.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[yt.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[yt.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[yt.INDEX_FINGER_TIP]:`index_tip_${t}`,[yt.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[yt.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[yt.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[yt.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[yt.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[yt.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[yt.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[yt.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[yt.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[yt.RING_FINGER_TIP]:`ring_tip_${t}`,[yt.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[yt.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[yt.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[yt.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[yt.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.onHandAddedObservable=new he,this.onHandRemovedObservable=new he,this._attachHand=r=>{var n,a,l;if(!r.inputSource.hand||r.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const h=r.inputSource.handedness,c=new EF(r,this._handResources.jointMeshes[h],this._handResources.handMeshes&&this._handResources.handMeshes[h],this._handResources.rigMappings&&this._handResources.rigMappings[h],(n=this.options.handMeshes)===null||n===void 0?void 0:n.meshesUseLeftHandedCoordinates,(a=this.options.jointMeshes)===null||a===void 0?void 0:a.invisible,(l=this.options.jointMeshes)===null||l===void 0?void 0:l.scaleFactor);this._attachedHands[r.uniqueId]=c,this._trackingHands[h]=c,this.onHandAddedObservable.notifyObservers(c)},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(a=>{const l=a[0],h=a[1];l.forEach((c,u)=>{h[mo[u]]=c})}),t.handMeshes.customRigMappings={left:r,right:n}}}attach(){var e,t,i,s;return super.attach()?(this._handResources={jointMeshes:Gi._GenerateTrackedJointMeshes(this.options),handMeshes:((e=this.options.handMeshes)===null||e===void 0?void 0:e.customMeshes)||null,rigMappings:((t=this.options.handMeshes)===null||t===void 0?void 0:t.customRigMappings)||null},!(!((i=this.options.handMeshes)===null||i===void 0)&&i.customMeshes)&&!(!((s=this.options.handMeshes)===null||s===void 0)&&s.disableDefaultMeshes)&&Gi._GenerateDefaultHandMeshesAsync(ht.LastCreatedScene,this.options).then(r=>{var n,a;this._handResources.handMeshes=r,this._handResources.rigMappings={left:Gi._GenerateDefaultHandMeshRigMapping("left"),right:Gi._GenerateDefaultHandMeshRigMapping("right")},(n=this._trackingHands.left)===null||n===void 0||n.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),(a=this._trackingHands.right)===null||a===void 0||a.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),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===void 0||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),(i=this._trackingHands.right)===null||i===void 0||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const s=i.xrController.inputSource.handedness=="left"?"left":"right";((t=this._trackingHands[s])===null||t===void 0?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return super.detach()?(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0):!1}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(!((e=this.options.handMeshes)===null||e===void 0)&&e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Gi._RightHandGLB=null,Gi._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}Gi.Name=oi.HAND_TRACKING;Gi.Version=1;Gi.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";Gi.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";Gi._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};Gi._RightHandGLB=null;Gi._LeftHandGLB=null;_s.AddWebXRFeature(Gi.Name,(o,e)=>()=>new Gi(o,e),Gi.Version,!1);var o0;(function(o){o[o.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",o[o.RADIAL_SIDE=1]="RADIAL_SIDE",o[o.ULNAR_SIDE=2]="ULNAR_SIDE",o[o.BELOW_WRIST=3]="BELOW_WRIST"})(o0||(o0={}));var l0;(function(o){o[o.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",o[o.HAND_ROTATION=1]="HAND_ROTATION"})(l0||(l0={}));var h0;(function(o){o[o.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",o[o.PALM_UP=1]="PALM_UP",o[o.GAZE_FOCUS=2]="GAZE_FOCUS",o[o.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(h0||(h0={}));T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero();Se.Identity();k.Identity(),k.Identity();js.BuildArray(10,T.Zero);Se.Identity();js.BuildArray(5,k.Identity);class Id{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=k.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 he,this.bones=[],this._scene=i||ht.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){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),this._transformMatrices)}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let 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-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){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,K.Matrix[1]),r._updateAbsoluteBindMatrices(K.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=Ws.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=Ws.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{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 e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=s.animations[0].serialize()),t.ranges=[];for(const a in this._ranges){const l=this._ranges[a];if(!l)continue;const h={};h.name=a,h.from=l.from,h.to=l.to,t.ranges.push(h)}}return t}static Parse(e,t){const i=new Id(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=T.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let s;for(s=0;s-1&&(a=i.bones[r.parentBoneIndex]);const l=r.rest?k.FromArray(r.rest):null,h=new rs(r.name,i,a,k.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(Ee.Parse(r.animation)),r.linkedTransformNodeId!==void 0&&r.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,h._waitingTransformNodeId=r.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class SF{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 Ku=(()=>{const o=new Uint8Array(4),e=new Uint32Array(o.buffer);return!!((e[0]=1)&o[0])})();Object.defineProperty(P.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});P.prototype._rebuild=function(){var o,e;(o=this._buffer)===null||o===void 0||o._rebuild(),(e=this._alignedBuffer)===null||e===void 0||e._rebuild()};P.prototype.dispose=function(){var o;this._ownsBuffer&&this._buffer.dispose(),(o=this._alignedBuffer)===null||o===void 0||o.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};P.prototype._alignBuffer=function(){var o,e;const t=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4===0||!t)return;const i=P.GetTypeByteLength(this.type),s=this.byteStride+3&-4,r=s/i,n=this.totalVertices,l=n*s/i;let h;if(Array.isArray(t)){const f=new Float32Array(t);h=new DataView(f.buffer,f.byteOffset,f.byteLength)}else t instanceof ArrayBuffer?h=new DataView(t,0,t.byteLength):h=new DataView(t.buffer,t.byteOffset,t.byteLength);let c;this.type===P.BYTE?c=new Int8Array(l):this.type===P.UNSIGNED_BYTE?c=new Uint8Array(l):this.type===P.SHORT?c=new Int16Array(l):this.type===P.UNSIGNED_SHORT?c=new Uint16Array(l):this.type===P.INT?c=new Int32Array(l):this.type===P.UNSIGNED_INT?c=new Uint32Array(l):c=new Float32Array(l);const u=this.getSize();let d=this.byteOffset;for(let f=0;f{if(t.type!==rt.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===fu.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,rt.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"}}A([D()],om.prototype,"wheelPrecisionX",void 0);A([D()],om.prototype,"wheelPrecisionY",void 0);A([D()],om.prototype,"wheelPrecisionZ",void 0);class Tx{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=fe.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=a=>{var l,h;const c=a.event,u=c.pointerType==="touch";if(a.type!==rt.POINTERMOVE&&this.buttons.indexOf(c.button)===-1)return;const d=c.target;if(this._altKey=c.altKey,this._ctrlKey=c.ctrlKey,this._metaKey=c.metaKey,this._shiftKey=c.shiftKey,this._buttonsPressed=c.buttons,t.isPointerLock){const f=c.movementX,p=c.movementY;this.onTouch(null,f,p),this._pointA=null,this._pointB=null}else{if(a.type!==rt.POINTERDOWN&&u&&((l=this._pointA)===null||l===void 0?void 0:l.pointerId)!==c.pointerId&&((h=this._pointB)===null||h===void 0?void 0:h.pointerId)!==c.pointerId)return;if(a.type===rt.POINTERDOWN&&(this._currentActiveButton===-1||u)){try{d==null||d.setPointerCapture(c.pointerId)}catch{}if(this._pointA===null)this._pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else if(this._pointB===null)this._pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else return;this._currentActiveButton===-1&&!u&&(this._currentActiveButton=c.button),this.onButtonDown(c),e||(c.preventDefault(),i&&i.focus())}else if(a.type===rt.POINTERDOUBLETAP)this.onDoubleTap(c.pointerType);else if(a.type===rt.POINTERUP&&(this._currentActiveButton===c.button||u)){try{d==null||d.releasePointerCapture(c.pointerId)}catch{}u||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==c.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==c.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(c),e||c.preventDefault()}else if(a.type===rt.POINTERMOVE){if(e||c.preventDefault(),this._pointA&&this._pointB===null){const f=c.clientX-this._pointA.x,p=c.clientY-this._pointA.y;this.onTouch(this._pointA,f,p),this._pointA.x=c.clientX,this._pointA.y=c.clientY}else if(this._pointA&&this._pointB){const f=this._pointA.pointerId===c.pointerId?this._pointA:this._pointB;f.x=c.clientX,f.y=c.clientY;const p=this._pointA.x-this._pointB.x,_=this._pointA.y-this._pointB.y,g=p*p+_*_,v={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:c.pointerId,type:a.type};this.onMultiTouch(this._pointA,this._pointB,s,g,r,v),r=v,s=g}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,rt.POINTERDOWN|rt.POINTERUP|rt.POINTERMOVE|rt.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=a=>this.onContextMenu(a),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&fe.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&fe.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(){}}A([D()],Tx.prototype,"buttons",void 0);var qr={};class lm{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){G.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=et.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=Xe.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=qr[i];if(s){const r=t[i],n=Xe.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=qr[this.attached[i].getClassName()];if(s){const r=Xe.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class xr{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=xr.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}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(){}}xr.GAMEPAD=0;xr.GENERIC=1;xr.XBOX=2;xr.POSE_ENABLED=3;xr.DUALSHOCK=4;class CF extends xr{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new he,this.onButtonUpObservable=new he,this.type=xr.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{t.type!==xr.POSE_ENABLED&&(!this.gamepad||t.type===xr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(xr.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(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"}}A([D()],hm.prototype,"gamepadRotationSensibility",void 0);A([D()],hm.prototype,"gamepadMoveSensibility",void 0);qr.ArcRotateCameraGamepadInput=hm;class Ro{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=fe.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===dh.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?i=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==rt.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===fu.DOM_DELTA_LINE?bF: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 a=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)a-=l,l*=this.camera.inertia;a=ye.Clamp(a,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,a)}}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,rt.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=Rn.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),s=i.createPickingRay(i.pointerX,i.pointerY,k.Identity(),t,!1);(t.targetScreenOffset.x!==0||t.targetScreenOffset.y!==0)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=T.TransformNormal(this._viewOffset,t._cameraTransformMatrix),s.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(e=s.intersectsPlane(this._hitPlane))!==null&&e!==void 0?e:0),s.origin.addInPlace(s.direction.scaleInPlace(r))}_zoomToMouse(e){var t,i;const s=this.camera,r=1-s.inertia;if(s.lowerRadiusLimit){const c=(t=s.lowerRadiusLimit)!==null&&t!==void 0?t:0;s.radius-(s.inertialRadiusOffset+e)/rc&&(e=(s.radius-c)*r-s.inertialRadiusOffset)}const a=e/r/s.radius,l=this._getPosition(),h=K.Vector3[6];l.subtractToRef(s.target,h),h.scaleInPlace(a),h.scaleInPlace(r),this._inertialPanning.addInPlace(h),s.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<$t&&(e.x=0),Math.abs(e.y)<$t&&(e.y=0),Math.abs(e.z)<$t&&(e.z=0)}}A([D()],sp.prototype,"wheelPrecision",void 0);A([D()],sp.prototype,"zoomToMouseLocation",void 0);A([D()],sp.prototype,"wheelDeltaPercentage",void 0);qr.ArcRotateCameraMouseWheelInput=sp;class Hn extends Tx{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||Hn.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}}Hn.MinimumRadiusForPinch=.001;A([D()],Hn.prototype,"buttons",void 0);A([D()],Hn.prototype,"angularSensibilityX",void 0);A([D()],Hn.prototype,"angularSensibilityY",void 0);A([D()],Hn.prototype,"pinchPrecision",void 0);A([D()],Hn.prototype,"pinchDeltaPercentage",void 0);A([D()],Hn.prototype,"useNaturalPinchZoom",void 0);A([D()],Hn.prototype,"pinchZoom",void 0);A([D()],Hn.prototype,"panningSensibility",void 0);A([D()],Hn.prototype,"multiTouchPanning",void 0);A([D()],Hn.prototype,"multiTouchPanAndZoom",void 0);qr.ArcRotateCameraPointersInput=Hn;class Ex extends lm{constructor(e){super(e)}addMouseWheel(){return this.add(new sp),this}addPointers(){return this.add(new Hn),this}addKeyboard(){return this.add(new Ro),this}}Ex.prototype.addVRDeviceOrientation=function(){return this.add(new wb),this};class wb{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=fe.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):fe.Warn("Permission not granted.")}).catch(i=>{fe.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"}}qr.ArcRotateCameraVRDeviceOrientationInput=wb;class Th{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=fe.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===dh.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._pointerInput(t)},rt.POINTERDOWN|rt.POINTERUP|rt.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!==rt.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const r=t.target;if(e.type===rt.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===rt.POINTERUP){try{r==null||r.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===rt.POINTERMOVE){if(!this._previousPosition){s.isPointerLock&&this._onMouseMove(e.event);return}const n=t.clientX-this._previousPosition.x,a=t.clientY-this._previousPosition.y;this._rotateCamera(n,a),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,a=Se.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(h=>h===this.activeButton)&&(l=Se.RotationAxis(an.X,n),a.multiplyInPlace(l)),this.buttonsYaw.some(h=>h===this.activeButton)){l=Se.RotationAxis(an.Y,r),a.multiplyInPlace(l);const h=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-hh===this.activeButton)&&(l=Se.RotationAxis(an.Z,-r),i._trackRoll-=r,a.multiplyInPlace(l)),a.toEulerAnglesToRef(i.rotation)}}A([D()],cm.prototype,"buttons",void 0);A([D()],cm.prototype,"angularSensibility",void 0);qr.FlyCameraMouseInput=cm;class Gr{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=fe.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===dh.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}}A([D()],Gr.prototype,"keysHeightOffsetIncr",void 0);A([D()],Gr.prototype,"keysHeightOffsetDecr",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierAlt",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierCtrl",void 0);A([D()],Gr.prototype,"keysHeightOffsetModifierShift",void 0);A([D()],Gr.prototype,"keysRotationOffsetIncr",void 0);A([D()],Gr.prototype,"keysRotationOffsetDecr",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierAlt",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierCtrl",void 0);A([D()],Gr.prototype,"keysRotationOffsetModifierShift",void 0);A([D()],Gr.prototype,"keysRadiusIncr",void 0);A([D()],Gr.prototype,"keysRadiusDecr",void 0);A([D()],Gr.prototype,"keysRadiusModifierAlt",void 0);A([D()],Gr.prototype,"keysRadiusModifierCtrl",void 0);A([D()],Gr.prototype,"keysRadiusModifierShift",void 0);A([D()],Gr.prototype,"heightSensibility",void 0);A([D()],Gr.prototype,"rotationSensibility",void 0);A([D()],Gr.prototype,"radiusSensibility",void 0);qr.FollowCameraKeyboardMoveInput=Gr;class tc{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=fe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==rt.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&&G.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,rt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}A([D()],tc.prototype,"axisControlRadius",void 0);A([D()],tc.prototype,"axisControlHeight",void 0);A([D()],tc.prototype,"axisControlRotation",void 0);A([D()],tc.prototype,"wheelPrecision",void 0);A([D()],tc.prototype,"wheelDeltaPercentage",void 0);qr.FollowCameraMouseWheelInput=tc;class Xn extends Tx{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 a=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_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&&G.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&G.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&G.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}A([D()],Xn.prototype,"angularSensibilityX",void 0);A([D()],Xn.prototype,"angularSensibilityY",void 0);A([D()],Xn.prototype,"pinchPrecision",void 0);A([D()],Xn.prototype,"pinchDeltaPercentage",void 0);A([D()],Xn.prototype,"axisXControlRadius",void 0);A([D()],Xn.prototype,"axisXControlHeight",void 0);A([D()],Xn.prototype,"axisXControlRotation",void 0);A([D()],Xn.prototype,"axisYControlRadius",void 0);A([D()],Xn.prototype,"axisYControlHeight",void 0);A([D()],Xn.prototype,"axisYControlRotation",void 0);A([D()],Xn.prototype,"axisPinchControlRadius",void 0);A([D()],Xn.prototype,"axisPinchControlHeight",void 0);A([D()],Xn.prototype,"axisPinchControlRotation",void 0);qr.FollowCameraPointersInput=Xn;class La{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=fe.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===dh.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{const r=s.event,n=r.pointerType==="touch";if(!this.touchEnabled&&n||s.type!==rt.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const a=r.target;if(s.type===rt.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{a==null||a.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===rt.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{a==null||a.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===rt.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 a=s.movementY;this.camera.cameraRotation.x+=a/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,rt.POINTERDOWN|rt.POINTERUP|rt.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"}}A([D()],um.prototype,"buttons",void 0);A([D()],um.prototype,"angularSensibility",void 0);qr.FreeCameraMouseInput=um;var Zi;(function(o){o[o.MoveRelative=0]="MoveRelative",o[o.RotateRelative=1]="RotateRelative",o[o.MoveScene=2]="MoveScene"})(Zi||(Zi={}));class Io extends om{constructor(){super(...arguments),this._moveRelative=T.Zero(),this._rotateRelative=T.Zero(),this._moveScene=T.Zero(),this._wheelXAction=Zi.MoveRelative,this._wheelXActionCoordinate=Fh.X,this._wheelYAction=Zi.MoveRelative,this._wheelYActionCoordinate=Fh.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Zi.MoveRelative||(this._wheelXAction=Zi.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Zi.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Zi.MoveRelative||(this._wheelYAction=Zi.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Zi.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Zi.MoveRelative||(this._wheelZAction=Zi.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Zi.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Zi.RotateRelative||(this._wheelXAction=Zi.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Zi.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Zi.RotateRelative||(this._wheelYAction=Zi.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Zi.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Zi.RotateRelative||(this._wheelZAction=Zi.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Zi.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Zi.MoveScene||(this._wheelXAction=Zi.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Zi.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Zi.MoveScene||(this._wheelYAction=Zi.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Zi.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Zi.MoveScene||(this._wheelZAction=Zi.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Zi.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=k.Zero();this.camera.getViewMatrix().invertToRef(e);const t=T.Zero();T.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 Zi.MoveRelative:s=this._moveRelative;break;case Zi.RotateRelative:s=this._rotateRelative;break;case Zi.MoveScene:s=this._moveScene;break}switch(i){case Fh.X:s.set(e,0,0);break;case Fh.Y:s.set(0,e,0);break;case Fh.Z:s.set(0,0,e);break}}}A([D()],Io.prototype,"wheelXMoveRelative",null);A([D()],Io.prototype,"wheelYMoveRelative",null);A([D()],Io.prototype,"wheelZMoveRelative",null);A([D()],Io.prototype,"wheelXRotateRelative",null);A([D()],Io.prototype,"wheelYRotateRelative",null);A([D()],Io.prototype,"wheelZRotateRelative",null);A([D()],Io.prototype,"wheelXMoveScene",null);A([D()],Io.prototype,"wheelYMoveScene",null);A([D()],Io.prototype,"wheelZMoveScene",null);qr.FreeCameraMouseWheelInput=Io;class dm{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=fe.IsSafari()}attachControl(e){e=fe.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===rt.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===rt.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===rt.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,rt.POINTERDOWN|rt.POINTERUP|rt.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 T(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);k.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(T.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}A([D()],dm.prototype,"touchAngularSensibility",void 0);A([D()],dm.prototype,"touchMoveSensibility",void 0);qr.FreeCameraTouchInput=dm;class fm extends lm{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new La),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new um(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Io,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new dm),this}clear(){super.clear(),this._mouseInput=null}}fm.prototype.addDeviceOrientation=function(o){return this._deviceOrientationInput||(this._deviceOrientationInput=new Fb,o&&(this._deviceOrientationInput.smoothFactor=o),this.add(this._deviceOrientationInput)),this};class Fb{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):fe.Warn("Permission not granted.")}).catch(n=>{fe.Error(n)}):window.addEventListener("deviceorientation",r)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new Se,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new he,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-fe.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?fe.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?fe.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?fe.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 Se(-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 Se),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():fe.Warn("Permission not granted.")}).catch(i=>{fe.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(Se.RotationYawPitchRollToRef(fe.ToRadians(this._alpha),fe.ToRadians(this._beta),-fe.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"}}qr.FreeCameraDeviceOrientationInput=Fb;class pm{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=k.Identity(),this._deltaTransform=T.Zero(),this._vector3=T.Zero(),this._vector2=Re.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!==xr.POSE_ENABLED&&(!this.gamepad||t.type===xr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(xr.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):k.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),T.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"}}A([D()],pm.prototype,"gamepadAngularSensibility",void 0);A([D()],pm.prototype,"gamepadMoveSensibility",void 0);qr.FreeCameraGamepadInput=pm;var fr;(function(o){o[o.X=0]="X",o[o.Y=1]="Y",o[o.Z=2]="Z"})(fr||(fr={}));class dt{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=Object.assign(Object.assign({},dt._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,dt._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=fr.X,this._axisTargetedByUpAndDown=fr.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Ov,this.deltaPosition=T.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{dt._VJCanvasWidth=window.innerWidth,dt._VJCanvasHeight=window.innerHeight,dt.Canvas&&(dt.Canvas.width=dt._VJCanvasWidth,dt.Canvas.height=dt._VJCanvasHeight),dt._HalfWidth=dt._VJCanvasWidth/2},!dt.Canvas){window.addEventListener("resize",this._onResize,!1),dt.Canvas=document.createElement("canvas"),dt._VJCanvasWidth=window.innerWidth,dt._VJCanvasHeight=window.innerHeight,dt.Canvas.width=window.innerWidth,dt.Canvas.height=window.innerHeight,dt.Canvas.style.width="100%",dt.Canvas.style.height="100%",dt.Canvas.style.position="absolute",dt.Canvas.style.backgroundColor="transparent",dt.Canvas.style.top="0px",dt.Canvas.style.left="0px",dt.Canvas.style.zIndex="5",dt.Canvas.style.touchAction="none",dt.Canvas.setAttribute("touch-action","none");const s=dt.Canvas.getContext("2d");if(!s)throw new Error("Unable to create canvas for virtual joystick");dt._VJCanvasContext=s,dt._VJCanvasContext.strokeStyle="#ffffff",dt._VJCanvasContext.lineWidth=2,document.body.appendChild(dt.Canvas)}dt._HalfWidth=dt.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&&dt._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Re(0,0),this._joystickPreviousPointerPos=new Re(0,0),this._joystickPointerStartPos=new Re(0,0),this._deltaJoystickVector=new Re(0,0),this._onPointerDownHandlerRef=s=>{this._onPointerDown(s)},this._onPointerMoveHandlerRef=s=>{this._onPointerMove(s)},this._onPointerUpHandlerRef=s=>{this._onPointerUp(s)},dt.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),dt.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),dt.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),dt.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),dt.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.clientXdt._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)):dt._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 Re(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),a=n.length();a>this.containerSize&&n.scaleInPlace(this.containerSize/a),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),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?dt._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.lineWidth=2,dt._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath(),dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.lineWidth=6,dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?dt._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle=this._joystickColor,dt._VJCanvasContext.lineWidth=2,dt._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._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()):(dt._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.fillStyle="white",dt._VJCanvasContext.beginPath(),dt._VJCanvasContext.strokeStyle="red",dt._VJCanvasContext.lineWidth=6,dt._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),dt._VJCanvasContext.stroke(),dt._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){dt.Canvas&&(dt.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),dt.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),dt.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),dt.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(dt.Canvas),dt.Canvas=null),this._released=!0}}dt._GlobalJoystickIndex=0;dt._AlwaysVisibleSticks=0;fm.prototype.addVirtualJoystick=function(){return this.add(new Lb),this};class Lb{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=k.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=T.TransformCoordinates(new T(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 dt(!0),this._leftjoystick.setAxisForUpDown(fr.Z),this._leftjoystick.setAxisForLeftRight(fr.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new dt(!1),this._rightjoystick.setAxisForUpDown(fr.X),this._rightjoystick.setAxisForLeftRight(fr.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"}}qr.FreeCameraVirtualJoystickInput=Lb;class Us extends et{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=T.Zero(),this._tmpTargetVector=T.Zero(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new Re(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new Se,this.rotation=new T(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=T.Zero(),this._initialFocalDistance=1,this._viewMatrix=k.Zero(),this._camMatrix=k.Zero(),this._cameraTransformMatrix=k.Zero(),this._cameraRotationMatrix=k.Zero(),this._referencePoint=new T(0,0,1),this._transformedReferencePoint=T.Zero(),this._deferredPositionUpdate=new T,this._deferredRotationQuaternionUpdate=new Se,this._deferredRotationUpdate=new T,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=T.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 T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Se(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+=$t),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),k.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&&Se.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(K.Matrix[0]),T.TransformNormalToRef(this.cameraDirection,K.Matrix[0],K.Vector3[0]),this._deferredPositionUpdate.addInPlace(K.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()&&(Se.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._newPosition.copyFrom(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>re.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&a&&this.onCollide(a))},this.inputs=new fm(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=fe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new Re(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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=T.Zero(),this._transformedDirection=T.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"}}A([kr()],zn.prototype,"ellipsoid",void 0);A([kr()],zn.prototype,"ellipsoidOffset",void 0);A([D()],zn.prototype,"checkCollisions",void 0);A([D()],zn.prototype,"applyGravity",void 0);Mi.AddNodeConstructor("TouchCamera",(o,e)=>()=>new Bb(o,T.Zero(),e));class Bb extends zn{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Mi.AddNodeConstructor("ArcRotateCamera",(o,e)=>()=>new Ji(o,0,0,1,T.Zero(),e));class Ji extends Us{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 k,this._upToYMatrix=new k,this._upVector=T.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){k.RotationAlignToRef(T.UpReadOnly,this._upVector,this._yToUpMatrix),k.RotationAlignToRef(this._upVector,T.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 zh,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 Un,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 cF,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,a=!0){super(e,T.Zero(),n,a),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=T.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Re.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new k,this.panningAxis=new T(1,1,0),this._transformedDirection=new T,this.mapPanning=!1,this.onMeshTargetChangedObservable=new he,this.checkCollisions=!1,this.collisionRadius=new T(.5,.5,.5),this._previousPosition=T.Zero(),this._collisionVelocity=T.Zero(),this._newPosition=T.Zero(),this._computationVector=T.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 p=Math.sin(this.beta);p===0&&(p=1e-4);const _=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*p,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,_,g),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=T.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Ex(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new T(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=Re.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=fe.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)<$t&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<$t&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&T.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){var r;if(s=(r=this.overrideCloneAlphaBetaRadius)!==null&&r!==void 0?r:s,e.getBoundingInfo)t?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 n=e,a=this._getTargetPosition();if(a&&!i&&a.equals(n))return;this._targetHost=null,this._target=n,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)&&T.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=se.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=se.MinMax(r),s=T.Distance(i.min,i.max)}else{const r=e;i=r,s=r.distance}this._target=se.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case et.RIG_MODE_STEREOSCOPIC_INTERLACED:case et.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new Ji(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 et.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case et.RIG_MODE_STEREOSCOPIC_OVERUNDER:case et.RIG_MODE_STEREOSCOPIC_INTERLACED:case et.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case et.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=T.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),a=Math.tan(this.fov/2),l=a*n,c=s*.5*i,u=c*Math.sqrt(1+1/(l*l)),d=c*Math.sqrt(1+1/(a*a));return Math.max(u,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}A([D()],Ji.prototype,"alpha",void 0);A([D()],Ji.prototype,"beta",void 0);A([D()],Ji.prototype,"radius",void 0);A([D()],Ji.prototype,"overrideCloneAlphaBetaRadius",void 0);A([kr("target")],Ji.prototype,"_target",void 0);A([Qf("targetHost")],Ji.prototype,"_targetHost",void 0);A([D()],Ji.prototype,"inertialAlphaOffset",void 0);A([D()],Ji.prototype,"inertialBetaOffset",void 0);A([D()],Ji.prototype,"inertialRadiusOffset",void 0);A([D()],Ji.prototype,"lowerAlphaLimit",void 0);A([D()],Ji.prototype,"upperAlphaLimit",void 0);A([D()],Ji.prototype,"lowerBetaLimit",void 0);A([D()],Ji.prototype,"upperBetaLimit",void 0);A([D()],Ji.prototype,"lowerRadiusLimit",void 0);A([D()],Ji.prototype,"upperRadiusLimit",void 0);A([D()],Ji.prototype,"inertialPanningX",void 0);A([D()],Ji.prototype,"inertialPanningY",void 0);A([D()],Ji.prototype,"pinchToPanMaxDistance",void 0);A([D()],Ji.prototype,"panningDistanceLimit",void 0);A([kr()],Ji.prototype,"panningOriginTarget",void 0);A([D()],Ji.prototype,"panningInertia",void 0);A([D()],Ji.prototype,"zoomToMouseLocation",null);A([D()],Ji.prototype,"zoomOnFactor",void 0);A([rx()],Ji.prototype,"targetScreenOffset",void 0);A([D()],Ji.prototype,"allowUpsideDown",void 0);A([D()],Ji.prototype,"useInputToRestoreState",void 0);Mi.AddNodeConstructor("DeviceOrientationCamera",(o,e)=>()=>new Sx(o,T.Zero(),e));class Sx extends zn{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new Se,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new Se,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 Se),Se.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=an.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Se),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 yF extends lm{constructor(e){super(e)}addKeyboard(){return this.add(new Th),this}addMouse(){return this.add(new cm),this}}class _m extends Us{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 T(1,1,1),this.ellipsoidOffset=new T(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=T.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=T.Zero(),this._diffPosition=T.Zero(),this._newPosition=T.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,a=null)=>{(h=>{this._newPosition.copyFrom(h),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>re.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&a&&this.onCollide(a))})(n)},this.inputs=new yF(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=fe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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=T.Zero(),this._transformedDirection=T.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"}}A([kr()],_m.prototype,"ellipsoid",void 0);A([kr()],_m.prototype,"ellipsoidOffset",void 0);A([D()],_m.prototype,"checkCollisions",void 0);A([D()],_m.prototype,"applyGravity",void 0);class AF extends lm{constructor(e){super(e)}addKeyboard(){return this.add(new Gr),this}addMouseWheel(){return this.add(new tc),this}addPointers(){return this.add(new Xn),this}addVRDeviceOrientation(){return G.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Mi.AddNodeConstructor("FollowCamera",(o,e)=>()=>new Ba(o,T.Zero(),e));Mi.AddNodeConstructor("ArcFollowCamera",(o,e)=>()=>new RF(o,0,0,1,null,e));class Ba extends Us{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 AF(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=K.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=fe.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,a=r.z+Math.cos(s)*this.radius,l=n-this.position.x,h=r.y+this.heightOffset-this.position.y,c=a-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 T(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(r)}attachControl(e,t){t=fe.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.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),this.lowerHeightOffsetLimit!==null&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),this.lowerRotationOffsetLimit!==null&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}A([D()],Ba.prototype,"radius",void 0);A([D()],Ba.prototype,"lowerRadiusLimit",void 0);A([D()],Ba.prototype,"upperRadiusLimit",void 0);A([D()],Ba.prototype,"rotationOffset",void 0);A([D()],Ba.prototype,"lowerRotationOffsetLimit",void 0);A([D()],Ba.prototype,"upperRotationOffsetLimit",void 0);A([D()],Ba.prototype,"heightOffset",void 0);A([D()],Ba.prototype,"lowerHeightOffsetLimit",void 0);A([D()],Ba.prototype,"upperHeightOffsetLimit",void 0);A([D()],Ba.prototype,"cameraAcceleration",void 0);A([D()],Ba.prototype,"maxCameraSpeed",void 0);A([Qf("lockedTargetId")],Ba.prototype,"lockedTarget",void 0);class RF extends Us{constructor(e,t,i,s,r,n){super(e,T.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=T.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 ia;(function(o){o[o.A=0]="A",o[o.B=1]="B",o[o.X=2]="X",o[o.Y=3]="Y",o[o.LB=4]="LB",o[o.RB=5]="RB",o[o.Back=8]="Back",o[o.Start=9]="Start",o[o.LeftStick=10]="LeftStick",o[o.RightStick=11]="RightStick"})(ia||(ia={}));var Mc;(function(o){o[o.Up=12]="Up",o[o.Down=13]="Down",o[o.Left=14]="Left",o[o.Right=15]="Right"})(Mc||(Mc={}));class IF extends xr{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new he,this.onButtonUpObservable=new he,this.onPadDownObservable=new he,this.onPadUpObservable=new he,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=xr.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,ia.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,ia.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,ia.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,ia.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,ia.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,ia.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,ia.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,ia.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,ia.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,ia.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Mc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Mc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Mc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Mc.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 Qa;(function(o){o[o.Cross=0]="Cross",o[o.Circle=1]="Circle",o[o.Square=2]="Square",o[o.Triangle=3]="Triangle",o[o.L1=4]="L1",o[o.R1=5]="R1",o[o.Share=8]="Share",o[o.Options=9]="Options",o[o.LeftStick=10]="LeftStick",o[o.RightStick=11]="RightStick"})(Qa||(Qa={}));var Dc;(function(o){o[o.Up=12]="Up",o[o.Down=13]="Down",o[o.Left=14]="Left",o[o.Right=15]="Right"})(Dc||(Dc={}));class PF extends xr{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 he,this.onButtonUpObservable=new he,this.onPadDownObservable=new he,this.onPadUpObservable=new he,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=xr.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,Qa.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Qa.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Qa.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Qa.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Qa.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Qa.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Qa.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Qa.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Qa.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Qa.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Dc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Dc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Dc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Dc.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 MF{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new he,gr()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new he(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=xr.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 IF(e.id,e.index,e,s):i?t=new PF(e.id,e.index,e):t=new CF(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&&(fe.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&re.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new _u(o,T.Zero(),e));class _u extends Bb{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"}}et._CreateDefaultParsedCamera=(o,e)=>new _u(o,T.Zero(),e);Mi.AddNodeConstructor("GamepadCamera",(o,e)=>()=>new Cx(o,T.Zero(),e));class Cx extends _u{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const OF="passCubePixelShader",NF=`varying vec2 vUV;uniform samplerCube textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 uv=vUV*2.0-1.0; @@ -283,10 +283,10 @@ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); #endif -}`;ne.ShadersStore[PF]=MF;class el extends lt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,a=0,l=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,a,void 0,null,l)}static _Parse(e,t,i,s){return Xe.Parse(()=>new el(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}j("BABYLON.PassPostProcess",el);re._RescalePostProcessFactory=o=>new el("rescale",1,null,2,o,!1,0);const DF="anaglyphPixelShader",OF=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +}`;ne.ShadersStore[OF]=NF;class el extends lt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,a=0,l=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,a,void 0,null,l)}static _Parse(e,t,i,s){return Xe.Parse(()=>new el(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}j("BABYLON.PassPostProcess",el);re._RescalePostProcessFactory=o=>new el("rescale",1,null,2,o,!1,0);const wF="anaglyphPixelShader",FF=`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);}`;ne.ShadersStore[DF]=OF;class Lb extends lt{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(a=>{a.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}j("BABYLON.AnaglyphPostProcess",Lb);function mm(o){o._rigCameras[0]._rigPostProcess=new el(o.name+"_passthru",1,o._rigCameras[0]),o._rigCameras[1]._rigPostProcess=new Lb(o.name+"_anaglyph",1,o._rigCameras)}Mi.AddNodeConstructor("AnaglyphArcRotateCamera",(o,e,t)=>()=>new NF(o,0,0,1,T.Zero(),t.interaxial_distance,e));class NF extends Ji{constructor(e,t,i,s,r,n,a){super(e,t,i,s,r,a),this._setRigMode=()=>mm(this),this.interaxialDistance=n,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Mi.AddNodeConstructor("AnaglyphFreeCamera",(o,e,t)=>()=>new wF(o,T.Zero(),t.interaxial_distance,e));class wF extends zn{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Mi.AddNodeConstructor("AnaglyphGamepadCamera",(o,e,t)=>()=>new FF(o,T.Zero(),t.interaxial_distance,e));class FF extends Ex{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Mi.AddNodeConstructor("AnaglyphUniversalCamera",(o,e,t)=>()=>new LF(o,T.Zero(),t.interaxial_distance,e));class LF extends _u{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const BF="stereoscopicInterlacePixelShader",VF=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +{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);}`;ne.ShadersStore[wF]=FF;class Vb extends lt{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(a=>{a.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}j("BABYLON.AnaglyphPostProcess",Vb);function mm(o){o._rigCameras[0]._rigPostProcess=new el(o.name+"_passthru",1,o._rigCameras[0]),o._rigCameras[1]._rigPostProcess=new Vb(o.name+"_anaglyph",1,o._rigCameras)}Mi.AddNodeConstructor("AnaglyphArcRotateCamera",(o,e,t)=>()=>new LF(o,0,0,1,T.Zero(),t.interaxial_distance,e));class LF extends Ji{constructor(e,t,i,s,r,n,a){super(e,t,i,s,r,a),this._setRigMode=()=>mm(this),this.interaxialDistance=n,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Mi.AddNodeConstructor("AnaglyphFreeCamera",(o,e,t)=>()=>new BF(o,T.Zero(),t.interaxial_distance,e));class BF extends zn{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Mi.AddNodeConstructor("AnaglyphGamepadCamera",(o,e,t)=>()=>new VF(o,T.Zero(),t.interaxial_distance,e));class VF extends Cx{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Mi.AddNodeConstructor("AnaglyphUniversalCamera",(o,e,t)=>()=>new UF(o,T.Zero(),t.interaxial_distance,e));class UF extends _u{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>mm(this),this.interaxialDistance=i,this.setCameraRigMode(et.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const kF="stereoscopicInterlacePixelShader",GF=`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; @@ -301,18 +301,18 @@ useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2. #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);} -`;ne.ShadersStore[BF]=VF;class UF extends lt{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,a,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Re(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Re(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 gm(o){const e=o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_INTERLACED?(o._rigCameras[0]._rigPostProcess=new el(o.name+"_passthru",1,o._rigCameras[0]),o._rigCameras[1]._rigPostProcess=new UF(o.name+"_stereoInterlace",o._rigCameras,!1,!0)):(o._rigCameras[t?1:0].viewport=new Na(0,0,e?.5:1,e?1:.5),o._rigCameras[t?0:1].viewport=new Na(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Mi.AddNodeConstructor("StereoscopicArcRotateCamera",(o,e,t)=>()=>new kF(o,0,0,1,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class kF extends Ji{constructor(e,t,i,s,r,n,a,l){super(e,t,i,s,r,l),this._setRigMode=()=>gm(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Mi.AddNodeConstructor("StereoscopicFreeCamera",(o,e,t)=>()=>new GF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class GF extends zn{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Mi.AddNodeConstructor("StereoscopicGamepadCamera",(o,e,t)=>()=>new zF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class zF extends Ex{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Mi.AddNodeConstructor("StereoscopicFreeCamera",(o,e,t)=>()=>new WF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class WF extends _u{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}Mi.AddNodeConstructor("VirtualJoysticksCamera",(o,e)=>()=>new HF(o,T.Zero(),e));class HF extends zn{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class mu{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 k.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return k.Translation(-t,0,0)}get leftPreViewMatrix(){return k.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return k.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new mu;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 XF="vrDistortionCorrectionPixelShader",YF=`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; +`;ne.ShadersStore[kF]=GF;class zF extends lt{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,a,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Re(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Re(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 gm(o){const e=o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;o.cameraRigMode===et.RIG_MODE_STEREOSCOPIC_INTERLACED?(o._rigCameras[0]._rigPostProcess=new el(o.name+"_passthru",1,o._rigCameras[0]),o._rigCameras[1]._rigPostProcess=new zF(o.name+"_stereoInterlace",o._rigCameras,!1,!0)):(o._rigCameras[t?1:0].viewport=new Na(0,0,e?.5:1,e?1:.5),o._rigCameras[t?0:1].viewport=new Na(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Mi.AddNodeConstructor("StereoscopicArcRotateCamera",(o,e,t)=>()=>new WF(o,0,0,1,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class WF extends Ji{constructor(e,t,i,s,r,n,a,l){super(e,t,i,s,r,l),this._setRigMode=()=>gm(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Mi.AddNodeConstructor("StereoscopicFreeCamera",(o,e,t)=>()=>new HF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class HF extends zn{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Mi.AddNodeConstructor("StereoscopicGamepadCamera",(o,e,t)=>()=>new XF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class XF extends Cx{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Mi.AddNodeConstructor("StereoscopicFreeCamera",(o,e,t)=>()=>new YF(o,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class YF extends _u{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>gm(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?et.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:et.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}Mi.AddNodeConstructor("VirtualJoysticksCamera",(o,e)=>()=>new $F(o,T.Zero(),e));class $F extends zn{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class mu{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 k.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return k.Translation(-t,0,0)}get leftPreViewMatrix(){return k.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return k.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new mu;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 KF="vrDistortionCorrectionPixelShader",qF=`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);}}`;ne.ShadersStore[XF]=YF;class l0 extends lt{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,ee.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 Re(2,2/this.aspectRatio),this._scaleFactor=new Re(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new Re(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 $F="vrMultiviewToSingleviewPixelShader",KF=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;ne.ShadersStore[KF]=qF;class c0 extends lt{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,ee.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 Re(2,2/this.aspectRatio),this._scaleFactor=new Re(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new Re(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 jF="vrMultiviewToSingleviewPixelShader",QF=`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));}`;ne.ShadersStore[$F]=KF;class Vv extends ms{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}}re.prototype.createMultiviewRenderTargetTexture=function(o,e,t,i){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:o,height:e});r._framebuffer=s.createFramebuffer();const n=new Ti(this,Vt.Unknown,!0);return n.width=o,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,o,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,o,e,2)),r._depthStencilTextureArray=i,n.isReady=!0,r.setTextures(n),r._depthStencilTexture=n,r};re.prototype.bindMultiviewFramebuffer=function(o){const e=o,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"};re.prototype.bindSpaceWarpFramebuffer=function(o){const e=o,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")};et.prototype._useMultiviewToSingleView=!1;et.prototype._multiviewTexture=null;et.prototype._resizeOrCreateMultiviewTexture=function(o,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=o||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new Vv(this.getScene(),{width:o,height:e})):this._multiviewTexture=new Vv(this.getScene(),{width:o,height:e})};function Bb(o,e){const t=new it(o,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 qF=Qe.prototype.createSceneUniformBuffer;Qe.prototype._transformMatrixR=k.Zero();Qe.prototype._multiviewSceneUbo=null;Qe.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=Bb(this.getEngine(),"scene_multiview")};Qe.prototype.createSceneUniformBuffer=function(o){return this._multiviewSceneUbo?Bb(this.getEngine(),o):qF.bind(this)(o)};Qe.prototype._updateMultiviewUbo=function(o,e){o&&e&&o.multiplyToRef(e,this._transformMatrixR),o&&e&&(o.multiplyToRef(e,K.Matrix[0]),Aa.GetRightPlaneToRef(K.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))};Qe.prototype._renderMultiviewToSingleView=function(o){o._resizeOrCreateMultiviewTexture(o._rigPostProcess&&o._rigPostProcess&&o._rigPostProcess.width>0?o._rigPostProcess.width:this.getEngine().getRenderWidth(!0),o._rigPostProcess&&o._rigPostProcess&&o._rigPostProcess.height>0?o._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),o.outputRenderTarget=o._multiviewTexture,this._renderForCamera(o),o.outputRenderTarget=null;for(let e=0;e{}),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 Sx(o,e){const t=e.vrCameraMetrics||mu.GetDefault();o._rigCameras[0]._cameraRigParams.vrMetrics=t,o._rigCameras[0].viewport=new Na(0,0,.5,1),o._rigCameras[0]._cameraRigParams.vrWorkMatrix=new k,o._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,o._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,o._rigCameras[0].getProjectionMatrix=o._rigCameras[0]._getVRProjectionMatrix,o._rigCameras[1]._cameraRigParams.vrMetrics=t,o._rigCameras[1].viewport=new Na(.5,0,.5,1),o._rigCameras[1]._cameraRigParams.vrWorkMatrix=new k,o._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,o._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,o._rigCameras[1].getProjectionMatrix=o._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(o.getScene().getEngine().getCaps().multiview?(o._useMultiviewToSingleView=!0,o._rigPostProcess=new jF("VRMultiviewToSingleview",o,t.postProcessScaleFactor)):(G.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(o._rigCameras[0]._rigPostProcess=new l0("VR_Distort_Compensation_Left",o._rigCameras[0],!1,t),o._rigCameras[1]._rigPostProcess=new l0("VR_Distort_Compensation_Right",o._rigCameras[1],!0,t))}Mi.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(o,e)=>()=>new QF(o,0,0,1,T.Zero(),e));class QF extends Ji{constructor(e,t,i,s,r,n,a=!0,l=mu.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=h=>Sx(this,h),l.compensateDistortion=a,this.setCameraRigMode(et.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Mi.AddNodeConstructor("VRDeviceOrientationFreeCamera",(o,e)=>()=>new Cx(o,T.Zero(),e));class Cx extends Tx{constructor(e,t,i,s=!0,r=mu.GetDefault()){super(e,t,i),this._setRigMode=n=>Sx(this,n),r.compensateDistortion=s,this.setCameraRigMode(et.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Mi.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(o,e)=>()=>new ZF(o,T.Zero(),e));class ZF extends Cx{constructor(e,t,i,s=!0,r=mu.GetDefault()){super(e,t,i,s,r),this._setRigMode=n=>Sx(this,n),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class P_{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 we{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,re.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}}we._DiffuseTextureEnabled=!0;we._DetailTextureEnabled=!0;we._DecalMapEnabled=!0;we._AmbientTextureEnabled=!0;we._OpacityTextureEnabled=!0;we._ReflectionTextureEnabled=!0;we._EmissiveTextureEnabled=!0;we._SpecularTextureEnabled=!0;we._BumpTextureEnabled=!0;we._LightmapTextureEnabled=!0;we._RefractionTextureEnabled=!0;we._ColorGradingTextureEnabled=!0;we._FresnelEnabled=!0;we._ClearCoatTextureEnabled=!0;we._ClearCoatBumpTextureEnabled=!0;we._ClearCoatTintTextureEnabled=!0;we._SheenTextureEnabled=!0;we._AnisotropicTextureEnabled=!0;we._ThicknessTextureEnabled=!0;we._RefractionIntensityTextureEnabled=!0;we._TranslucencyIntensityTextureEnabled=!0;we._IridescenceTextureEnabled=!0;const JF="decalFragmentDeclaration",e1=`#ifdef DECAL +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;ne.ShadersStore[jF]=QF;class Vv extends ms{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}}re.prototype.createMultiviewRenderTargetTexture=function(o,e,t,i){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:o,height:e});r._framebuffer=s.createFramebuffer();const n=new Ti(this,Ut.Unknown,!0);return n.width=o,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,o,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,o,e,2)),r._depthStencilTextureArray=i,n.isReady=!0,r.setTextures(n),r._depthStencilTexture=n,r};re.prototype.bindMultiviewFramebuffer=function(o){const e=o,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"};re.prototype.bindSpaceWarpFramebuffer=function(o){const e=o,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")};et.prototype._useMultiviewToSingleView=!1;et.prototype._multiviewTexture=null;et.prototype._resizeOrCreateMultiviewTexture=function(o,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=o||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new Vv(this.getScene(),{width:o,height:e})):this._multiviewTexture=new Vv(this.getScene(),{width:o,height:e})};function Ub(o,e){const t=new it(o,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 ZF=Qe.prototype.createSceneUniformBuffer;Qe.prototype._transformMatrixR=k.Zero();Qe.prototype._multiviewSceneUbo=null;Qe.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=Ub(this.getEngine(),"scene_multiview")};Qe.prototype.createSceneUniformBuffer=function(o){return this._multiviewSceneUbo?Ub(this.getEngine(),o):ZF.bind(this)(o)};Qe.prototype._updateMultiviewUbo=function(o,e){o&&e&&o.multiplyToRef(e,this._transformMatrixR),o&&e&&(o.multiplyToRef(e,K.Matrix[0]),Aa.GetRightPlaneToRef(K.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))};Qe.prototype._renderMultiviewToSingleView=function(o){o._resizeOrCreateMultiviewTexture(o._rigPostProcess&&o._rigPostProcess&&o._rigPostProcess.width>0?o._rigPostProcess.width:this.getEngine().getRenderWidth(!0),o._rigPostProcess&&o._rigPostProcess&&o._rigPostProcess.height>0?o._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),o.outputRenderTarget=o._multiviewTexture,this._renderForCamera(o),o.outputRenderTarget=null;for(let e=0;e{}),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 bx(o,e){const t=e.vrCameraMetrics||mu.GetDefault();o._rigCameras[0]._cameraRigParams.vrMetrics=t,o._rigCameras[0].viewport=new Na(0,0,.5,1),o._rigCameras[0]._cameraRigParams.vrWorkMatrix=new k,o._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,o._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,o._rigCameras[0].getProjectionMatrix=o._rigCameras[0]._getVRProjectionMatrix,o._rigCameras[1]._cameraRigParams.vrMetrics=t,o._rigCameras[1].viewport=new Na(.5,0,.5,1),o._rigCameras[1]._cameraRigParams.vrWorkMatrix=new k,o._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,o._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,o._rigCameras[1].getProjectionMatrix=o._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(o.getScene().getEngine().getCaps().multiview?(o._useMultiviewToSingleView=!0,o._rigPostProcess=new JF("VRMultiviewToSingleview",o,t.postProcessScaleFactor)):(G.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(o._rigCameras[0]._rigPostProcess=new c0("VR_Distort_Compensation_Left",o._rigCameras[0],!1,t),o._rigCameras[1]._rigPostProcess=new c0("VR_Distort_Compensation_Right",o._rigCameras[1],!0,t))}Mi.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(o,e)=>()=>new e1(o,0,0,1,T.Zero(),e));class e1 extends Ji{constructor(e,t,i,s,r,n,a=!0,l=mu.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=h=>bx(this,h),l.compensateDistortion=a,this.setCameraRigMode(et.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Mi.AddNodeConstructor("VRDeviceOrientationFreeCamera",(o,e)=>()=>new yx(o,T.Zero(),e));class yx extends Sx{constructor(e,t,i,s=!0,r=mu.GetDefault()){super(e,t,i),this._setRigMode=n=>bx(this,n),r.compensateDistortion=s,this.setCameraRigMode(et.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Mi.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(o,e)=>()=>new t1(o,T.Zero(),e));class t1 extends yx{constructor(e,t,i,s=!0,r=mu.GetDefault()){super(e,t,i,s,r),this._setRigMode=n=>bx(this,n),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class P_{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 we{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,re.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,re.MarkAllMaterialsAsDirty(1))}}we._DiffuseTextureEnabled=!0;we._DetailTextureEnabled=!0;we._DecalMapEnabled=!0;we._AmbientTextureEnabled=!0;we._OpacityTextureEnabled=!0;we._ReflectionTextureEnabled=!0;we._EmissiveTextureEnabled=!0;we._SpecularTextureEnabled=!0;we._BumpTextureEnabled=!0;we._LightmapTextureEnabled=!0;we._RefractionTextureEnabled=!0;we._ColorGradingTextureEnabled=!0;we._FresnelEnabled=!0;we._ClearCoatTextureEnabled=!0;we._ClearCoatBumpTextureEnabled=!0;we._ClearCoatTintTextureEnabled=!0;we._SheenTextureEnabled=!0;we._AnisotropicTextureEnabled=!0;we._ThicknessTextureEnabled=!0;we._RefractionIntensityTextureEnabled=!0;we._TranslucencyIntensityTextureEnabled=!0;we._IridescenceTextureEnabled=!0;const i1="decalFragmentDeclaration",s1=`#ifdef DECAL uniform vec4 vDecalInfos; #endif -`;ne.IncludesShadersStore[JF]=e1;const t1="defaultFragmentDeclaration",i1=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +`;ne.IncludesShadersStore[i1]=s1;const r1="defaultFragmentDeclaration",n1=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; #ifdef SPECULARTERM uniform vec4 vSpecularColor; #endif @@ -384,25 +384,25 @@ uniform vec4 vDetailInfos; #endif #include #define ADDITIONAL_FRAGMENT_DECLARATION -`;ne.IncludesShadersStore[t1]=i1;const s1="sceneUboDeclaration",r1=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +`;ne.IncludesShadersStore[r1]=n1;const a1="sceneUboDeclaration",o1=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;}; -`;ne.IncludesShadersStore[s1]=r1;const n1="meshUboDeclaration",a1=`#ifdef WEBGL2 +`;ne.IncludesShadersStore[a1]=o1;const l1="meshUboDeclaration",h1=`#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO -`;ne.IncludesShadersStore[n1]=a1;const o1="defaultUboDeclaration",l1=`layout(std140,column_major) uniform;uniform Material +`;ne.IncludesShadersStore[l1]=h1;const c1="defaultUboDeclaration",u1=`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 #include -`;ne.IncludesShadersStore[o1]=l1;const h1="prePassDeclaration",c1=`#ifdef PREPASS +`;ne.IncludesShadersStore[c1]=u1;const d1="prePassDeclaration",f1=`#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_DEPTH @@ -412,17 +412,17 @@ varying highp vec3 vViewPos; varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif -`;ne.IncludesShadersStore[h1]=c1;const u1="oitDeclaration",d1=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;ne.IncludesShadersStore[d1]=f1;const p1="oitDeclaration",_1=`#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 -`;ne.IncludesShadersStore[u1]=d1;const f1="mainUVVaryingDeclaration",p1=`#ifdef MAINUV{X} +`;ne.IncludesShadersStore[p1]=_1;const m1="mainUVVaryingDeclaration",g1=`#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif -`;ne.IncludesShadersStore[f1]=p1;const _1="helperFunctions",m1=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; +`;ne.IncludesShadersStore[m1]=g1;const v1="helperFunctions",x1=`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 @@ -522,7 +522,7 @@ float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float nor 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;} -`;ne.IncludesShadersStore[_1]=m1;const g1="lightFragmentDeclaration",v1=`#ifdef LIGHT{X} +`;ne.IncludesShadersStore[v1]=x1;const T1="lightFragmentDeclaration",E1=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; @@ -584,7 +584,7 @@ uniform vec3 vLightGround{X}; uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; #endif #endif -`;ne.IncludesShadersStore[g1]=v1;const x1="lightUboDeclaration",T1=`#ifdef LIGHT{X} +`;ne.IncludesShadersStore[T1]=E1;const S1="lightUboDeclaration",C1=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} @@ -642,7 +642,7 @@ uniform mat4 lightMatrix{X}; #endif #endif #endif -`;ne.IncludesShadersStore[x1]=T1;const E1="lightsFragmentFunctions",S1=`struct lightingInfo +`;ne.IncludesShadersStore[S1]=C1;const b1="lightsFragmentFunctions",y1=`struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; @@ -691,7 +691,7 @@ vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vN #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;}`;ne.IncludesShadersStore[E1]=S1;const C1="shadowsFragmentFunctions",b1=`#ifdef SHADOWS +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;}`;ne.IncludesShadersStore[b1]=y1;const A1="shadowsFragmentFunctions",R1=`#ifdef SHADOWS #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else @@ -1017,7 +1017,7 @@ float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depth {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} #endif #endif -`;ne.IncludesShadersStore[C1]=b1;const y1="samplerFragmentDeclaration",A1=`#ifdef _DEFINENAME_ +`;ne.IncludesShadersStore[A1]=R1;const I1="samplerFragmentDeclaration",P1=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -1035,11 +1035,11 @@ varying vec2 v_VARYINGNAME_UV; #endif uniform sampler2D _SAMPLERNAME_Sampler; #endif -`;ne.IncludesShadersStore[y1]=A1;const R1="fresnelFunction",I1=`#ifdef FRESNEL +`;ne.IncludesShadersStore[I1]=P1;const M1="fresnelFunction",D1=`#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 -`;ne.IncludesShadersStore[R1]=I1;const P1="reflectionFunction",M1=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +`;ne.IncludesShadersStore[M1]=D1;const O1="reflectionFunction",N1=`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); } @@ -1101,7 +1101,7 @@ return vec3(0,0,0); #endif } #endif -`;ne.IncludesShadersStore[P1]=M1;const D1="imageProcessingDeclaration",O1=`#ifdef EXPOSURE +`;ne.IncludesShadersStore[O1]=N1;const w1="imageProcessingDeclaration",F1=`#ifdef EXPOSURE uniform float exposureLinear; #endif #ifdef CONTRAST @@ -1127,7 +1127,7 @@ uniform vec4 colorTransformSettings; #ifdef DITHER uniform float ditherIntensity; #endif -`;ne.IncludesShadersStore[D1]=O1;const N1="imageProcessingFunctions",w1=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) +`;ne.IncludesShadersStore[w1]=F1;const L1="imageProcessingFunctions",B1=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) /** * Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. * sampler3dSetting.x=textureOffset (0.5/textureSize). @@ -1211,7 +1211,7 @@ float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*- 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;}`;ne.IncludesShadersStore[N1]=w1;const F1="bumpFragmentMainFunctions",L1=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +return result;}`;ne.IncludesShadersStore[L1]=B1;const V1="bumpFragmentMainFunctions",U1=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif @@ -1272,7 +1272,7 @@ vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float 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 -`;ne.IncludesShadersStore[F1]=L1;const B1="bumpFragmentFunctions",V1=`#if defined(BUMP) +`;ne.IncludesShadersStore[V1]=U1;const k1="bumpFragmentFunctions",G1=`#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) @@ -1302,7 +1302,7 @@ return -texCoordOffset; #endif } #endif -`;ne.IncludesShadersStore[B1]=V1;const U1="clipPlaneFragmentDeclaration",k1=`#ifdef CLIPPLANE +`;ne.IncludesShadersStore[k1]=G1;const z1="clipPlaneFragmentDeclaration",W1=`#ifdef CLIPPLANE varying float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -1320,10 +1320,10 @@ varying float fClipDistance5; #ifdef CLIPPLANE6 varying float fClipDistance6; #endif -`;ne.IncludesShadersStore[U1]=k1;const G1="logDepthDeclaration",z1=`#ifdef LOGARITHMICDEPTH +`;ne.IncludesShadersStore[z1]=W1;const H1="logDepthDeclaration",X1=`#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif -`;ne.IncludesShadersStore[G1]=z1;const W1="fogFragmentDeclaration",H1=`#ifdef FOG +`;ne.IncludesShadersStore[H1]=X1;const Y1="fogFragmentDeclaration",$1=`#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. @@ -1338,7 +1338,7 @@ else if (FOGMODE_EXP2==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif -`;ne.IncludesShadersStore[W1]=H1;const X1="clipPlaneFragment",Y1=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +`;ne.IncludesShadersStore[Y1]=$1;const K1="clipPlaneFragment",q1=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE @@ -1365,7 +1365,7 @@ else if (fClipDistance5>0.0) else if (fClipDistance6>0.0) {discard;} #endif -`;ne.IncludesShadersStore[X1]=Y1;const $1="bumpFragment",K1=`vec2 uvOffset=vec2(0.0,0.0); +`;ne.IncludesShadersStore[K1]=q1;const j1="bumpFragment",Q1=`vec2 uvOffset=vec2(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; @@ -1417,7 +1417,7 @@ normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif -`;ne.IncludesShadersStore[$1]=K1;const q1="decalFragment",j1=`#ifdef DECAL +`;ne.IncludesShadersStore[j1]=Q1;const Z1="decalFragment",J1=`#ifdef DECAL #ifdef GAMMADECAL decalColor.rgb=toLinearSpace(decalColor.rgb); #endif @@ -1426,10 +1426,10 @@ decalColor.a*=decalColor.a; #endif surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); #endif -`;ne.IncludesShadersStore[q1]=j1;const Q1="depthPrePass",Z1=`#ifdef DEPTHPREPASS +`;ne.IncludesShadersStore[Z1]=J1;const eL="depthPrePass",tL=`#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif -`;ne.IncludesShadersStore[Q1]=Z1;const J1="lightFragment",eL=`#ifdef LIGHT{X} +`;ne.IncludesShadersStore[eL]=tL;const iL="lightFragment",sL=`#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else #ifdef PBR @@ -1691,17 +1691,17 @@ sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif -`;ne.IncludesShadersStore[J1]=eL;const tL="logDepthFragment",iL=`#ifdef LOGARITHMICDEPTH +`;ne.IncludesShadersStore[iL]=sL;const rL="logDepthFragment",nL=`#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif -`;ne.IncludesShadersStore[tL]=iL;const sL="fogFragment",rL=`#ifdef FOG +`;ne.IncludesShadersStore[rL]=nL;const aL="fogFragment",oL=`#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif -`;ne.IncludesShadersStore[sL]=rL;const nL="oitFragment",aL=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;ne.IncludesShadersStore[aL]=oL;const lL="oitFragment",hL=`#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; @@ -1726,7 +1726,7 @@ if (fragDepth>nearestDepth && fragDepth +`;ne.IncludesShadersStore[lL]=hL;const cL="defaultPixelShader",uL=`#include<__decl__defaultFragment> #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif @@ -2055,10 +2055,10 @@ if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier; #endif #define CUSTOM_FRAGMENT_MAIN_END } -`;ne.ShadersStore[oL]=lL;const hL="decalVertexDeclaration",cL=`#ifdef DECAL +`;ne.ShadersStore[cL]=uL;const dL="decalVertexDeclaration",fL=`#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif -`;ne.IncludesShadersStore[hL]=cL;const uL="defaultVertexDeclaration",dL=`uniform mat4 viewProjection;uniform mat4 view; +`;ne.IncludesShadersStore[dL]=fL;const pL="defaultVertexDeclaration",_L=`uniform mat4 viewProjection;uniform mat4 view; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif @@ -2091,10 +2091,10 @@ uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION -`;ne.IncludesShadersStore[uL]=dL;const fL="uvAttributeDeclaration",pL=`#ifdef UV{X} +`;ne.IncludesShadersStore[pL]=_L;const mL="uvAttributeDeclaration",gL=`#ifdef UV{X} attribute vec2 uv{X}; #endif -`;ne.IncludesShadersStore[fL]=pL;const _L="bonesDeclaration",mL=`#if NUM_BONE_INFLUENCERS>0 +`;ne.IncludesShadersStore[mL]=gL;const vL="bonesDeclaration",xL=`#if NUM_BONE_INFLUENCERS>0 attribute vec4 matricesIndices;attribute vec4 matricesWeights; #if NUM_BONE_INFLUENCERS>4 attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; @@ -2115,7 +2115,7 @@ mat4 readMatrixFromRawSampler(sampler2D smp,float index) #endif #endif #endif -`;ne.IncludesShadersStore[_L]=mL;const gL="bakedVertexAnimationDeclaration",vL=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStore[vL]=xL;const TL="bakedVertexAnimationDeclaration",EL=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; #ifdef INSTANCES attribute vec4 bakedVertexAnimationSettingsInstanced; @@ -2124,7 +2124,7 @@ attribute vec4 bakedVertexAnimationSettingsInstanced; 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 -`;ne.IncludesShadersStore[gL]=vL;const xL="instancesDeclaration",TL=`#ifdef INSTANCES +`;ne.IncludesShadersStore[TL]=EL;const SL="instancesDeclaration",CL=`#ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #ifdef INSTANCESCOLOR attribute vec4 instanceColor; @@ -2146,7 +2146,7 @@ uniform mat4 world; uniform mat4 previousWorld; #endif #endif -`;ne.IncludesShadersStore[xL]=TL;const EL="prePassVertexDeclaration",SL=`#ifdef PREPASS +`;ne.IncludesShadersStore[SL]=CL;const bL="prePassVertexDeclaration",yL=`#ifdef PREPASS #ifdef PREPASS_DEPTH varying vec3 vViewPos; #endif @@ -2154,15 +2154,15 @@ varying vec3 vViewPos; uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif -`;ne.IncludesShadersStore[EL]=SL;const CL="samplerVertexDeclaration",bL=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;ne.IncludesShadersStore[bL]=yL;const AL="samplerVertexDeclaration",RL=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif -`;ne.IncludesShadersStore[CL]=bL;const yL="bumpVertexDeclaration",AL=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;ne.IncludesShadersStore[AL]=RL;const IL="bumpVertexDeclaration",PL=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif -`;ne.IncludesShadersStore[yL]=AL;const RL="clipPlaneVertexDeclaration",IL=`#ifdef CLIPPLANE +`;ne.IncludesShadersStore[IL]=PL;const ML="clipPlaneVertexDeclaration",DL=`#ifdef CLIPPLANE uniform vec4 vClipPlane;varying float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -2180,10 +2180,10 @@ uniform vec4 vClipPlane5;varying float fClipDistance5; #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;varying float fClipDistance6; #endif -`;ne.IncludesShadersStore[RL]=IL;const PL="fogVertexDeclaration",ML=`#ifdef FOG +`;ne.IncludesShadersStore[ML]=DL;const OL="fogVertexDeclaration",NL=`#ifdef FOG varying vec3 vFogDistance; #endif -`;ne.IncludesShadersStore[PL]=ML;const DL="lightVxFragmentDeclaration",OL=`#ifdef LIGHT{X} +`;ne.IncludesShadersStore[OL]=NL;const wL="lightVxFragmentDeclaration",FL=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; @@ -2207,7 +2207,7 @@ uniform vec4 vLightFalloff{X}; uniform vec3 vLightGround{X}; #endif #endif -`;ne.IncludesShadersStore[DL]=OL;const NL="lightVxUboDeclaration",wL=`#ifdef LIGHT{X} +`;ne.IncludesShadersStore[wL]=FL;const LL="lightVxUboDeclaration",BL=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} @@ -2227,7 +2227,7 @@ varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 li #endif #endif #endif -`;ne.IncludesShadersStore[NL]=wL;const FL="morphTargetsVertexGlobalDeclaration",LL=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStore[LL]=BL;const VL="morphTargetsVertexGlobalDeclaration",UL=`#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) @@ -2235,7 +2235,7 @@ uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morp 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 -`;ne.IncludesShadersStore[FL]=LL;const BL="morphTargetsVertexDeclaration",VL=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStore[VL]=UL;const kL="morphTargetsVertexDeclaration",GL=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute vec3 position{X}; #ifdef MORPHTARGETS_NORMAL @@ -2249,12 +2249,12 @@ attribute vec2 uv_{X}; #endif #endif #endif -`;ne.IncludesShadersStore[BL]=VL;const UL="morphTargetsVertexGlobal",kL=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStore[kL]=GL;const zL="morphTargetsVertexGlobal",WL=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif -`;ne.IncludesShadersStore[UL]=kL;const GL="morphTargetsVertex",zL=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStore[zL]=WL;const HL="morphTargetsVertex",XL=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; #ifdef MORPHTARGETS_NORMAL @@ -2279,7 +2279,7 @@ uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; #endif #endif #endif -`;ne.IncludesShadersStore[GL]=zL;const WL="instancesVertex",HL=`#ifdef INSTANCES +`;ne.IncludesShadersStore[HL]=XL;const YL="instancesVertex",$L=`#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); @@ -2296,7 +2296,7 @@ mat4 finalWorld=world; mat4 finalPreviousWorld=previousWorld; #endif #endif -`;ne.IncludesShadersStore[WL]=HL;const XL="bonesVertex",YL=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStore[YL]=$L;const KL="bonesVertex",qL=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 mat4 influence; #ifdef BONETEXTURE @@ -2349,7 +2349,7 @@ influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; finalWorld=finalWorld*influence; #endif #endif -`;ne.IncludesShadersStore[XL]=YL;const $L="bakedVertexAnimation",KL=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStore[KL]=qL;const jL="bakedVertexAnimation",QL=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES #define BVASNAME bakedVertexAnimationSettingsInstanced @@ -2380,7 +2380,7 @@ VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIn #endif finalWorld=finalWorld*VATInfluence;} #endif -`;ne.IncludesShadersStore[$L]=KL;const qL="prePassVertex",jL=`#ifdef PREPASS_DEPTH +`;ne.IncludesShadersStore[jL]=QL;const ZL="prePassVertex",JL=`#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) @@ -2413,13 +2413,13 @@ vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*ve vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif -`;ne.IncludesShadersStore[qL]=jL;const QL="uvVariableDeclaration",ZL=`#if !defined(UV{X}) && defined(MAINUV{X}) +`;ne.IncludesShadersStore[ZL]=JL;const eB="uvVariableDeclaration",tB=`#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif -`;ne.IncludesShadersStore[QL]=ZL;const JL="samplerVertexImplementation",eB=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;ne.IncludesShadersStore[eB]=tB;const iB="samplerVertexImplementation",sB=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (v_INFONAME_==0.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} #ifdef UV2 @@ -2443,12 +2443,12 @@ else if (v_INFONAME_==5.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} #endif #endif -`;ne.IncludesShadersStore[JL]=eB;const tB="bumpVertex",iB=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;ne.IncludesShadersStore[iB]=sB;const rB="bumpVertex",nB=`#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 -`;ne.IncludesShadersStore[tB]=iB;const sB="clipPlaneVertex",rB=`#ifdef CLIPPLANE +`;ne.IncludesShadersStore[rB]=nB;const aB="clipPlaneVertex",oB=`#ifdef CLIPPLANE fClipDistance=dot(worldPos,vClipPlane); #endif #ifdef CLIPPLANE2 @@ -2466,10 +2466,10 @@ fClipDistance5=dot(worldPos,vClipPlane5); #ifdef CLIPPLANE6 fClipDistance6=dot(worldPos,vClipPlane6); #endif -`;ne.IncludesShadersStore[sB]=rB;const nB="fogVertex",aB=`#ifdef FOG +`;ne.IncludesShadersStore[aB]=oB;const lB="fogVertex",hB=`#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif -`;ne.IncludesShadersStore[nB]=aB;const oB="shadowsVertex",lB=`#ifdef SHADOWS +`;ne.IncludesShadersStore[lB]=hB;const cB="shadowsVertex",uB=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) vPositionFromCamera{X}=view*worldPos;for (int i=0; i +`;ne.IncludesShadersStore[mB]=gB;const vB="defaultVertexShader",xB=`#include<__decl__defaultVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL @@ -2635,19 +2635,19 @@ vMainUV1=uvUpdated; #include #define CUSTOM_VERTEX_MAIN_END } -`;ne.ShadersStore[_B]=mB;const gB=new RegExp("^([gimus]+)!");class eh{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;sthis._handlePluginEvent(s,r),this._plugins.push(e),this._plugins.sort((s,r)=>s.priority-r.priority),this._codeInjectionPoints={};const i={};i[eh._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&s.uniforms.push(...this._uniformList),this._samplerList.length>0&&s.samplers.push(...this._samplerList),this._uboList.length>0&&s.uniformBuffersNames.push(...this._uboList),s.customCode=this._injectCustomCode(s,s.customCode);break}case Lr.PrepareUniformBuffer:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const r of this._plugins){const n=r.getUniforms();if(n){if(n.ubo)for(const a of n.ubo){if(a.size&&a.type){const l=(i=a.arraySize)!==null&&i!==void 0?i:0;s.ubo.addUniform(a.name,a.size,l),this._uboDeclaration+=`${a.type} ${a.name}${l>0?`[${l}]`:""}; +`;ne.ShadersStore[vB]=xB;const TB=new RegExp("^([gimus]+)!");class th{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;sthis._handlePluginEvent(s,r),this._plugins.push(e),this._plugins.sort((s,r)=>s.priority-r.priority),this._codeInjectionPoints={};const i={};i[th._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&s.uniforms.push(...this._uniformList),this._samplerList.length>0&&s.samplers.push(...this._samplerList),this._uboList.length>0&&s.uniformBuffersNames.push(...this._uboList),s.customCode=this._injectCustomCode(s,s.customCode);break}case Lr.PrepareUniformBuffer:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const r of this._plugins){const n=r.getUniforms();if(n){if(n.ubo)for(const a of n.ubo){if(a.size&&a.type){const l=(i=a.arraySize)!==null&&i!==void 0?i:0;s.ubo.addUniform(a.name,a.size,l),this._uboDeclaration+=`${a.type} ${a.name}${l>0?`[${l}]`:""}; `}this._uniformList.push(a.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+` `),n.fragment&&(this._fragmentDeclaration+=n.fragment+` `)}r.getSamplers(this._samplerList),r.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 r,n;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 a=(r=this._codeInjectionPoints)===null||r===void 0?void 0:r[i];if(!a)return s;let l=null;for(let h in a){let c="";for(const u of this._activePlugins){let d=(n=u.getCustomCode(i))===null||n===void 0?void 0:n[h];if(d){if(u.resolveIncludes){if(l===null){const f=is.GLSL;l={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:ne.GetShadersRepository(f),includesShadersStore:ne.GetIncludesShadersStore(f),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}l.isFragment=i==="fragment",Ia._ProcessIncludes(d,l,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 _=gB.exec(h);_&&_.length>=2&&(u=_[1],h=h.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const d=s,f=new RegExp(h,u);let p=f.exec(d);for(;p!==null;){let _=c;for(let g=0;g0)if(h.charAt(0)==="!"){h=h.substring(1);let u="g";if(h.charAt(0)==="!")u="",h=h.substring(1);else{const _=TB.exec(h);_&&_.length>=2&&(u=_[1],h=h.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const d=s,f=new RegExp(h,u);let p=f.exec(d);for(;p!==null;){let _=c;for(let g=0;g{xB()});const vB=[];let h0=null;function xB(){vB.length=0,Ie.OnEventObservable.remove(h0),h0=null}class ca{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new eh(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){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([D()],ca.prototype,"name",void 0);A([D()],ca.prototype,"priority",void 0);A([D()],ca.prototype,"resolveIncludes",void 0);A([D()],ca.prototype,"registerForExtraEvents",void 0);class TB extends Wn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Th extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new TB,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ie.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&this._isEnabled?(Me.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&we.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Me.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&we.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)===null||t===void 0||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}A([Jt("detailTexture"),Ce("_markAllSubMeshesAsTexturesDirty")],Th.prototype,"texture",void 0);A([D()],Th.prototype,"diffuseBlendLevel",void 0);A([D()],Th.prototype,"roughnessBlendLevel",void 0);A([D()],Th.prototype,"bumpLevel",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Th.prototype,"normalBlendMethod",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Th.prototype,"isEnabled",void 0);const dv={effect:null,subMesh:null};class EB extends Wn{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 Oe extends ep{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 Te(0,0,0),this.diffuseColor=new Te(1,1,1),this.specularColor=new Te(1,1,1),this.emissiveColor=new Te(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 qs(16),this._worldViewProjectionMatrix=k.Zero(),this._globalAmbientColor=new Te(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Th(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new P_,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Oe.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),Oe.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 Oe.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||Oe.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===Ie.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ie.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo),t.materialDefines=new EB(this._eventInfo.defineNames));const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();r._needNormals=Me.PrepareDefinesForLights(s,e,r,!0,this._maxSimultaneousLights,this._disableLighting),Me.PrepareDefinesForMultiview(s,r);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Me.PrepareDefinesForPrePass(s,r,this.canRenderToMRT&&!a),Me.PrepareDefinesForOIT(s,r,a),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let h=1;h<=6;++h)r["MAINUV"+h]=!1;if(s.texturesEnabled){if(r.DIFFUSEDIRECTUV=0,r.BUMPDIRECTUV=0,r.AMBIENTDIRECTUV=0,r.OPACITYDIRECTUV=0,r.EMISSIVEDIRECTUV=0,r.SPECULARDIRECTUV=0,r.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&Oe.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&Oe.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&Oe.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&Oe.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===ee.INVCUBIC_MODE,r.REFLECTIONMAP_3D=this._reflectionTexture.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,r.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case ee.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case ee.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case ee.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case ee.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case ee.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case ee.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case ee.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC");break}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&Oe.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&Oe.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&Oe.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Oe.BumpTextureEnabled){if(this._bumpTexture.isReady())Me.PrepareDefinesForMergedUV(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAX_RHS=s.useRightHandedSystem,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAX_RHS=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&Oe.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())r._needUVs=!0,r.REFRACTION=!0,r.REFRACTIONMAP_3D=this._refractionTexture.isCube,r.RGBDREFRACTION=this._refractionTexture.isRGBD,r.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else r.REFRACTION=!1;r.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else r.DIFFUSE=!1,r.AMBIENT=!1,r.OPACITY=!1,r.REFLECTION=!1,r.EMISSIVE=!1,r.LIGHTMAP=!1,r.BUMP=!1,r.REFRACTION=!1;r.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),r.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,r.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,r.SPECULAROVERALPHA=this._useSpecularOverAlpha,r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,r.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(Oe.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(r.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,r.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,r.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,r.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,r.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,r.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,r._needNormals=!0,r.FRESNEL=!0):r.FRESNEL=!1),Me.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),Me.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Me.PrepareDefinesForAttributes(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(r.isDirty){const h=r._areLightsDisposed;r.markAsProcessed();const c=new Jh;r.REFLECTION&&c.addFallback(0,"REFLECTION"),r.SPECULAR&&c.addFallback(0,"SPECULAR"),r.BUMP&&c.addFallback(0,"BUMP"),r.PARALLAX&&c.addFallback(1,"PARALLAX"),r.PARALLAX_RHS&&c.addFallback(1,"PARALLAX_RHS"),r.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&c.addFallback(1,"FOG"),r.POINTSIZE&&c.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),Me.HandleFallbacksForShadows(r,c,this._maxSimultaneousLights),r.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&c.addFallback(4,"FRESNEL"),r.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const u=[P.PositionKind];r.NORMAL&&u.push(P.NormalKind),r.TANGENT&&u.push(P.TangentKind);for(let b=1;b<=6;++b)r["UV"+b]&&u.push(`uv${b===1?"":b}`);r.VERTEXCOLOR&&u.push(P.ColorKind),Me.PrepareAttributesForBones(u,e,r,c),Me.PrepareAttributesForInstances(u,r),Me.PrepareAttributesForMorphTargets(u,e,r),Me.PrepareAttributesForBakedVertexAnimation(u,e,r);let d="default";const f=["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"],_=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=f,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(Lr.PrepareEffect,this._eventInfo),P_.AddUniforms(f),jt&&(jt.PrepareUniforms(f,r),jt.PrepareSamplers(p,r)),Me.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),Ao(f);const v={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,f,_,p,r,u,v));const E=r.toString(),C=t.effect;let S=s.getEngine().createEffect(d,{attributes:u,uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:E,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},n);if(this._eventInfo.customCode=void 0,S)if(this._onEffectCreatedObservable&&(dv.effect=S,dv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dv)),this.allowShaderHotSwapping&&C&&!S.isReady()){if(S=C,r.markAsUnprocessed(),l=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(S,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!l,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var s;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=a._forceRebindOnNextCall||this._mustRebind(r,a,t.visibility);Me.BindBonesParameters(t,a);const h=this._uniformBuffer;if(l){if(this.bindViewProjection(a),!h.useUbo||!this.isFrozen||!h.isSync||a._forceRebindOnNextCall){if(Oe.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new Te(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&Oe.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Me.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&Oe.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Me.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&Oe.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Me.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&Oe.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;h.updateVector3("vReflectionPosition",c.boundingBoxPosition),h.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&Oe.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Me.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&Oe.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Me.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&Oe.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Me.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Oe.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Me.BindTextureMatrix(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&Oe.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;h.updateVector3("vRefractionPosition",u.boundingBoxPosition),h.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",Oe.EmissiveTextureEnabled?this.emissiveColor:Te.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&Oe.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&Oe.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Oe.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&Oe.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&Oe.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Oe.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&Oe.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Oe.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&Oe.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),so(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Me.BindLights(r,t,a,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==Qe.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),Me.BindFogParameters(r,t,a),n.NUM_MORPH_INFLUENCERS&&Me.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((s=t.bakedVertexAnimationManager)===null||s===void 0||s.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&Me.BindLogDepth(n,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,s,r,n,a,l,h,c,u;t&&((i=this._diffuseTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(a=this._emissiveTexture)===null||a===void 0||a.dispose(),(l=this._specularTexture)===null||l===void 0||l.dispose(),(h=this._bumpTexture)===null||h===void 0||h.dispose(),(c=this._lightmapTexture)===null||c===void 0||c.dispose(),(u=this._refractionTexture)===null||u===void 0||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Xe.Clone(()=>new Oe(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=Xe.Parse(()=>new Oe(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ie._parsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return we.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){we.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return we.DetailTextureEnabled}static set DetailTextureEnabled(e){we.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return we.AmbientTextureEnabled}static set AmbientTextureEnabled(e){we.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return we.OpacityTextureEnabled}static set OpacityTextureEnabled(e){we.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return we.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){we.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return we.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){we.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return we.SpecularTextureEnabled}static set SpecularTextureEnabled(e){we.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return we.BumpTextureEnabled}static set BumpTextureEnabled(e){we.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return we.LightmapTextureEnabled}static set LightmapTextureEnabled(e){we.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return we.RefractionTextureEnabled}static set RefractionTextureEnabled(e){we.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return we.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){we.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return we.FresnelEnabled}static set FresnelEnabled(e){we.FresnelEnabled=e}}A([Jt("diffuseTexture")],Oe.prototype,"_diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Oe.prototype,"diffuseTexture",void 0);A([Jt("ambientTexture")],Oe.prototype,"_ambientTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"ambientTexture",void 0);A([Jt("opacityTexture")],Oe.prototype,"_opacityTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Oe.prototype,"opacityTexture",void 0);A([Jt("reflectionTexture")],Oe.prototype,"_reflectionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"reflectionTexture",void 0);A([Jt("emissiveTexture")],Oe.prototype,"_emissiveTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"emissiveTexture",void 0);A([Jt("specularTexture")],Oe.prototype,"_specularTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"specularTexture",void 0);A([Jt("bumpTexture")],Oe.prototype,"_bumpTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"bumpTexture",void 0);A([Jt("lightmapTexture")],Oe.prototype,"_lightmapTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"lightmapTexture",void 0);A([Jt("refractionTexture")],Oe.prototype,"_refractionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"refractionTexture",void 0);A([ds("ambient")],Oe.prototype,"ambientColor",void 0);A([ds("diffuse")],Oe.prototype,"diffuseColor",void 0);A([ds("specular")],Oe.prototype,"specularColor",void 0);A([ds("emissive")],Oe.prototype,"emissiveColor",void 0);A([D()],Oe.prototype,"specularPower",void 0);A([D("useAlphaFromDiffuseTexture")],Oe.prototype,"_useAlphaFromDiffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Oe.prototype,"useAlphaFromDiffuseTexture",void 0);A([D("useEmissiveAsIllumination")],Oe.prototype,"_useEmissiveAsIllumination",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useEmissiveAsIllumination",void 0);A([D("linkEmissiveWithDiffuse")],Oe.prototype,"_linkEmissiveWithDiffuse",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"linkEmissiveWithDiffuse",void 0);A([D("useSpecularOverAlpha")],Oe.prototype,"_useSpecularOverAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useSpecularOverAlpha",void 0);A([D("useReflectionOverAlpha")],Oe.prototype,"_useReflectionOverAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useReflectionOverAlpha",void 0);A([D("disableLighting")],Oe.prototype,"_disableLighting",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],Oe.prototype,"disableLighting",void 0);A([D("useObjectSpaceNormalMap")],Oe.prototype,"_useObjectSpaceNormalMap",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useObjectSpaceNormalMap",void 0);A([D("useParallax")],Oe.prototype,"_useParallax",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useParallax",void 0);A([D("useParallaxOcclusion")],Oe.prototype,"_useParallaxOcclusion",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useParallaxOcclusion",void 0);A([D()],Oe.prototype,"parallaxScaleBias",void 0);A([D("roughness")],Oe.prototype,"_roughness",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"roughness",void 0);A([D()],Oe.prototype,"indexOfRefraction",void 0);A([D()],Oe.prototype,"invertRefractionY",void 0);A([D()],Oe.prototype,"alphaCutOff",void 0);A([D("useLightmapAsShadowmap")],Oe.prototype,"_useLightmapAsShadowmap",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useLightmapAsShadowmap",void 0);A([jf("diffuseFresnelParameters")],Oe.prototype,"_diffuseFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],Oe.prototype,"diffuseFresnelParameters",void 0);A([jf("opacityFresnelParameters")],Oe.prototype,"_opacityFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelAndMiscDirty")],Oe.prototype,"opacityFresnelParameters",void 0);A([jf("reflectionFresnelParameters")],Oe.prototype,"_reflectionFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],Oe.prototype,"reflectionFresnelParameters",void 0);A([jf("refractionFresnelParameters")],Oe.prototype,"_refractionFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],Oe.prototype,"refractionFresnelParameters",void 0);A([jf("emissiveFresnelParameters")],Oe.prototype,"_emissiveFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],Oe.prototype,"emissiveFresnelParameters",void 0);A([D("useReflectionFresnelFromSpecular")],Oe.prototype,"_useReflectionFresnelFromSpecular",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],Oe.prototype,"useReflectionFresnelFromSpecular",void 0);A([D("useGlossinessFromSpecularMapAlpha")],Oe.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"useGlossinessFromSpecularMapAlpha",void 0);A([D("maxSimultaneousLights")],Oe.prototype,"_maxSimultaneousLights",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],Oe.prototype,"maxSimultaneousLights",void 0);A([D("invertNormalMapX")],Oe.prototype,"_invertNormalMapX",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"invertNormalMapX",void 0);A([D("invertNormalMapY")],Oe.prototype,"_invertNormalMapY",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"invertNormalMapY",void 0);A([D("twoSidedLighting")],Oe.prototype,"_twoSidedLighting",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Oe.prototype,"twoSidedLighting",void 0);A([D("applyDecalMapAfterDetailMap")],Oe.prototype,"_applyDecalMapAfterDetailMap",void 0);A([Ce("_markAllSubMeshesAsMiscDirty")],Oe.prototype,"applyDecalMapAfterDetailMap",void 0);j("BABYLON.StandardMaterial",Oe);Qe.DefaultMaterialFactory=o=>new Oe("default material",o);We.prototype.createDynamicTexture=function(o,e,t,i){const s=new Ti(this,Vt.Dynamic);return s.baseWidth=o,s.baseHeight=e,t&&(o=this.needPOTTextures?We.GetExponentOfTwo(o,this._caps.maxTextureSize):o,e=this.needPOTTextures?We.GetExponentOfTwo(e,this._caps.maxTextureSize):e),s.width=o,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};We.prototype.updateDynamicTexture=function(o,e,t,i=!1,s,r=!1,n=!1){if(!o)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,o,!0,r);this._unpackFlipY(t===void 0?o.invertY:t),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(o.type),u=this._getInternalFormat(s||o.format),d=this._getRGBABufferInternalSizedFormat(o.type,u);a.texImage2D(l,0,d,u,c,e),o.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(o.format=s),o._dynamicTextureSource=e,o._premulAlpha=i,o.invertY=t||!1,o.isReady=!0};class Id extends ee{constructor(e,t,i=null,s=!1,r=3,n=5,a){super(null,i,!s,a,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._texture=l.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=l.createCanvas(1,1),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,a,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(a)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Id(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()&&G.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Id._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 bx{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}}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.createRenderTargetTextureProvider=r}}class yx{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Ti(this._engine,Vt.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new uu(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 a={width:e,height:t},l=n?new Vv(this._scene,a):new ms("XR renderTargetTexture",a,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(a,s);h.setTexture(c,0),l._texture=c}return r&&(n?h._depthStencilTextureArray=r:h._depthStencilTexture=this._createInternalTexture(a,r)),l.disableRescaling(),typeof XRWebGLBinding<"u"&&(l.skipInitialClear=!0),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 Ax extends bx{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new SB(t.scene,this)),this.layer=e}}class SB extends yx{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 vm{static GetDefaults(e){const t=new vm;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 CB{constructor(e,t=vm.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new he,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 Ax(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{fe.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 bB extends bx{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new yB(t,this)),this.layer=e}}class yB extends yx{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 AB{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 xm{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new he,this.onXRReferenceSpaceChanged=new he,this.onXRSessionEnded=new he,this.onXRSessionInit=new he,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),(e=this._engine)===null||e===void 0||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{G.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)===null||i===void 0?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new AB(this):(e=e||vm.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new CB(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.onXRSessionInit.notifyObservers(i),this.inXRSession=!0,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===void 0||s.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return xm.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;!this.inXRSession||!this._engine||(this.currentFrame=i,this.currentTimestamp=t,i&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=((s=this._baseLayerRTTProvider)===null||s===void 0?void 0:s.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)===null||e===void 0?void 0:e.getFramebufferDimensions())||null,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=>(G.Error("XR.requestReferenceSpace failed for the following reason: "),G.Error(t),G.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 G.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.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)===null||t===void 0||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)===null||i===void 0?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new bB(e.baseLayer):new Ax(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=>(G.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return(e=this._xrNavigator.xr.native)!==null&&e!==void 0?e:!1}get currentFrameRate(){var e;return(e=this.session)===null||e===void 0?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)===null||e===void 0?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||e===void 0?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)===null||e===void 0?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,t;return(t=(e=this.session)===null||e===void 0?void 0:e.enabledFeatures)!==null&&t!==void 0?t:null}}var rr;(function(o){o[o.ENTERING_XR=0]="ENTERING_XR",o[o.EXITING_XR=1]="EXITING_XR",o[o.IN_XR=2]="IN_XR",o[o.NOT_IN_XR=3]="NOT_IN_XR"})(rr||(rr={}));var Oc;(function(o){o[o.NOT_TRACKING=0]="NOT_TRACKING",o[o.TRACKING_LOST=1]="TRACKING_LOST",o[o.TRACKING=2]="TRACKING"})(Oc||(Oc={}));se._GroundMeshParser=(o,e)=>rp.Parse(o,e);class rp extends se{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=K.Matrix[5];i.invertToRef(s);const r=K.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return T.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new T(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=K.Matrix[5];s.invertToRef(r);const n=K.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return T.TransformNormalFromFloatsToRef(a.x,a.y,a.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 to.maxHeight){h=!0;const u=o.maxHeight;o.maxHeight=o.minHeight,o.minHeight=u}for(r=0;r<=o.subdivisions;r++)for(n=0;n<=o.subdivisions;n++){const u=new T(n*o.width/o.subdivisions-o.width/2,0,(o.subdivisions-r)*o.height/o.subdivisions-o.height/2),d=(u.x+o.width/2)/o.width*(o.bufferWidth-1)|0,f=(1-(u.z+o.height/2)/o.height)*(o.bufferHeight-1)|0,p=(d+f*o.bufferWidth)*4;let _=o.buffer[p]/255,g=o.buffer[p+1]/255,v=o.buffer[p+2]/255;const E=o.buffer[p+3]/255;h&&(_=1-_,g=1-g,v=1-v);const C=_*a.r+g*a.g+v*a.b;E>=l?u.y=o.minHeight+(o.maxHeight-o.minHeight)*C:u.y=o.minHeight-$t,t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/o.subdivisions,1-r/o.subdivisions)}for(r=0;r=o.minHeight,g=t[d*3+1]>=o.minHeight,v=t[f*3+1]>=o.minHeight;_&&g&&v&&(e.push(u),e.push(d),e.push(f)),t[p*3+1]>=o.minHeight&&_&&v&&(e.push(p),e.push(u),e.push(f))}De.ComputeNormals(t,e,i);const c=new De;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Tm(o,e={},t){const i=new rp(o,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,xl(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function kb(o,e,t=null){const i=new se(o,t);return Vb(e).applyToMesh(i,e.updatable),i}function Gb(o,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,a=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new Te(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||ht.LastCreatedScene;const f=new rp(o,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);const p=(_,g,v)=>{Ub({width:s,height:r,subdivisions:n,minHeight:a,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:g,bufferHeight:v,alphaFilter:c}).applyToMesh(f,u),d&&d(f),f._setReady(!0)};if(typeof e=="string"){const _=g=>{const v=g.width,E=g.height;if(i.isDisposed)return;const C=i==null?void 0:i.getEngine().resizeImageBitmap(g,v,E);p(C,v,E)};fe.LoadImage(e,_,t.onError?t.onError:()=>{},i.offlineProvider)}else p(e.data,e.width,e.height);return f}De.CreateGround=xl;De.CreateTiledGround=Vb;De.CreateGroundFromHeightMap=Ub;se.CreateGround=(o,e,t,i,s,r)=>Tm(o,{width:e,height:t,subdivisions:i,updatable:r},s);se.CreateTiledGround=(o,e,t,i,s,r,n,a,l)=>kb(o,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:l},a);se.CreateGroundFromHeightMap=(o,e,t,i,s,r,n,a,l,h,c)=>Gb(o,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},a);function Rx(o){const e=[],t=[],i=[],s=[],r=o.diameter||1,n=o.thickness||.5,a=(o.tessellation||16)|0,l=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,h=a+1;for(let u=0;u<=a;u++){const d=u/a,f=u*Math.PI*2/a-Math.PI/2,p=k.Translation(r/2,0,0).multiply(k.RotationY(f));for(let _=0;_<=a;_++){const g=1-_/a,v=_*Math.PI*2/a+Math.PI,E=Math.cos(v),C=Math.sin(v);let S=new T(E,C,0),b=S.scale(n/2);const R=new Re(d,g);b=T.TransformCoordinates(b,p),S=T.TransformNormal(S,p),t.push(b.x,b.y,b.z),i.push(S.x,S.y,S.z),s.push(R.x,pi.UseOpenGLOrientationForUV?1-R.y:R.y);const I=(u+1)%h,N=(_+1)%h;e.push(u*h+_),e.push(u*h+N),e.push(I*h+_),e.push(u*h+N),e.push(I*h+N),e.push(I*h+_)}}De._ComputeSides(l,t,e,i,s,o.frontUVs,o.backUVs);const c=new De;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function $h(o,e={},t){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Rx(e).applyToMesh(i,e.updatable),i}De.CreateTorus=Rx;se.CreateTorus=(o,e,t,i,s,r,n)=>$h(o,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);class Em{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=Em._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=$h("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new Oe("targetMat",e);i.specularColor=Te.Black(),i.emissiveColor=new Te(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new Kt(T.Zero(),new T(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()}}Em._IdCounter=0;class c0 extends Em{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Kt(T.Zero(),T.Forward())}}class Jc{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 he,this.onAfterEnteringVRObservable=new he,this.onExitingVRObservable=new he,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Jc.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new T(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new T(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Te(.2,.2,1),this._pickedGazeColor=new Te(0,0,1),this.onNewMeshSelected=new he,this.onNewMeshPicked=new he,this.onBeforeCameraTeleport=new he,this.onAfterCameraTeleport=new he,this.onSelectedMeshUnselected=new he,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!==xr.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===xr.XBOX&&(s.onbuttondown(r=>{this._interactionsEnabled&&r===ia.A&&this._cameraGazer._selectionPointerDown()}),s.onbuttonup(r=>{this._interactionsEnabled&&r===ia.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=T.Zero(),this._workingQuaternion=Se.Identity(),this._workingMatrix=k.Identity(),G.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 T(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Tx("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 Us&&this._scene.activeCamera.rotation)){const s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Se.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?xm.IsSessionSupportedAsync("immersive-vr").then(s=>{s?(G.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 c0(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(n=>{switch(n){case rr.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case rr.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case rr.IN_XR:this._hasEnteredVR=!0;break;case rr.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 Cx("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new c0(()=>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())},rt.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new Fw,this._circleEase.setEasingMode(ln.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(s=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===rt.POINTERDOWN?this._cameraGazer._selectionPointerDown():s.type===rt.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===rr.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){G.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Se.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){G.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===rr.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-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 jt;t.vignetteColor=new Ze(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&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const i=Se.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Se.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),T.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new Kt(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=Tm("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new Id("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 a=new Oe("TextPlaneMaterial",this._scene);a.diffuseTexture=t,this._teleportationTarget.material=a;const l=$h("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const h=new Ee("animationInnerCircle","position.y",30,Ee.ANIMATIONTYPE_FLOAT,Ee.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 mb;u.setEasingMode(ln.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 zn))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=Se.FromRotationMatrix(k.RotationY(Math.PI/4*this._rotationAngle)),i=new Ee("animationRotation","rotationQuaternion",90,Ee.ANIMATIONTYPE_QUATERNION,Ee.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 Ee("animationPP","vignetteWeight",90,Ee.ANIMATIONTYPE_FLOAT,Ee.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 a=new Ee("animationPP2","vignetteStretch",90,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),a.setKeys(l),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),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 zn))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==Jc.TELEPORTATIONMODE_CONSTANTSPEED){s=t;const d=T.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 Ee("animationCameraTeleportation","position",t,Ee.ANIMATIONTYPE_VECTOR3,Ee.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 a=Math.round(s/2),l=new Ee("animationPP","vignetteWeight",t,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:a,value:8}),h.push({frame:s,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l);const c=new Ee("animationPP2","vignetteStretch",t,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:a,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"}}Jc.TELEPORTATIONMODE_CONSTANTTIME=0;Jc.TELEPORTATIONMODE_CONSTANTSPEED=1;const RB=(o,e,t,i)=>!(o.x>t.x+i||t.x-i>e.x||o.y>t.y+i||t.y-i>e.y||o.z>t.z+i||t.z-i>e.z),bc=function(){const o={root:0,found:!1};return function(e,t,i,s){o.root=0,o.found=!1;const r=t*t-4*e*i;if(r<0)return o;const n=Math.sqrt(r);let a=(-t-n)/(2*e),l=(-t+n)/(2*e);if(a>l){const h=l;l=a,a=h}return a>0&&a0&&l=0)}_canDoCollision(e,t,i,s){const r=T.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!RB(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,a){let l,h=!1;t||(t=[]),t[e]||(t[e]=new An(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=T.Dot(c.normal,this._velocity);if(Sm.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/d;let _=(1-u)/d;if(l>_){const g=_;_=l,l=g}if(l>1||_<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,p=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,p=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let _=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p);E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p),E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p),E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex);if(_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),r.addToRef(this._edge,this._collisionPoint))}}if(f){const _=p*p*this._velocitySquaredLength;(!this.collisionFound||_=s){r.copyFrom(e);return}const l=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);const h=n&&n.surroundingMeshes||this._scene.meshes;for(let c=0;cnew IB;class eu{constructor(e,t,i,s=""){var r,n;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new he,this.onErrorObservable=new he,this.onBindObservable=new he,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=is.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=eu._UniqueIdSeed++,this.defines=(r=t.defines)!==null&&r!==void 0?r:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(n=t.entryPoint)!==null&&n!==void 0?n:"main",this._shaderStore=ne.GetShadersStore(this._shaderLanguage),this._shaderRepository=ne.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=ne.GetIncludesShadersStore(this._shaderLanguage);let a;const l=gr()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=l?l.getElementById(e.computeElement):null,a||(a=e.computeElement)):a=e.compute||e;const h={defines:this.defines.split(` +`+u)}}return s}}}th._MaterialPluginClassToMainDefine={};th._MaterialPluginCounter=0;ht.OnEnginesDisposedObservable.add(()=>{SB()});const EB=[];let u0=null;function SB(){EB.length=0,Ie.OnEventObservable.remove(u0),u0=null}class ca{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new th(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){Xe.Clone(()=>e,this)}serialize(){return Xe.Serialize(this)}parse(e,t,i){Xe.Parse(()=>this,e,t,i)}}A([D()],ca.prototype,"name",void 0);A([D()],ca.prototype,"priority",void 0);A([D()],ca.prototype,"resolveIncludes",void 0);A([D()],ca.prototype,"registerForExtraEvents",void 0);class CB extends Wn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Eh extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new CB,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ie.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&this._isEnabled?(Me.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&we.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Me.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&we.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)===null||t===void 0||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}A([Jt("detailTexture"),Ce("_markAllSubMeshesAsTexturesDirty")],Eh.prototype,"texture",void 0);A([D()],Eh.prototype,"diffuseBlendLevel",void 0);A([D()],Eh.prototype,"roughnessBlendLevel",void 0);A([D()],Eh.prototype,"bumpLevel",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Eh.prototype,"normalBlendMethod",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Eh.prototype,"isEnabled",void 0);const dv={effect:null,subMesh:null};class bB extends Wn{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 ep{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 Te(0,0,0),this.diffuseColor=new Te(1,1,1),this.specularColor=new Te(1,1,1),this.emissiveColor=new Te(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 qs(16),this._worldViewProjectionMatrix=k.Zero(),this._globalAmbientColor=new Te(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Eh(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new P_,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===Ie.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ie.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo),t.materialDefines=new bB(this._eventInfo.defineNames));const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();r._needNormals=Me.PrepareDefinesForLights(s,e,r,!0,this._maxSimultaneousLights,this._disableLighting),Me.PrepareDefinesForMultiview(s,r);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Me.PrepareDefinesForPrePass(s,r,this.canRenderToMRT&&!a),Me.PrepareDefinesForOIT(s,r,a),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let h=1;h<=6;++h)r["MAINUV"+h]=!1;if(s.texturesEnabled){if(r.DIFFUSEDIRECTUV=0,r.BUMPDIRECTUV=0,r.AMBIENTDIRECTUV=0,r.OPACITYDIRECTUV=0,r.EMISSIVEDIRECTUV=0,r.SPECULARDIRECTUV=0,r.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&De.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&De.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&De.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&De.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===ee.INVCUBIC_MODE,r.REFLECTIONMAP_3D=this._reflectionTexture.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,r.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case ee.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case ee.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case ee.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case ee.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case ee.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case ee.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case ee.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC");break}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&De.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&De.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&De.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())Me.PrepareDefinesForMergedUV(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&De.BumpTextureEnabled){if(this._bumpTexture.isReady())Me.PrepareDefinesForMergedUV(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAX_RHS=s.useRightHandedSystem,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAX_RHS=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&De.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())r._needUVs=!0,r.REFRACTION=!0,r.REFRACTIONMAP_3D=this._refractionTexture.isCube,r.RGBDREFRACTION=this._refractionTexture.isRGBD,r.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else r.REFRACTION=!1;r.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else r.DIFFUSE=!1,r.AMBIENT=!1,r.OPACITY=!1,r.REFLECTION=!1,r.EMISSIVE=!1,r.LIGHTMAP=!1,r.BUMP=!1,r.REFRACTION=!1;r.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),r.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,r.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,r.SPECULAROVERALPHA=this._useSpecularOverAlpha,r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,r.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(De.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(r.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,r.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,r.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,r.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,r.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,r.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,r._needNormals=!0,r.FRESNEL=!0):r.FRESNEL=!1),Me.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),Me.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Me.PrepareDefinesForAttributes(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(r.isDirty){const h=r._areLightsDisposed;r.markAsProcessed();const c=new ec;r.REFLECTION&&c.addFallback(0,"REFLECTION"),r.SPECULAR&&c.addFallback(0,"SPECULAR"),r.BUMP&&c.addFallback(0,"BUMP"),r.PARALLAX&&c.addFallback(1,"PARALLAX"),r.PARALLAX_RHS&&c.addFallback(1,"PARALLAX_RHS"),r.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&c.addFallback(1,"FOG"),r.POINTSIZE&&c.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),Me.HandleFallbacksForShadows(r,c,this._maxSimultaneousLights),r.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&c.addFallback(4,"FRESNEL"),r.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const u=[P.PositionKind];r.NORMAL&&u.push(P.NormalKind),r.TANGENT&&u.push(P.TangentKind);for(let b=1;b<=6;++b)r["UV"+b]&&u.push(`uv${b===1?"":b}`);r.VERTEXCOLOR&&u.push(P.ColorKind),Me.PrepareAttributesForBones(u,e,r,c),Me.PrepareAttributesForInstances(u,r),Me.PrepareAttributesForMorphTargets(u,e,r),Me.PrepareAttributesForBakedVertexAnimation(u,e,r);let d="default";const f=["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"],_=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=f,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(Lr.PrepareEffect,this._eventInfo),P_.AddUniforms(f),jt&&(jt.PrepareUniforms(f,r),jt.PrepareSamplers(p,r)),Me.PrepareUniformsAndSamplersList({uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),Ao(f);const v={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,f,_,p,r,u,v));const E=r.toString(),C=t.effect;let S=s.getEngine().createEffect(d,{attributes:u,uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:E,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},n);if(this._eventInfo.customCode=void 0,S)if(this._onEffectCreatedObservable&&(dv.effect=S,dv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dv)),this.allowShaderHotSwapping&&C&&!S.isReady()){if(S=C,r.markAsUnprocessed(),l=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(S,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!l,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var s;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=a._forceRebindOnNextCall||this._mustRebind(r,a,t.visibility);Me.BindBonesParameters(t,a);const h=this._uniformBuffer;if(l){if(this.bindViewProjection(a),!h.useUbo||!this.isFrozen||!h.isSync||a._forceRebindOnNextCall){if(De.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new Te(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&De.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Me.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&De.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Me.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&De.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Me.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&De.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;h.updateVector3("vReflectionPosition",c.boundingBoxPosition),h.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&De.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Me.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&De.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Me.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&De.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Me.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&De.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Me.BindTextureMatrix(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&De.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;h.updateVector3("vRefractionPosition",u.boundingBoxPosition),h.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",De.EmissiveTextureEnabled?this.emissiveColor:Te.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&De.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&De.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&De.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&De.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&De.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&De.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&De.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&De.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&De.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),so(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Me.BindLights(r,t,a,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==Qe.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),Me.BindFogParameters(r,t,a),n.NUM_MORPH_INFLUENCERS&&Me.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((s=t.bakedVertexAnimationManager)===null||s===void 0||s.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&Me.BindLogDepth(n,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,s,r,n,a,l,h,c,u;t&&((i=this._diffuseTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(a=this._emissiveTexture)===null||a===void 0||a.dispose(),(l=this._specularTexture)===null||l===void 0||l.dispose(),(h=this._bumpTexture)===null||h===void 0||h.dispose(),(c=this._lightmapTexture)===null||c===void 0||c.dispose(),(u=this._refractionTexture)===null||u===void 0||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Xe.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=Xe.Parse(()=>new De(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ie._parsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return we.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){we.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return we.DetailTextureEnabled}static set DetailTextureEnabled(e){we.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return we.AmbientTextureEnabled}static set AmbientTextureEnabled(e){we.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return we.OpacityTextureEnabled}static set OpacityTextureEnabled(e){we.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return we.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){we.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return we.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){we.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return we.SpecularTextureEnabled}static set SpecularTextureEnabled(e){we.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return we.BumpTextureEnabled}static set BumpTextureEnabled(e){we.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return we.LightmapTextureEnabled}static set LightmapTextureEnabled(e){we.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return we.RefractionTextureEnabled}static set RefractionTextureEnabled(e){we.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return we.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){we.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return we.FresnelEnabled}static set FresnelEnabled(e){we.FresnelEnabled=e}}A([Jt("diffuseTexture")],De.prototype,"_diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],De.prototype,"diffuseTexture",void 0);A([Jt("ambientTexture")],De.prototype,"_ambientTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"ambientTexture",void 0);A([Jt("opacityTexture")],De.prototype,"_opacityTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],De.prototype,"opacityTexture",void 0);A([Jt("reflectionTexture")],De.prototype,"_reflectionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"reflectionTexture",void 0);A([Jt("emissiveTexture")],De.prototype,"_emissiveTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"emissiveTexture",void 0);A([Jt("specularTexture")],De.prototype,"_specularTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"specularTexture",void 0);A([Jt("bumpTexture")],De.prototype,"_bumpTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"bumpTexture",void 0);A([Jt("lightmapTexture")],De.prototype,"_lightmapTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"lightmapTexture",void 0);A([Jt("refractionTexture")],De.prototype,"_refractionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"refractionTexture",void 0);A([ds("ambient")],De.prototype,"ambientColor",void 0);A([ds("diffuse")],De.prototype,"diffuseColor",void 0);A([ds("specular")],De.prototype,"specularColor",void 0);A([ds("emissive")],De.prototype,"emissiveColor",void 0);A([D()],De.prototype,"specularPower",void 0);A([D("useAlphaFromDiffuseTexture")],De.prototype,"_useAlphaFromDiffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],De.prototype,"useAlphaFromDiffuseTexture",void 0);A([D("useEmissiveAsIllumination")],De.prototype,"_useEmissiveAsIllumination",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useEmissiveAsIllumination",void 0);A([D("linkEmissiveWithDiffuse")],De.prototype,"_linkEmissiveWithDiffuse",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"linkEmissiveWithDiffuse",void 0);A([D("useSpecularOverAlpha")],De.prototype,"_useSpecularOverAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useSpecularOverAlpha",void 0);A([D("useReflectionOverAlpha")],De.prototype,"_useReflectionOverAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useReflectionOverAlpha",void 0);A([D("disableLighting")],De.prototype,"_disableLighting",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],De.prototype,"disableLighting",void 0);A([D("useObjectSpaceNormalMap")],De.prototype,"_useObjectSpaceNormalMap",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useObjectSpaceNormalMap",void 0);A([D("useParallax")],De.prototype,"_useParallax",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useParallax",void 0);A([D("useParallaxOcclusion")],De.prototype,"_useParallaxOcclusion",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useParallaxOcclusion",void 0);A([D()],De.prototype,"parallaxScaleBias",void 0);A([D("roughness")],De.prototype,"_roughness",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"roughness",void 0);A([D()],De.prototype,"indexOfRefraction",void 0);A([D()],De.prototype,"invertRefractionY",void 0);A([D()],De.prototype,"alphaCutOff",void 0);A([D("useLightmapAsShadowmap")],De.prototype,"_useLightmapAsShadowmap",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useLightmapAsShadowmap",void 0);A([jf("diffuseFresnelParameters")],De.prototype,"_diffuseFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],De.prototype,"diffuseFresnelParameters",void 0);A([jf("opacityFresnelParameters")],De.prototype,"_opacityFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelAndMiscDirty")],De.prototype,"opacityFresnelParameters",void 0);A([jf("reflectionFresnelParameters")],De.prototype,"_reflectionFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],De.prototype,"reflectionFresnelParameters",void 0);A([jf("refractionFresnelParameters")],De.prototype,"_refractionFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],De.prototype,"refractionFresnelParameters",void 0);A([jf("emissiveFresnelParameters")],De.prototype,"_emissiveFresnelParameters",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],De.prototype,"emissiveFresnelParameters",void 0);A([D("useReflectionFresnelFromSpecular")],De.prototype,"_useReflectionFresnelFromSpecular",void 0);A([Ce("_markAllSubMeshesAsFresnelDirty")],De.prototype,"useReflectionFresnelFromSpecular",void 0);A([D("useGlossinessFromSpecularMapAlpha")],De.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"useGlossinessFromSpecularMapAlpha",void 0);A([D("maxSimultaneousLights")],De.prototype,"_maxSimultaneousLights",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],De.prototype,"maxSimultaneousLights",void 0);A([D("invertNormalMapX")],De.prototype,"_invertNormalMapX",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"invertNormalMapX",void 0);A([D("invertNormalMapY")],De.prototype,"_invertNormalMapY",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"invertNormalMapY",void 0);A([D("twoSidedLighting")],De.prototype,"_twoSidedLighting",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],De.prototype,"twoSidedLighting",void 0);A([D("applyDecalMapAfterDetailMap")],De.prototype,"_applyDecalMapAfterDetailMap",void 0);A([Ce("_markAllSubMeshesAsMiscDirty")],De.prototype,"applyDecalMapAfterDetailMap",void 0);j("BABYLON.StandardMaterial",De);Qe.DefaultMaterialFactory=o=>new De("default material",o);We.prototype.createDynamicTexture=function(o,e,t,i){const s=new Ti(this,Ut.Dynamic);return s.baseWidth=o,s.baseHeight=e,t&&(o=this.needPOTTextures?We.GetExponentOfTwo(o,this._caps.maxTextureSize):o,e=this.needPOTTextures?We.GetExponentOfTwo(e,this._caps.maxTextureSize):e),s.width=o,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};We.prototype.updateDynamicTexture=function(o,e,t,i=!1,s,r=!1,n=!1){if(!o)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,o,!0,r);this._unpackFlipY(t===void 0?o.invertY:t),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(o.type),u=this._getInternalFormat(s||o.format),d=this._getRGBABufferInternalSizedFormat(o.type,u);a.texImage2D(l,0,d,u,c,e),o.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(o.format=s),o._dynamicTextureSource=e,o._premulAlpha=i,o.invertY=t||!1,o.isReady=!0};class Pd extends ee{constructor(e,t,i=null,s=!1,r=3,n=5,a){super(null,i,!s,a,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._texture=l.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=l.createCanvas(1,1),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,a,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(a)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Pd(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()&&G.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Pd._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 Ax{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}}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.createRenderTargetTextureProvider=r}}class Rx{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Ti(this._engine,Ut.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new uu(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 a={width:e,height:t},l=n?new Vv(this._scene,a):new ms("XR renderTargetTexture",a,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(a,s);h.setTexture(c,0),l._texture=c}return r&&(n?h._depthStencilTextureArray=r:h._depthStencilTexture=this._createInternalTexture(a,r)),l.disableRescaling(),typeof XRWebGLBinding<"u"&&(l.skipInitialClear=!0),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 Ix extends Ax{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new yB(t.scene,this)),this.layer=e}}class yB extends Rx{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 vm{static GetDefaults(e){const t=new vm;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 AB{constructor(e,t=vm.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new he,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 Ix(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{fe.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 RB extends Ax{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new IB(t,this)),this.layer=e}}class IB extends Rx{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 PB{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 xm{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new he,this.onXRReferenceSpaceChanged=new he,this.onXRSessionEnded=new he,this.onXRSessionInit=new he,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),(e=this._engine)===null||e===void 0||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{G.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return((i=this._baseLayerRTTProvider)===null||i===void 0?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return((t=this._baseLayerRTTProvider)===null||t===void 0?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new PB(this):(e=e||vm.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new AB(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.onXRSessionInit.notifyObservers(i),this.inXRSession=!0,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===void 0||s.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return xm.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;!this.inXRSession||!this._engine||(this.currentFrame=i,this.currentTimestamp=t,i&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=((s=this._baseLayerRTTProvider)===null||s===void 0?void 0:s.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(i),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=((e=this._baseLayerRTTProvider)===null||e===void 0?void 0:e.getFramebufferDimensions())||null,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=>(G.Error("XR.requestReferenceSpace failed for the following reason: "),G.Error(t),G.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 G.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.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&((t=this._baseLayerRTTProvider)===null||t===void 0||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=((i=this._baseLayerWrapper)===null||i===void 0?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new RB(e.baseLayer):new Ix(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=>(G.Warn(i),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return(e=this._xrNavigator.xr.native)!==null&&e!==void 0?e:!1}get currentFrameRate(){var e;return(e=this.session)===null||e===void 0?void 0:e.frameRate}get supportedFrameRates(){var e;return(e=this.session)===null||e===void 0?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||e===void 0?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return((e=this._baseLayerWrapper)===null||e===void 0?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,t;return(t=(e=this.session)===null||e===void 0?void 0:e.enabledFeatures)!==null&&t!==void 0?t:null}}var rr;(function(o){o[o.ENTERING_XR=0]="ENTERING_XR",o[o.EXITING_XR=1]="EXITING_XR",o[o.IN_XR=2]="IN_XR",o[o.NOT_IN_XR=3]="NOT_IN_XR"})(rr||(rr={}));var Oc;(function(o){o[o.NOT_TRACKING=0]="NOT_TRACKING",o[o.TRACKING_LOST=1]="TRACKING_LOST",o[o.TRACKING=2]="TRACKING"})(Oc||(Oc={}));se._GroundMeshParser=(o,e)=>rp.Parse(o,e);class rp extends se{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=K.Matrix[5];i.invertToRef(s);const r=K.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return T.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new T(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=K.Matrix[5];s.invertToRef(r);const n=K.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return T.TransformNormalFromFloatsToRef(a.x,a.y,a.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 to.maxHeight){h=!0;const u=o.maxHeight;o.maxHeight=o.minHeight,o.minHeight=u}for(r=0;r<=o.subdivisions;r++)for(n=0;n<=o.subdivisions;n++){const u=new T(n*o.width/o.subdivisions-o.width/2,0,(o.subdivisions-r)*o.height/o.subdivisions-o.height/2),d=(u.x+o.width/2)/o.width*(o.bufferWidth-1)|0,f=(1-(u.z+o.height/2)/o.height)*(o.bufferHeight-1)|0,p=(d+f*o.bufferWidth)*4;let _=o.buffer[p]/255,g=o.buffer[p+1]/255,v=o.buffer[p+2]/255;const E=o.buffer[p+3]/255;h&&(_=1-_,g=1-g,v=1-v);const C=_*a.r+g*a.g+v*a.b;E>=l?u.y=o.minHeight+(o.maxHeight-o.minHeight)*C:u.y=o.minHeight-$t,t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/o.subdivisions,1-r/o.subdivisions)}for(r=0;r=o.minHeight,g=t[d*3+1]>=o.minHeight,v=t[f*3+1]>=o.minHeight;_&&g&&v&&(e.push(u),e.push(d),e.push(f)),t[p*3+1]>=o.minHeight&&_&&v&&(e.push(p),e.push(u),e.push(f))}Oe.ComputeNormals(t,e,i);const c=new Oe;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Tm(o,e={},t){const i=new rp(o,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,xl(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function zb(o,e,t=null){const i=new se(o,t);return kb(e).applyToMesh(i,e.updatable),i}function Wb(o,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,a=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new Te(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||ht.LastCreatedScene;const f=new rp(o,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);const p=(_,g,v)=>{Gb({width:s,height:r,subdivisions:n,minHeight:a,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:g,bufferHeight:v,alphaFilter:c}).applyToMesh(f,u),d&&d(f),f._setReady(!0)};if(typeof e=="string"){const _=g=>{const v=g.width,E=g.height;if(i.isDisposed)return;const C=i==null?void 0:i.getEngine().resizeImageBitmap(g,v,E);p(C,v,E)};fe.LoadImage(e,_,t.onError?t.onError:()=>{},i.offlineProvider)}else p(e.data,e.width,e.height);return f}Oe.CreateGround=xl;Oe.CreateTiledGround=kb;Oe.CreateGroundFromHeightMap=Gb;se.CreateGround=(o,e,t,i,s,r)=>Tm(o,{width:e,height:t,subdivisions:i,updatable:r},s);se.CreateTiledGround=(o,e,t,i,s,r,n,a,l)=>zb(o,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:l},a);se.CreateGroundFromHeightMap=(o,e,t,i,s,r,n,a,l,h,c)=>Wb(o,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},a);function Px(o){const e=[],t=[],i=[],s=[],r=o.diameter||1,n=o.thickness||.5,a=(o.tessellation||16)|0,l=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,h=a+1;for(let u=0;u<=a;u++){const d=u/a,f=u*Math.PI*2/a-Math.PI/2,p=k.Translation(r/2,0,0).multiply(k.RotationY(f));for(let _=0;_<=a;_++){const g=1-_/a,v=_*Math.PI*2/a+Math.PI,E=Math.cos(v),C=Math.sin(v);let S=new T(E,C,0),b=S.scale(n/2);const R=new Re(d,g);b=T.TransformCoordinates(b,p),S=T.TransformNormal(S,p),t.push(b.x,b.y,b.z),i.push(S.x,S.y,S.z),s.push(R.x,pi.UseOpenGLOrientationForUV?1-R.y:R.y);const I=(u+1)%h,N=(_+1)%h;e.push(u*h+_),e.push(u*h+N),e.push(I*h+_),e.push(u*h+N),e.push(I*h+N),e.push(I*h+_)}}Oe._ComputeSides(l,t,e,i,s,o.frontUVs,o.backUVs);const c=new Oe;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Kh(o,e={},t){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Px(e).applyToMesh(i,e.updatable),i}Oe.CreateTorus=Px;se.CreateTorus=(o,e,t,i,s,r,n)=>Kh(o,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);class Em{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=Em._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Kh("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=Te.Black(),i.emissiveColor=new Te(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new Kt(T.Zero(),new T(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()}}Em._IdCounter=0;class d0 extends Em{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Kt(T.Zero(),T.Forward())}}class Jc{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 he,this.onAfterEnteringVRObservable=new he,this.onExitingVRObservable=new he,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Jc.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new T(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new T(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Te(.2,.2,1),this._pickedGazeColor=new Te(0,0,1),this.onNewMeshSelected=new he,this.onNewMeshPicked=new he,this.onBeforeCameraTeleport=new he,this.onAfterCameraTeleport=new he,this.onSelectedMeshUnselected=new he,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!==xr.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===xr.XBOX&&(s.onbuttondown(r=>{this._interactionsEnabled&&r===ia.A&&this._cameraGazer._selectionPointerDown()}),s.onbuttonup(r=>{this._interactionsEnabled&&r===ia.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=T.Zero(),this._workingQuaternion=Se.Identity(),this._workingMatrix=k.Identity(),G.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 T(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Sx("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 Us&&this._scene.activeCamera.rotation)){const s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Se.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?xm.IsSessionSupportedAsync("immersive-vr").then(s=>{s?(G.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 d0(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(n=>{switch(n){case rr.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case rr.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case rr.IN_XR:this._hasEnteredVR=!0;break;case rr.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 yx("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new d0(()=>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())},rt.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new Vw,this._circleEase.setEasingMode(ln.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(s=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===rt.POINTERDOWN?this._cameraGazer._selectionPointerDown():s.type===rt.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===rr.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){G.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Se.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){G.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===rr.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-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 jt;t.vignetteColor=new Ze(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&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const i=Se.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Se.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),T.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new Kt(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=Tm("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new Pd("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 a=new De("TextPlaneMaterial",this._scene);a.diffuseTexture=t,this._teleportationTarget.material=a;const l=Kh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const h=new Ee("animationInnerCircle","position.y",30,Ee.ANIMATIONTYPE_FLOAT,Ee.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 vb;u.setEasingMode(ln.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 zn))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=Se.FromRotationMatrix(k.RotationY(Math.PI/4*this._rotationAngle)),i=new Ee("animationRotation","rotationQuaternion",90,Ee.ANIMATIONTYPE_QUATERNION,Ee.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 Ee("animationPP","vignetteWeight",90,Ee.ANIMATIONTYPE_FLOAT,Ee.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 a=new Ee("animationPP2","vignetteStretch",90,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),a.setKeys(l),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),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 zn))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==Jc.TELEPORTATIONMODE_CONSTANTSPEED){s=t;const d=T.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 Ee("animationCameraTeleportation","position",t,Ee.ANIMATIONTYPE_VECTOR3,Ee.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 a=Math.round(s/2),l=new Ee("animationPP","vignetteWeight",t,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:a,value:8}),h.push({frame:s,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l);const c=new Ee("animationPP2","vignetteStretch",t,Ee.ANIMATIONTYPE_FLOAT,Ee.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:a,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"}}Jc.TELEPORTATIONMODE_CONSTANTTIME=0;Jc.TELEPORTATIONMODE_CONSTANTSPEED=1;const MB=(o,e,t,i)=>!(o.x>t.x+i||t.x-i>e.x||o.y>t.y+i||t.y-i>e.y||o.z>t.z+i||t.z-i>e.z),bc=function(){const o={root:0,found:!1};return function(e,t,i,s){o.root=0,o.found=!1;const r=t*t-4*e*i;if(r<0)return o;const n=Math.sqrt(r);let a=(-t-n)/(2*e),l=(-t+n)/(2*e);if(a>l){const h=l;l=a,a=h}return a>0&&a0&&l=0)}_canDoCollision(e,t,i,s){const r=T.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!MB(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,a){let l,h=!1;t||(t=[]),t[e]||(t[e]=new Rn(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=T.Dot(c.normal,this._velocity);if(Sm.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/d;let _=(1-u)/d;if(l>_){const g=_;_=l,l=g}if(l>1||_<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,p=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,p=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let _=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p);E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p),E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),g=2*T.Dot(this._velocity,this._tempVector),v=this._tempVector.lengthSquared()-1,E=bc(_,g,v,p),E.found&&(p=E.root,f=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex);if(_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),S=T.Dot(this._edge,this._velocity),b=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+S*S,g=2*(C*T.Dot(this._velocity,this._baseToVertex)-S*b),v=C*(1-this._baseToVertex.lengthSquared())+b*b,E=bc(_,g,v,p),E.found){const R=(S*E.root-b)/C;R>=0&&R<=1&&(p=E.root,f=!0,this._edge.scaleInPlace(R),r.addToRef(this._edge,this._collisionPoint))}}if(f){const _=p*p*this._velocitySquaredLength;(!this.collisionFound||_=s){r.copyFrom(e);return}const l=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);const h=n&&n.surroundingMeshes||this._scene.meshes;for(let c=0;cnew DB;class eu{constructor(e,t,i,s=""){var r,n;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new he,this.onErrorObservable=new he,this.onBindObservable=new he,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=is.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=eu._UniqueIdSeed++,this.defines=(r=t.defines)!==null&&r!==void 0?r:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(n=t.entryPoint)!==null&&n!==void 0?n:"main",this._shaderStore=ne.GetShadersStore(this._shaderLanguage),this._shaderRepository=ne.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=ne.GetIncludesShadersStore(this._shaderLanguage);let a;const l=gr()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=l?l.getElementById(e.computeElement):null,a||(a=e.computeElement)):a=e.compute||e;const h={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(a,"Compute","",c=>{Ia.Initialize(h),Ia.PreProcess(c,h,u=>{this._rawComputeSourceCode=c,t.processFinalCode&&(u=t.processFinalCode(u));const d=Ia.Finalize(u,"",h);this._useFinalCode(d.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=nx(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,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getComputeShaderCode())!==null&&t!==void 0?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{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]),a=e.split(` +`+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=ox(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,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:(t=(e=this._pipelineContext)===null||e===void 0?void 0:e._getComputeShaderCode())!==null&&t!==void 0?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{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]),a=e.split(` `,-1);a.length>=n&&(s=`Offending line [${n}] in compute code: ${a[n-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,G.Error("Unable to compile compute effect:"),G.Error(`Defines: -`+this.defines),eu.LogShaderCodeOnCompilationError){let s=null,r=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getComputeShaderCode()&&([r,s]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),r&&(G.Error("Compute code:"),G.Error(r))),s&&G.Error(s)}G.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){ne.GetShadersStore(is.WGSL)[`${e}ComputeShader`]=t}}eu._UniqueIdSeed=0;eu.LogShaderCodeOnCompilationError=!0;var ns;(function(o){o[o.Texture=0]="Texture",o[o.StorageTexture=1]="StorageTexture",o[o.UniformBuffer=2]="UniformBuffer",o[o.StorageBuffer=3]="StorageBuffer",o[o.TextureWithoutSampler=4]="TextureWithoutSampler",o[o.Sampler=5]="Sampler",o[o.ExternalTexture=6]="ExternalTexture"})(ns||(ns={}));We.prototype.createComputeEffect=function(o,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};We.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};We.prototype.createComputeContext=function(){};We.prototype.computeDispatch=function(o,e,t,i,s,r,n){throw new Error("computeDispatch: This engine does not support compute shaders!")};We.prototype.areAllComputeEffectsReady=function(){return!0};We.prototype.releaseComputeEffects=function(){};We.prototype._prepareComputePipelineContext=function(o,e,t,i,s){};We.prototype._rebuildComputeEffects=function(){};We.prototype._executeWhenComputeStateIsCompiled=function(o,e){e()};We.prototype._releaseComputeEffect=function(o){};We.prototype._deleteComputePipelineContext=function(o){};class Ix{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Pa}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()})}serialize(){const e=Xe.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 ns.Texture:case ns.TextureWithoutSampler:case ns.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case ns.UniformBuffer:break}}return e}static Parse(e,t,i){const s=Xe.Parse(()=>new gu(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const r in e.textures){const n=e.bindings[r],a=ee.Parse(e.textures[r],t,i);n.type===ns.Texture?s.setTexture(r,a):n.type===ns.TextureWithoutSampler?s.setTexture(r,a,!1):s.setStorageTexture(r,a)}return s}}A([D()],gu.prototype,"name",void 0);A([D()],gu.prototype,"fastMode",void 0);j("BABYLON.ComputeShader",gu);class M_{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;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const t=o.getBoundingInfo();!o.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(o)};tu.CreationFuncForSubMeshes=(o,e)=>{o.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(o)};Qe.prototype.createOrUpdateSelectionOctree=function(o=64,e=2){let t=this._getComponent(Fe.NAME_OCTREE);t||(t=new zb(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new tu(tu.CreationFuncForMeshes,o,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(Qe.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});hi.prototype.createOrUpdateSubmeshesOctree=function(o=64,e=2){const t=this.getScene();let i=t._getComponent(Fe.NAME_OCTREE);i||(i=new zb(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new tu(tu.CreationFuncForSubMeshes,o,e)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class zb{constructor(e){this.name=Fe.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Kt(T.Zero(),new T(1,1,1)),e=e||ht.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||e===void 0?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?(Kt.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 Px(o){const e=o.height||2;let t=o.diameterTop===0?0:o.diameterTop||o.diameter||1,i=o.diameterBottom===0?0:o.diameterBottom||o.diameter||1;t=t||1e-5,i=i||1e-5;const s=(o.tessellation||24)|0,r=(o.subdivisions||1)|0,n=!!o.hasRings,a=!!o.enclose,l=o.cap===0?0:o.cap||se.CAP_ALL,h=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,c=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,u=o.faceUV||new Array(3),d=o.faceColors,f=h!==1&&a?2:0,p=n?r:1,_=2+(1+f)*p;let g;for(g=0;g<_;g++)d&&d[g]===void 0&&(d[g]=new Ze(1,1,1,1));for(g=0;g<_;g++)u&&u[g]===void 0&&(u[g]=new Dt(0,0,1,1));const v=[],E=[],C=[],S=[],b=[],R=Math.PI*2*h/s;let I,N,O;const L=(i-t)/2/e,B=T.Zero(),V=T.Zero(),Z=T.Zero(),ue=T.Zero(),oe=T.Zero(),me=an.Y;let le,ae,ce,ie=1,w=1,H=0,X=0;for(le=0;le<=r;le++)for(N=le/r,O=(N*(t-i)+i)/2,ie=n&&le!==0&&le!==r?2:1,ce=0;ce{const de=q?t/2:i/2;if(de===0)return;let ge,ve,be;const Le=q?u[_-1]:u[0];let Ye=null;d&&(Ye=q?d[_-1]:d[0]);const He=E.length/3,Be=q?e/2:-e/2,Ge=new T(0,Be,0);E.push(Ge.x,Ge.y,Ge.z),C.push(0,q?1:-1,0);const Lt=Le.y+(Le.w-Le.y)*.5;S.push(Le.x+(Le.z-Le.x)*.5,pi.UseOpenGLOrientationForUV?1-Lt:Lt),Ye&&b.push(Ye.r,Ye.g,Ye.b,Ye.a);const Mt=new Re(.5,.5);for(be=0;be<=s;be++){ge=Math.PI*2*be*h/s;const Vi=Math.cos(-ge),at=Math.sin(-ge);ve=new T(Vi*de,Be,at*de);const ei=new Re(Vi*Mt.x+.5,at*Mt.y+.5);E.push(ve.x,ve.y,ve.z),C.push(0,q?1:-1,0);const di=Le.y+(Le.w-Le.y)*ei.y;S.push(Le.x+(Le.z-Le.x)*ei.x,pi.UseOpenGLOrientationForUV?1-di:di),Ye&&b.push(Ye.r,Ye.g,Ye.b,Ye.a)}for(be=0;be((n===void 0||!(n instanceof Qe))&&(n!==void 0&&(l=a||se.DEFAULTSIDE,a=n),n=r,r=1),Cm(o,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:l,updatable:a},n));Mi.AddNodeConstructor("Light_Type_3",(o,e)=>()=>new np(o,T.Zero(),e));class np extends Yt{constructor(e,t,i){super(e,i),this.groundColor=new Te(0,0,0),this.direction=t||T.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=T.Normalize(e.subtract(T.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=T.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=T.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=k.Identity()),this._worldMatrix}getTypeID(){return Yt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}A([ds()],np.prototype,"groundColor",void 0);A([kr()],np.prototype,"direction",void 0);class zs{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 np("shared gizmo light",new T(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Te.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return zs._DefaultUtilityLayer==null?zs._CreateDefaultUtilityLayerFromScene(ht.LastCreatedScene):zs._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return zs._DefaultUtilityLayer=new zs(e),zs._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zs._DefaultUtilityLayer=null}),zs._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return zs._DefaultKeepDepthUtilityLayer==null&&(zs._DefaultKeepDepthUtilityLayer=new zs(ht.LastCreatedScene),zs._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,zs._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zs._DefaultKeepDepthUtilityLayer=null})),zs._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 he,this.utilityLayerScene=new Qe(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!==rt.POINTERMOVE&&i.type!==rt.POINTERUP&&i.type!==rt.POINTERDOWN&&i.type!==rt.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=a=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==a?l=i.nearInteractionPickingInfo:l=new Vr;else if(a!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let h=null;this._renderCamera&&(h=a._activeCamera,a._activeCamera=this._renderCamera,i.ray=null),l=i.ray?a.pickWithRay(i.ray):a.pick(e.pointerX,e.pointerY),h&&(a._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!=rt.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Ja(i.type,i.event,n),i.type),i.type===rt.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 Ja(i.type,i.event,n),i.type),i.skipOnPointerObservable=!0);else{const a=r(e),l=i.event;a&&n&&(n.distance===0&&a.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(a.pickedMesh)?(this._notifyObservers(i,a,l),i.skipOnPointerObservable=!0):i.type===rt.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===rt.POINTERMOVE||i.type===rt.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,a,l)):!this._pointerCaptures[l.pointerId]&&(n.distance0)):!this._pointerCaptures[l.pointerId]&&n.distance>=a.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(a.pickedMesh)?(this._notifyObservers(i,a,l),i.skipOnPointerObservable=!0):((i.type===rt.POINTERMOVE||i.type===rt.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,n,l))),i.type===rt.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 Ja(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()}}zs._DefaultUtilityLayer=null;zs._DefaultKeepDepthUtilityLayer=null;var u0;(function(o){o[o.Origin=0]="Origin",o[o.Pivot=1]="Pivot"})(u0||(u0={}));var d0;(function(o){o[o.World=0]="World",o[o.Local=1]="Local"})(d0||(d0={}));Object.defineProperty(Qe.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new iu(this)),this._debugLayer},enumerable:!0,configurable:!0});var f0;(function(o){o[o.Properties=0]="Properties",o[o.Debug=1]="Debug",o[o.Statistics=2]="Statistics",o[o.Tools=3]="Tools",o[o.Settings=4]="Settings"})(f0||(f0={}));class iu{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new he),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new he),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||ht.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=Object.assign(Object.assign({},iu.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:iu.InspectorURL;fe.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}iu.InspectorURL=`${fe._DefaultCdnUrl}/v${re.Version}/inspector/babylon.inspector.bundle.js`;iu.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function Mx(o){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=o.width||o.size||1,a=o.height||o.size||1,l=o.depth||o.size||1,h=o.wrap||!1;let c=o.topBaseAt===void 0?1:o.topBaseAt,u=o.bottomBaseAt===void 0?0:o.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let p=d[c],_=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 I=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],N=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const O=[17,18,19,16],L=[22,23,20,21];for(;p>0;)I.unshift(I.pop()),O.unshift(O.pop()),p--;for(;_>0;)N.unshift(N.pop()),L.unshift(L.pop()),_--;I=I.flat(),N=N.flat(),g=g.concat(I).concat(N),t.push(O[0],O[2],O[3],O[0],O[1],O[2]),t.push(L[0],L[2],L[3],L[0],L[1],L[2])}const v=[n/2,a/2,l/2];r=g.reduce((I,N,O)=>I.concat(N*v[O%3]),[]);const E=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,C=o.faceUV||new Array(6),S=o.faceColors,b=[];for(let I=0;I<6;I++)C[I]===void 0&&(C[I]=new Dt(0,0,1,1)),S&&S[I]===void 0&&(S[I]=new Ze(1,1,1,1));for(let I=0;I<6;I++)if(s.push(C[I].z,pi.UseOpenGLOrientationForUV?1-C[I].w:C[I].w),s.push(C[I].x,pi.UseOpenGLOrientationForUV?1-C[I].w:C[I].w),s.push(C[I].x,pi.UseOpenGLOrientationForUV?1-C[I].y:C[I].y),s.push(C[I].z,pi.UseOpenGLOrientationForUV?1-C[I].y:C[I].y),S)for(let N=0;N<4;N++)b.push(S[I].r,S[I].g,S[I].b,S[I].a);De._ComputeSides(E,r,t,i,s,o.frontUVs,o.backUVs);const R=new De;if(R.indices=t,R.positions=r,R.normals=i,R.uvs=s,S){const I=E===De.DOUBLESIDE?b.concat(b):b;R.colors=I}return R}function PB(o){const e=o.width||o.size||1,t=o.height||o.size||1,i=o.depth||o.size||1,s=(o.widthSegments||o.segments||1)|0,r=(o.heightSegments||o.segments||1)|0,n=(o.depthSegments||o.segments||1)|0,a=new k,l=new k,h=new k,c=xl({width:e,height:i,subdivisionsX:s,subdivisionsY:n});k.TranslationToRef(0,-t/2,0,l),k.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=xl({width:e,height:i,subdivisionsX:s,subdivisionsY:n});k.TranslationToRef(0,t/2,0,h),u.transform(h);const d=xl({width:t,height:i,subdivisionsX:r,subdivisionsY:n});k.TranslationToRef(-e/2,0,0,l),k.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const f=xl({width:t,height:i,subdivisionsX:r,subdivisionsY:n});k.TranslationToRef(e/2,0,0,l),k.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const p=xl({width:e,height:t,subdivisionsX:s,subdivisionsY:r});k.TranslationToRef(0,0,-i/2,l),k.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const _=xl({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return k.TranslationToRef(0,0,i/2,l),k.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,f,d,p,_],!0),c}function bm(o,e={},t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Mx(e).applyToMesh(i,e.updatable),i}De.CreateBox=Mx;se.CreateBox=(o,e,t=null,i,s)=>bm(o,{size:e,sideOrientation:s,updatable:i},t);function Dx(o){const e=(o.segments||32)|0,t=o.diameterX||o.diameter||1,i=o.diameterY||o.diameter||1,s=o.diameterZ||o.diameter||1,r=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,n=o.slice&&o.slice<=0?1:o.slice||1,a=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,l=!!o.dedupTopBottomIndices,h=new T(t/2,i/2,s/2),c=2+e,u=2*c,d=[],f=[],p=[],_=[];for(let v=0;v<=c;v++){const E=v/c,C=E*Math.PI*n;for(let S=0;S<=u;S++){const b=S/u,R=b*Math.PI*2*r,I=k.RotationZ(-C),N=k.RotationY(R),O=T.TransformCoordinates(T.Up(),I),L=T.TransformCoordinates(O,N),B=L.multiply(h),V=L.divide(h).normalize();f.push(B.x,B.y,B.z),p.push(V.x,V.y,V.z),_.push(b,pi.UseOpenGLOrientationForUV?1-E:E)}if(v>0){const S=f.length/3;for(let b=S-2*(u+1);b+u+21&&(d.push(b),d.push(b+1),d.push(b+u+1)),(vQo(o,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function Ox(o={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(o.subdivisions?o.subdivisions:2,1)|0,t=Math.max(o.tessellation?o.tessellation:16,3)|0,i=Math.max(o.height?o.height:1,0),s=Math.max(o.radius?o.radius:.25,0),r=Math.max(o.capSubdivisions?o.capSubdivisions:6,1)|0,n=t,a=e,l=Math.max(o.radiusTop?o.radiusTop:s,0),h=Math.max(o.radiusBottom?o.radiusBottom:s,0),c=i-(l+h),u=0,d=2*Math.PI,f=Math.max(o.topCapSubdivisions?o.topCapSubdivisions:r,1),p=Math.max(o.bottomCapSubdivisions?o.bottomCapSubdivisions:r,1),_=Math.acos((h-l)/i);let g=[];const v=[],E=[],C=[];let S=0;const b=[],R=c*.5,I=Math.PI*.5;let N,O;const L=T.Zero(),B=T.Zero(),V=Math.cos(_),Z=Math.sin(_),ue=new Re(l*Z,R+l*V).subtract(new Re(h*Z,-R+h*V)).length(),oe=l*_+ue+h*(I-_);let me=0;for(O=0;O<=f;O++){const ie=[],w=I-_*(O/f);me+=l*_/f;const H=Math.cos(w),X=Math.sin(w),te=H*l;for(N=0;N<=n;N++){const Q=N/n,_e=Q*d+u,q=Math.sin(_e),de=Math.cos(_e);B.x=te*q,B.y=R+X*l,B.z=te*de,v.push(B.x,B.y,B.z),L.set(H*q,X,H*de),E.push(L.x,L.y,L.z),C.push(Q,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}const le=i-l-h+V*l-V*h,ae=Z*(h-l)/le;for(O=1;O<=a;O++){const ie=[];me+=ue/a;const w=Z*(O*(h-l)/a+l);for(N=0;N<=n;N++){const H=N/n,X=H*d+u,te=Math.sin(X),Q=Math.cos(X);B.x=w*te,B.y=R+V*l-O*le/a,B.z=w*Q,v.push(B.x,B.y,B.z),L.set(te,ae,Q).normalize(),E.push(L.x,L.y,L.z),C.push(H,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}for(O=1;O<=p;O++){const ie=[],w=I-_-(Math.PI-_)*(O/p);me+=h*_/p;const H=Math.cos(w),X=Math.sin(w),te=H*h;for(N=0;N<=n;N++){const Q=N/n,_e=Q*d+u,q=Math.sin(_e),de=Math.cos(_e);B.x=te*q,B.y=-R+X*h,B.z=te*de,v.push(B.x,B.y,B.z),L.set(H*q,X,H*de),E.push(L.x,L.y,L.z),C.push(Q,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}for(N=0;NWb(o,e,t);De.CreateCapsule=Ox;function Hb(o){let e=o.pathArray;const t=o.closeArray||!1,i=o.closePath||!1,s=o.invertUV||!1,r=Math.floor(e[0].length/2);let n=o.offset||r;n=n>r?r:Math.floor(n);const a=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,l=o.uvs,h=o.colors,c=[],u=[],d=[],f=[],p=[],_=[],g=[],v=[];let E;const C=[],S=[];let b,R,I;if(e.length<2){const be=[],Le=[];for(R=0;R0&&(V=L[I].subtract(L[I-1]).length(),Z=V+g[b],p[b].push(Z),g[b]=Z),I++;i&&(I--,c.push(L[0].x,L[0].y,L[0].z),V=L[I].subtract(L[0]).length(),Z=V+g[b],p[b].push(Z),g[b]=Z),C[b]=B+O,S[b]=N,N+=B+O}let ue,oe,me=null,le=null;for(R=0;R{let p=i[0].length;const _=a;let g=0;const v=_._originalBuilderSideOrientation===se.DOUBLESIDE?2:1;for(let E=1;E<=v;++E)for(let C=0;CKh(o,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:a,instance:l},r);function Nx(o){const e=[],t=[],i=[],s=[],r=o.radius||.5,n=o.tessellation||64,a=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,l=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*a,c=a===1?h/n:h/(n-1);let u=0;for(let p=0;pwx(o,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);function id(o){const e=o.pattern||se.NO_FLIP,t=o.tileWidth||o.tileSize||1,i=o.tileHeight||o.tileSize||1,s=o.alignHorizontal||0,r=o.alignVertical||0,n=o.width||o.size||1,a=Math.floor(n/t);let l=n-a*t;const h=o.height||o.size||1,c=Math.floor(h/i);let u=h-c*i;const d=t*a/2,f=i*c/2;let p=0,_=0,g=0,v=0,E=0,C=0;if(l>0||u>0){switch(g=-d,v=-f,E=d,C=f,s){case se.CENTER:l/=2,g-=l,E+=l;break;case se.LEFT:E+=l,p=-l/2;break;case se.RIGHT:g-=l,p=l/2;break}switch(r){case se.CENTER:u/=2,v-=u,C+=u;break;case se.BOTTOM:C+=u,_=-u/2;break;case se.TOP:v-=u,_=u/2;break}}const S=[],b=[],R=[];R[0]=[0,0,1,0,1,1,0,1],R[1]=[0,0,1,0,1,1,0,1],(e===se.ROTATE_TILE||e===se.ROTATE_ROW)&&(R[1]=[1,1,0,1,0,0,1,0]),(e===se.FLIP_TILE||e===se.FLIP_ROW)&&(R[1]=[1,0,0,0,0,1,1,1]),(e===se.FLIP_N_ROTATE_TILE||e===se.FLIP_N_ROTATE_ROW)&&(R[1]=[0,1,1,1,1,0,0,0]);let I=[];const N=[],O=[];let L=0;for(let ue=0;ue0||u>0){const ue=u>0&&(r===se.CENTER||r===se.TOP),oe=u>0&&(r===se.CENTER||r===se.BOTTOM),me=l>0&&(s===se.CENTER||s===se.RIGHT),le=l>0&&(s===se.CENTER||s===se.LEFT);let ae=[],ce,ie,w,H;if(ue&&me&&(S.push(g+p,v+_,0),S.push(-d+p,v+_,0),S.push(-d+p,v+u+_,0),S.push(g+p,v+u+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=1-l/t,ie=1-u/i,w=1,H=1,ae=[ce,ie,w,ie,w,H,ce,H],e===se.ROTATE_ROW&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),e===se.FLIP_ROW&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),e===se.FLIP_N_ROTATE_ROW&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ue&&le&&(S.push(d+p,v+_,0),S.push(E+p,v+_,0),S.push(E+p,v+u+_,0),S.push(d+p,v+u+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=0,ie=1-u/i,w=l/t,H=1,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW||e===se.ROTATE_TILE&&a%2===0)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW||e===se.FLIP_TILE&&a%2===0)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW||e===se.FLIP_N_ROTATE_TILE&&a%2===0)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe&&me&&(S.push(g+p,f+_,0),S.push(-d+p,f+_,0),S.push(-d+p,C+_,0),S.push(g+p,C+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=1-l/t,ie=0,w=1,H=u/i,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW&&c%2===1||e===se.ROTATE_TILE&&c%1===0)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW&&c%2===1||e===se.FLIP_TILE&&c%2===0)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW&&c%2===1||e===se.FLIP_N_ROTATE_TILE&&c%2===0)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe&&le&&(S.push(d+p,f+_,0),S.push(E+p,f+_,0),S.push(E+p,C+_,0),S.push(d+p,C+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=0,ie=0,w=l/t,H=u/i,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW&&c%2===1||e===se.ROTATE_TILE&&(c+a)%2===1)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW&&c%2===1||e===se.FLIP_TILE&&(c+a)%2===1)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW&&c%2===1||e===se.FLIP_N_ROTATE_TILE&&(c+a)%2===1)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ue){const X=[];ce=0,ie=1-u/i,w=1,H=1,X[0]=[ce,ie,w,ie,w,H,ce,H],X[1]=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_TILE||e===se.ROTATE_ROW)&&(X[1]=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_TILE||e===se.FLIP_ROW)&&(X[1]=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_TILE||e===se.FLIP_N_ROTATE_ROW)&&(X[1]=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]);for(let te=0;teX+B)),B+=I[w].length,i)for(let X=0;X<4;X++)R.push(i[w].r,i[w].g,i[w].b,i[w].a)}const V=new T(0,0,_),Z=k.RotationY(Math.PI);E=I[0].map(w=>T.TransformNormal(w,Z).add(V)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]),C=N[0].map(w=>T.TransformNormal(w,Z)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]),E=E.concat(I[1].map(w=>w.subtract(V)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[1].map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const ue=new T(f,0,0),oe=k.RotationY(-Math.PI/2);E=E.concat(I[2].map(w=>T.TransformNormal(w,oe).add(ue)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[2].map(w=>T.TransformNormal(w,oe)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const me=k.RotationY(Math.PI/2);E=E.concat(I[3].map(w=>T.TransformNormal(w,me).subtract(ue)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[3].map(w=>T.TransformNormal(w,me)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const le=new T(0,p,0),ae=k.RotationX(Math.PI/2);E=E.concat(I[4].map(w=>T.TransformNormal(w,ae).add(le)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[4].map(w=>T.TransformNormal(w,ae)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const ce=k.RotationX(-Math.PI/2);E=E.concat(I[5].map(w=>T.TransformNormal(w,ce).subtract(le)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[5].map(w=>T.TransformNormal(w,ce)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),De._ComputeSides(d,E,b,C,S);const ie=new De;if(ie.indices=b,ie.positions=E,ie.normals=C,ie.uvs=S,i){const w=d===De.DOUBLESIDE?R.concat(R):R;ie.colors=w}return ie}function DB(o,e,t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Xb(e).applyToMesh(i,e.updatable),i}De.CreateTiledBox=Xb;function Yb(o){const e=[],t=[],i=[],s=[],r=o.radius||2,n=o.tube||.5,a=o.radialSegments||32,l=o.tubularSegments||32,h=o.p||2,c=o.q||3,u=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,d=g=>{const v=Math.cos(g),E=Math.sin(g),C=c/h*g,S=Math.cos(C),b=r*(2+S)*.5*v,R=r*(2+S)*E*.5,I=r*Math.sin(C)*.5;return new T(b,R,I)};let f,p;for(f=0;f<=a;f++){const v=f%a/a*2*h*Math.PI,E=d(v),C=d(v+.01),S=C.subtract(E);let b=C.add(E);const R=T.Cross(S,b);for(b=T.Cross(R,S),R.normalize(),b.normalize(),p=0;p$b(o,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:h,updatable:l},a);const fv={effect:null,subMesh:null};class wa extends ep{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 k,this._cachedWorldViewProjectionMatrix=new k,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},s)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let s=0;sr===e||r.startsWith(i));return s>=0&&this.options.defines.splice(s,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var s,r,n,a;const l=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(l){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const O=this._drawWrapper.effect;if(O&&O._wasPreviouslyReady&&O._wasPreviouslyUsingInstances===t)return!0}const h=this.getScene(),c=h.getEngine(),u=[],d=[],f=new Jh;let p=this._shaderPath,_=this._options.uniforms,g=this._options.uniformBuffers,v=this._options.samplers;c.getCaps().multiview&&h.activeCamera&&h.activeCamera.outputRenderTarget&&h.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,u.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.indexOf("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(let O=0;O4&&(d.push(P.MatricesIndicesExtraKind),d.push(P.MatricesWeightsExtraKind));const O=e.skeleton;u.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),f.addCPUSkinningFallback(0,e),O.isUsingTextureForMatrices?(u.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(u.push("#define BonesPerMesh "+(O.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else u.push("#define NUM_BONE_INFLUENCERS 0");let E=0;const C=e?e.morphTargetManager:null;if(C){const O=C.supportsUVs&&u.indexOf("#define UV1")!==-1,L=C.supportsTangents&&u.indexOf("#define TANGENT")!==-1,B=C.supportsNormals&&u.indexOf("#define NORMAL")!==-1;E=C.numInfluencers,O&&u.push("#define MORPHTARGETS_UV"),L&&u.push("#define MORPHTARGETS_TANGENT"),B&&u.push("#define MORPHTARGETS_NORMAL"),E>0&&u.push("#define MORPHTARGETS"),C.isUsingTextureForTargets&&(u.push("#define MORPHTARGETS_TEXTURE"),this._options.uniforms.indexOf("morphTargetTextureIndices")===-1&&this._options.uniforms.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),u.push("#define NUM_MORPH_INFLUENCERS "+E);for(let V=0;V0&&(_=_.slice(),_.push("morphTargetInfluences"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else u.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const O=e.bakedVertexAnimationManager;O&&O.isEnabled&&(u.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),this._options.uniforms.indexOf("bakedVertexAnimationSettings")===-1&&this._options.uniforms.push("bakedVertexAnimationSettings"),this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),this._options.uniforms.indexOf("bakedVertexAnimationTime")===-1&&this._options.uniforms.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Me.PrepareAttributesForBakedVertexAnimation(d,e,u)}for(const O in this._textures)if(!this._textures[O].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&u.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Ao(_),vh(this,h,u)),this._useLogarithmicDepth&&(u.push("#define LOGARITHMICDEPTH"),this._options.uniforms.indexOf("logarithmicDepthConstant")===-1&&this._options.uniforms.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(_=_.slice(),g=g.slice(),v=v.slice(),p=this.customShaderNameResolve(p,_,g,v,u,d));const S=l?i._getDrawWrapper():this._drawWrapper,b=(s=S==null?void 0:S.effect)!==null&&s!==void 0?s:null,R=(r=S==null?void 0:S.defines)!==null&&r!==void 0?r:null,I=u.join(` -`);let N=b;return R!==I&&(N=c.createEffect(p,{attributes:d,uniformsNames:_,uniformBuffersNames:g,samplers:v,defines:I,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:E},shaderLanguage:this._options.shaderLanguage},c),l?i.setEffect(N,I,this._materialContext):S&&S.setEffect(N,I),this._onEffectCreatedObservable&&(fv.effect=N,fv.subMesh=(n=i??(e==null?void 0:e.subMeshes[0]))!==null&&n!==void 0?n:null,this._onEffectCreatedObservable.notifyObservers(fv))),N._wasPreviouslyUsingInstances=!!t,!((a=!(N!=null&&N.isReady()))!==null&&a!==void 0)||a?!1:(b!==N&&h.resetCachedMaterial(),N._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(this._options.uniforms.indexOf("world")!==-1&&s.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)===null||s===void 0?void 0:s.effect,i)}bind(e,t,i,s){var r;const n=s&&this._storeEffectOnSubMeshes,a=i??(n?s.effect:this.getEffect());if(!a)return;const l=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const h=this._options.uniformBuffers;let c=!1;if(a&&h&&h.length>0&&l.getEngine().supportsUniformBuffers)for(let d=0;d0&&Me.BindMorphTargetParameters(t,a);const f=t.bakedVertexAnimationManager;f&&f.isEnabled&&((r=t.bakedVertexAnimationManager)===null||r===void 0||r.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;snew wa(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(i=>{const s=this._options[i];Array.isArray(s)&&(this._options[i]=s.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const r=this._textureArrays[s];for(let n=0;nnew wa(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,ee.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let l=0;l(h%3===0?a.push([l]):a[a.length-1].push(l),a),[]).map(a=>Te.FromArray(a));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,Ze.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((a,l,h)=>(h%4===0?a.push([l]):a[a.length-1].push(l),a),[]).map(a=>Ze.FromArray(a));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,Re.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,T.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,Dt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,Se.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,k.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const a=new Hs;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const l=JSON.parse(a.responseText),h=this.Parse(l,i||ht.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the ShaderMaterial")}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new Hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(a.shaderMaterial),h=this.Parse(l,t||ht.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()})}}wa.SnippetUrl="https://snippet.babylonjs.com";wa.CreateFromSnippetAsync=wa.ParseFromSnippetAsync;j("BABYLON.ShaderMaterial",wa);const OB="colorPixelShader",NB=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +`+this.defines),eu.LogShaderCodeOnCompilationError){let s=null,r=null;!((i=this._pipelineContext)===null||i===void 0)&&i._getComputeShaderCode()&&([r,s]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),r&&(G.Error("Compute code:"),G.Error(r))),s&&G.Error(s)}G.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){ne.GetShadersStore(is.WGSL)[`${e}ComputeShader`]=t}}eu._UniqueIdSeed=0;eu.LogShaderCodeOnCompilationError=!0;var ns;(function(o){o[o.Texture=0]="Texture",o[o.StorageTexture=1]="StorageTexture",o[o.UniformBuffer=2]="UniformBuffer",o[o.StorageBuffer=3]="StorageBuffer",o[o.TextureWithoutSampler=4]="TextureWithoutSampler",o[o.Sampler=5]="Sampler",o[o.ExternalTexture=6]="ExternalTexture"})(ns||(ns={}));We.prototype.createComputeEffect=function(o,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};We.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};We.prototype.createComputeContext=function(){};We.prototype.computeDispatch=function(o,e,t,i,s,r,n){throw new Error("computeDispatch: This engine does not support compute shaders!")};We.prototype.areAllComputeEffectsReady=function(){return!0};We.prototype.releaseComputeEffects=function(){};We.prototype._prepareComputePipelineContext=function(o,e,t,i,s){};We.prototype._rebuildComputeEffects=function(){};We.prototype._executeWhenComputeStateIsCompiled=function(o,e){e()};We.prototype._releaseComputeEffect=function(o){};We.prototype._deleteComputePipelineContext=function(o){};class Mx{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Pa}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()})}serialize(){const e=Xe.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 ns.Texture:case ns.TextureWithoutSampler:case ns.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case ns.UniformBuffer:break}}return e}static Parse(e,t,i){const s=Xe.Parse(()=>new gu(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const r in e.textures){const n=e.bindings[r],a=ee.Parse(e.textures[r],t,i);n.type===ns.Texture?s.setTexture(r,a):n.type===ns.TextureWithoutSampler?s.setTexture(r,a,!1):s.setStorageTexture(r,a)}return s}}A([D()],gu.prototype,"name",void 0);A([D()],gu.prototype,"fastMode",void 0);j("BABYLON.ComputeShader",gu);class M_{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;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const t=o.getBoundingInfo();!o.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(o)};tu.CreationFuncForSubMeshes=(o,e)=>{o.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(o)};Qe.prototype.createOrUpdateSelectionOctree=function(o=64,e=2){let t=this._getComponent(Fe.NAME_OCTREE);t||(t=new Hb(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new tu(tu.CreationFuncForMeshes,o,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(Qe.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});hi.prototype.createOrUpdateSubmeshesOctree=function(o=64,e=2){const t=this.getScene();let i=t._getComponent(Fe.NAME_OCTREE);i||(i=new Hb(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new tu(tu.CreationFuncForSubMeshes,o,e)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class Hb{constructor(e){this.name=Fe.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Kt(T.Zero(),new T(1,1,1)),e=e||ht.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||e===void 0?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?(Kt.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 Dx(o){const e=o.height||2;let t=o.diameterTop===0?0:o.diameterTop||o.diameter||1,i=o.diameterBottom===0?0:o.diameterBottom||o.diameter||1;t=t||1e-5,i=i||1e-5;const s=(o.tessellation||24)|0,r=(o.subdivisions||1)|0,n=!!o.hasRings,a=!!o.enclose,l=o.cap===0?0:o.cap||se.CAP_ALL,h=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,c=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,u=o.faceUV||new Array(3),d=o.faceColors,f=h!==1&&a?2:0,p=n?r:1,_=2+(1+f)*p;let g;for(g=0;g<_;g++)d&&d[g]===void 0&&(d[g]=new Ze(1,1,1,1));for(g=0;g<_;g++)u&&u[g]===void 0&&(u[g]=new Dt(0,0,1,1));const v=[],E=[],C=[],S=[],b=[],R=Math.PI*2*h/s;let I,N,O;const L=(i-t)/2/e,B=T.Zero(),V=T.Zero(),Z=T.Zero(),ue=T.Zero(),oe=T.Zero(),me=an.Y;let le,ae,ce,ie=1,w=1,H=0,X=0;for(le=0;le<=r;le++)for(N=le/r,O=(N*(t-i)+i)/2,ie=n&&le!==0&&le!==r?2:1,ce=0;ce{const de=q?t/2:i/2;if(de===0)return;let ge,ve,be;const Le=q?u[_-1]:u[0];let Ye=null;d&&(Ye=q?d[_-1]:d[0]);const He=E.length/3,Be=q?e/2:-e/2,Ge=new T(0,Be,0);E.push(Ge.x,Ge.y,Ge.z),C.push(0,q?1:-1,0);const Bt=Le.y+(Le.w-Le.y)*.5;S.push(Le.x+(Le.z-Le.x)*.5,pi.UseOpenGLOrientationForUV?1-Bt:Bt),Ye&&b.push(Ye.r,Ye.g,Ye.b,Ye.a);const Mt=new Re(.5,.5);for(be=0;be<=s;be++){ge=Math.PI*2*be*h/s;const Vi=Math.cos(-ge),at=Math.sin(-ge);ve=new T(Vi*de,Be,at*de);const ei=new Re(Vi*Mt.x+.5,at*Mt.y+.5);E.push(ve.x,ve.y,ve.z),C.push(0,q?1:-1,0);const di=Le.y+(Le.w-Le.y)*ei.y;S.push(Le.x+(Le.z-Le.x)*ei.x,pi.UseOpenGLOrientationForUV?1-di:di),Ye&&b.push(Ye.r,Ye.g,Ye.b,Ye.a)}for(be=0;be((n===void 0||!(n instanceof Qe))&&(n!==void 0&&(l=a||se.DEFAULTSIDE,a=n),n=r,r=1),Cm(o,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:l,updatable:a},n));Mi.AddNodeConstructor("Light_Type_3",(o,e)=>()=>new np(o,T.Zero(),e));class np extends Yt{constructor(e,t,i){super(e,i),this.groundColor=new Te(0,0,0),this.direction=t||T.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=T.Normalize(e.subtract(T.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=T.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=T.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=k.Identity()),this._worldMatrix}getTypeID(){return Yt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}A([ds()],np.prototype,"groundColor",void 0);A([kr()],np.prototype,"direction",void 0);class zs{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 np("shared gizmo light",new T(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Te.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return zs._DefaultUtilityLayer==null?zs._CreateDefaultUtilityLayerFromScene(ht.LastCreatedScene):zs._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return zs._DefaultUtilityLayer=new zs(e),zs._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zs._DefaultUtilityLayer=null}),zs._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return zs._DefaultKeepDepthUtilityLayer==null&&(zs._DefaultKeepDepthUtilityLayer=new zs(ht.LastCreatedScene),zs._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,zs._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zs._DefaultKeepDepthUtilityLayer=null})),zs._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 he,this.utilityLayerScene=new Qe(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!==rt.POINTERMOVE&&i.type!==rt.POINTERUP&&i.type!==rt.POINTERDOWN&&i.type!==rt.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=a=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==a?l=i.nearInteractionPickingInfo:l=new Vr;else if(a!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let h=null;this._renderCamera&&(h=a._activeCamera,a._activeCamera=this._renderCamera,i.ray=null),l=i.ray?a.pickWithRay(i.ray):a.pick(e.pointerX,e.pointerY),h&&(a._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!=rt.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Ja(i.type,i.event,n),i.type),i.type===rt.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 Ja(i.type,i.event,n),i.type),i.skipOnPointerObservable=!0);else{const a=r(e),l=i.event;a&&n&&(n.distance===0&&a.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(a.pickedMesh)?(this._notifyObservers(i,a,l),i.skipOnPointerObservable=!0):i.type===rt.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===rt.POINTERMOVE||i.type===rt.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,a,l)):!this._pointerCaptures[l.pointerId]&&(n.distance0)):!this._pointerCaptures[l.pointerId]&&n.distance>=a.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(a.pickedMesh)?(this._notifyObservers(i,a,l),i.skipOnPointerObservable=!0):((i.type===rt.POINTERMOVE||i.type===rt.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,n,l))),i.type===rt.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 Ja(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()}}zs._DefaultUtilityLayer=null;zs._DefaultKeepDepthUtilityLayer=null;var f0;(function(o){o[o.Origin=0]="Origin",o[o.Pivot=1]="Pivot"})(f0||(f0={}));var p0;(function(o){o[o.World=0]="World",o[o.Local=1]="Local"})(p0||(p0={}));Object.defineProperty(Qe.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new iu(this)),this._debugLayer},enumerable:!0,configurable:!0});var _0;(function(o){o[o.Properties=0]="Properties",o[o.Debug=1]="Debug",o[o.Statistics=2]="Statistics",o[o.Tools=3]="Tools",o[o.Settings=4]="Settings"})(_0||(_0={}));class iu{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new he),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new he),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||ht.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=Object.assign(Object.assign({},iu.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:iu.InspectorURL;fe.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}iu.InspectorURL=`${fe._DefaultCdnUrl}/v${re.Version}/inspector/babylon.inspector.bundle.js`;iu.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function Ox(o){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=o.width||o.size||1,a=o.height||o.size||1,l=o.depth||o.size||1,h=o.wrap||!1;let c=o.topBaseAt===void 0?1:o.topBaseAt,u=o.bottomBaseAt===void 0?0:o.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let p=d[c],_=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 I=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],N=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const O=[17,18,19,16],L=[22,23,20,21];for(;p>0;)I.unshift(I.pop()),O.unshift(O.pop()),p--;for(;_>0;)N.unshift(N.pop()),L.unshift(L.pop()),_--;I=I.flat(),N=N.flat(),g=g.concat(I).concat(N),t.push(O[0],O[2],O[3],O[0],O[1],O[2]),t.push(L[0],L[2],L[3],L[0],L[1],L[2])}const v=[n/2,a/2,l/2];r=g.reduce((I,N,O)=>I.concat(N*v[O%3]),[]);const E=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,C=o.faceUV||new Array(6),S=o.faceColors,b=[];for(let I=0;I<6;I++)C[I]===void 0&&(C[I]=new Dt(0,0,1,1)),S&&S[I]===void 0&&(S[I]=new Ze(1,1,1,1));for(let I=0;I<6;I++)if(s.push(C[I].z,pi.UseOpenGLOrientationForUV?1-C[I].w:C[I].w),s.push(C[I].x,pi.UseOpenGLOrientationForUV?1-C[I].w:C[I].w),s.push(C[I].x,pi.UseOpenGLOrientationForUV?1-C[I].y:C[I].y),s.push(C[I].z,pi.UseOpenGLOrientationForUV?1-C[I].y:C[I].y),S)for(let N=0;N<4;N++)b.push(S[I].r,S[I].g,S[I].b,S[I].a);Oe._ComputeSides(E,r,t,i,s,o.frontUVs,o.backUVs);const R=new Oe;if(R.indices=t,R.positions=r,R.normals=i,R.uvs=s,S){const I=E===Oe.DOUBLESIDE?b.concat(b):b;R.colors=I}return R}function OB(o){const e=o.width||o.size||1,t=o.height||o.size||1,i=o.depth||o.size||1,s=(o.widthSegments||o.segments||1)|0,r=(o.heightSegments||o.segments||1)|0,n=(o.depthSegments||o.segments||1)|0,a=new k,l=new k,h=new k,c=xl({width:e,height:i,subdivisionsX:s,subdivisionsY:n});k.TranslationToRef(0,-t/2,0,l),k.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=xl({width:e,height:i,subdivisionsX:s,subdivisionsY:n});k.TranslationToRef(0,t/2,0,h),u.transform(h);const d=xl({width:t,height:i,subdivisionsX:r,subdivisionsY:n});k.TranslationToRef(-e/2,0,0,l),k.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const f=xl({width:t,height:i,subdivisionsX:r,subdivisionsY:n});k.TranslationToRef(e/2,0,0,l),k.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const p=xl({width:e,height:t,subdivisionsX:s,subdivisionsY:r});k.TranslationToRef(0,0,-i/2,l),k.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const _=xl({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return k.TranslationToRef(0,0,i/2,l),k.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,f,d,p,_],!0),c}function bm(o,e={},t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Ox(e).applyToMesh(i,e.updatable),i}Oe.CreateBox=Ox;se.CreateBox=(o,e,t=null,i,s)=>bm(o,{size:e,sideOrientation:s,updatable:i},t);function Nx(o){const e=(o.segments||32)|0,t=o.diameterX||o.diameter||1,i=o.diameterY||o.diameter||1,s=o.diameterZ||o.diameter||1,r=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,n=o.slice&&o.slice<=0?1:o.slice||1,a=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,l=!!o.dedupTopBottomIndices,h=new T(t/2,i/2,s/2),c=2+e,u=2*c,d=[],f=[],p=[],_=[];for(let v=0;v<=c;v++){const E=v/c,C=E*Math.PI*n;for(let S=0;S<=u;S++){const b=S/u,R=b*Math.PI*2*r,I=k.RotationZ(-C),N=k.RotationY(R),O=T.TransformCoordinates(T.Up(),I),L=T.TransformCoordinates(O,N),B=L.multiply(h),V=L.divide(h).normalize();f.push(B.x,B.y,B.z),p.push(V.x,V.y,V.z),_.push(b,pi.UseOpenGLOrientationForUV?1-E:E)}if(v>0){const S=f.length/3;for(let b=S-2*(u+1);b+u+21&&(d.push(b),d.push(b+1),d.push(b+u+1)),(vQo(o,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function wx(o={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(o.subdivisions?o.subdivisions:2,1)|0,t=Math.max(o.tessellation?o.tessellation:16,3)|0,i=Math.max(o.height?o.height:1,0),s=Math.max(o.radius?o.radius:.25,0),r=Math.max(o.capSubdivisions?o.capSubdivisions:6,1)|0,n=t,a=e,l=Math.max(o.radiusTop?o.radiusTop:s,0),h=Math.max(o.radiusBottom?o.radiusBottom:s,0),c=i-(l+h),u=0,d=2*Math.PI,f=Math.max(o.topCapSubdivisions?o.topCapSubdivisions:r,1),p=Math.max(o.bottomCapSubdivisions?o.bottomCapSubdivisions:r,1),_=Math.acos((h-l)/i);let g=[];const v=[],E=[],C=[];let S=0;const b=[],R=c*.5,I=Math.PI*.5;let N,O;const L=T.Zero(),B=T.Zero(),V=Math.cos(_),Z=Math.sin(_),ue=new Re(l*Z,R+l*V).subtract(new Re(h*Z,-R+h*V)).length(),oe=l*_+ue+h*(I-_);let me=0;for(O=0;O<=f;O++){const ie=[],w=I-_*(O/f);me+=l*_/f;const H=Math.cos(w),X=Math.sin(w),te=H*l;for(N=0;N<=n;N++){const Q=N/n,_e=Q*d+u,q=Math.sin(_e),de=Math.cos(_e);B.x=te*q,B.y=R+X*l,B.z=te*de,v.push(B.x,B.y,B.z),L.set(H*q,X,H*de),E.push(L.x,L.y,L.z),C.push(Q,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}const le=i-l-h+V*l-V*h,ae=Z*(h-l)/le;for(O=1;O<=a;O++){const ie=[];me+=ue/a;const w=Z*(O*(h-l)/a+l);for(N=0;N<=n;N++){const H=N/n,X=H*d+u,te=Math.sin(X),Q=Math.cos(X);B.x=w*te,B.y=R+V*l-O*le/a,B.z=w*Q,v.push(B.x,B.y,B.z),L.set(te,ae,Q).normalize(),E.push(L.x,L.y,L.z),C.push(H,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}for(O=1;O<=p;O++){const ie=[],w=I-_-(Math.PI-_)*(O/p);me+=h*_/p;const H=Math.cos(w),X=Math.sin(w),te=H*h;for(N=0;N<=n;N++){const Q=N/n,_e=Q*d+u,q=Math.sin(_e),de=Math.cos(_e);B.x=te*q,B.y=-R+X*h,B.z=te*de,v.push(B.x,B.y,B.z),L.set(H*q,X,H*de),E.push(L.x,L.y,L.z),C.push(Q,pi.UseOpenGLOrientationForUV?me/oe:1-me/oe),ie.push(S),S++}b.push(ie)}for(N=0;NXb(o,e,t);Oe.CreateCapsule=wx;function Yb(o){let e=o.pathArray;const t=o.closeArray||!1,i=o.closePath||!1,s=o.invertUV||!1,r=Math.floor(e[0].length/2);let n=o.offset||r;n=n>r?r:Math.floor(n);const a=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,l=o.uvs,h=o.colors,c=[],u=[],d=[],f=[],p=[],_=[],g=[],v=[];let E;const C=[],S=[];let b,R,I;if(e.length<2){const be=[],Le=[];for(R=0;R0&&(V=L[I].subtract(L[I-1]).length(),Z=V+g[b],p[b].push(Z),g[b]=Z),I++;i&&(I--,c.push(L[0].x,L[0].y,L[0].z),V=L[I].subtract(L[0]).length(),Z=V+g[b],p[b].push(Z),g[b]=Z),C[b]=B+O,S[b]=N,N+=B+O}let ue,oe,me=null,le=null;for(R=0;R{let p=i[0].length;const _=a;let g=0;const v=_._originalBuilderSideOrientation===se.DOUBLESIDE?2:1;for(let E=1;E<=v;++E)for(let C=0;Cqh(o,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:a,instance:l},r);function Fx(o){const e=[],t=[],i=[],s=[],r=o.radius||.5,n=o.tessellation||64,a=o.arc&&(o.arc<=0||o.arc>1)?1:o.arc||1,l=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*a,c=a===1?h/n:h/(n-1);let u=0;for(let p=0;pLx(o,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);function id(o){const e=o.pattern||se.NO_FLIP,t=o.tileWidth||o.tileSize||1,i=o.tileHeight||o.tileSize||1,s=o.alignHorizontal||0,r=o.alignVertical||0,n=o.width||o.size||1,a=Math.floor(n/t);let l=n-a*t;const h=o.height||o.size||1,c=Math.floor(h/i);let u=h-c*i;const d=t*a/2,f=i*c/2;let p=0,_=0,g=0,v=0,E=0,C=0;if(l>0||u>0){switch(g=-d,v=-f,E=d,C=f,s){case se.CENTER:l/=2,g-=l,E+=l;break;case se.LEFT:E+=l,p=-l/2;break;case se.RIGHT:g-=l,p=l/2;break}switch(r){case se.CENTER:u/=2,v-=u,C+=u;break;case se.BOTTOM:C+=u,_=-u/2;break;case se.TOP:v-=u,_=u/2;break}}const S=[],b=[],R=[];R[0]=[0,0,1,0,1,1,0,1],R[1]=[0,0,1,0,1,1,0,1],(e===se.ROTATE_TILE||e===se.ROTATE_ROW)&&(R[1]=[1,1,0,1,0,0,1,0]),(e===se.FLIP_TILE||e===se.FLIP_ROW)&&(R[1]=[1,0,0,0,0,1,1,1]),(e===se.FLIP_N_ROTATE_TILE||e===se.FLIP_N_ROTATE_ROW)&&(R[1]=[0,1,1,1,1,0,0,0]);let I=[];const N=[],O=[];let L=0;for(let ue=0;ue0||u>0){const ue=u>0&&(r===se.CENTER||r===se.TOP),oe=u>0&&(r===se.CENTER||r===se.BOTTOM),me=l>0&&(s===se.CENTER||s===se.RIGHT),le=l>0&&(s===se.CENTER||s===se.LEFT);let ae=[],ce,ie,w,H;if(ue&&me&&(S.push(g+p,v+_,0),S.push(-d+p,v+_,0),S.push(-d+p,v+u+_,0),S.push(g+p,v+u+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=1-l/t,ie=1-u/i,w=1,H=1,ae=[ce,ie,w,ie,w,H,ce,H],e===se.ROTATE_ROW&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),e===se.FLIP_ROW&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),e===se.FLIP_N_ROTATE_ROW&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ue&&le&&(S.push(d+p,v+_,0),S.push(E+p,v+_,0),S.push(E+p,v+u+_,0),S.push(d+p,v+u+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=0,ie=1-u/i,w=l/t,H=1,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW||e===se.ROTATE_TILE&&a%2===0)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW||e===se.FLIP_TILE&&a%2===0)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW||e===se.FLIP_N_ROTATE_TILE&&a%2===0)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe&&me&&(S.push(g+p,f+_,0),S.push(-d+p,f+_,0),S.push(-d+p,C+_,0),S.push(g+p,C+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=1-l/t,ie=0,w=1,H=u/i,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW&&c%2===1||e===se.ROTATE_TILE&&c%1===0)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW&&c%2===1||e===se.FLIP_TILE&&c%2===0)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW&&c%2===1||e===se.FLIP_N_ROTATE_TILE&&c%2===0)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),oe&&le&&(S.push(d+p,f+_,0),S.push(E+p,f+_,0),S.push(E+p,C+_,0),S.push(d+p,C+_,0),O.push(L,L+1,L+3,L+1,L+2,L+3),L+=4,ce=0,ie=0,w=l/t,H=u/i,ae=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_ROW&&c%2===1||e===se.ROTATE_TILE&&(c+a)%2===1)&&(ae=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_ROW&&c%2===1||e===se.FLIP_TILE&&(c+a)%2===1)&&(ae=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_ROW&&c%2===1||e===se.FLIP_N_ROTATE_TILE&&(c+a)%2===1)&&(ae=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]),I=I.concat(ae),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ue){const X=[];ce=0,ie=1-u/i,w=1,H=1,X[0]=[ce,ie,w,ie,w,H,ce,H],X[1]=[ce,ie,w,ie,w,H,ce,H],(e===se.ROTATE_TILE||e===se.ROTATE_ROW)&&(X[1]=[1-ce,1-ie,1-w,1-ie,1-w,1-H,1-ce,1-H]),(e===se.FLIP_TILE||e===se.FLIP_ROW)&&(X[1]=[1-ce,ie,1-w,ie,1-w,H,1-ce,H]),(e===se.FLIP_N_ROTATE_TILE||e===se.FLIP_N_ROTATE_ROW)&&(X[1]=[ce,1-ie,w,1-ie,w,1-H,ce,1-H]);for(let te=0;teX+B)),B+=I[w].length,i)for(let X=0;X<4;X++)R.push(i[w].r,i[w].g,i[w].b,i[w].a)}const V=new T(0,0,_),Z=k.RotationY(Math.PI);E=I[0].map(w=>T.TransformNormal(w,Z).add(V)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]),C=N[0].map(w=>T.TransformNormal(w,Z)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]),E=E.concat(I[1].map(w=>w.subtract(V)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[1].map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const ue=new T(f,0,0),oe=k.RotationY(-Math.PI/2);E=E.concat(I[2].map(w=>T.TransformNormal(w,oe).add(ue)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[2].map(w=>T.TransformNormal(w,oe)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const me=k.RotationY(Math.PI/2);E=E.concat(I[3].map(w=>T.TransformNormal(w,me).subtract(ue)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[3].map(w=>T.TransformNormal(w,me)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const le=new T(0,p,0),ae=k.RotationX(Math.PI/2);E=E.concat(I[4].map(w=>T.TransformNormal(w,ae).add(le)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[4].map(w=>T.TransformNormal(w,ae)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[]));const ce=k.RotationX(-Math.PI/2);E=E.concat(I[5].map(w=>T.TransformNormal(w,ce).subtract(le)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),C=C.concat(N[5].map(w=>T.TransformNormal(w,ce)).map(w=>[w.x,w.y,w.z]).reduce((w,H)=>w.concat(H),[])),Oe._ComputeSides(d,E,b,C,S);const ie=new Oe;if(ie.indices=b,ie.positions=E,ie.normals=C,ie.uvs=S,i){const w=d===Oe.DOUBLESIDE?R.concat(R):R;ie.colors=w}return ie}function wB(o,e,t=null){const i=new se(o,t);return e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,$b(e).applyToMesh(i,e.updatable),i}Oe.CreateTiledBox=$b;function Kb(o){const e=[],t=[],i=[],s=[],r=o.radius||2,n=o.tube||.5,a=o.radialSegments||32,l=o.tubularSegments||32,h=o.p||2,c=o.q||3,u=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,d=g=>{const v=Math.cos(g),E=Math.sin(g),C=c/h*g,S=Math.cos(C),b=r*(2+S)*.5*v,R=r*(2+S)*E*.5,I=r*Math.sin(C)*.5;return new T(b,R,I)};let f,p;for(f=0;f<=a;f++){const v=f%a/a*2*h*Math.PI,E=d(v),C=d(v+.01),S=C.subtract(E);let b=C.add(E);const R=T.Cross(S,b);for(b=T.Cross(R,S),R.normalize(),b.normalize(),p=0;pqb(o,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:h,updatable:l},a);const fv={effect:null,subMesh:null};class wa extends ep{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 k,this._cachedWorldViewProjectionMatrix=new k,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},s)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,s)=>(s.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let s=0;sr===e||r.startsWith(i));return s>=0&&this.options.defines.splice(s,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var s,r,n,a;const l=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(l){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const O=this._drawWrapper.effect;if(O&&O._wasPreviouslyReady&&O._wasPreviouslyUsingInstances===t)return!0}const h=this.getScene(),c=h.getEngine(),u=[],d=[],f=new ec;let p=this._shaderPath,_=this._options.uniforms,g=this._options.uniformBuffers,v=this._options.samplers;c.getCaps().multiview&&h.activeCamera&&h.activeCamera.outputRenderTarget&&h.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,u.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.indexOf("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(let O=0;O4&&(d.push(P.MatricesIndicesExtraKind),d.push(P.MatricesWeightsExtraKind));const O=e.skeleton;u.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),f.addCPUSkinningFallback(0,e),O.isUsingTextureForMatrices?(u.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(u.push("#define BonesPerMesh "+(O.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else u.push("#define NUM_BONE_INFLUENCERS 0");let E=0;const C=e?e.morphTargetManager:null;if(C){const O=C.supportsUVs&&u.indexOf("#define UV1")!==-1,L=C.supportsTangents&&u.indexOf("#define TANGENT")!==-1,B=C.supportsNormals&&u.indexOf("#define NORMAL")!==-1;E=C.numInfluencers,O&&u.push("#define MORPHTARGETS_UV"),L&&u.push("#define MORPHTARGETS_TANGENT"),B&&u.push("#define MORPHTARGETS_NORMAL"),E>0&&u.push("#define MORPHTARGETS"),C.isUsingTextureForTargets&&(u.push("#define MORPHTARGETS_TEXTURE"),this._options.uniforms.indexOf("morphTargetTextureIndices")===-1&&this._options.uniforms.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),u.push("#define NUM_MORPH_INFLUENCERS "+E);for(let V=0;V0&&(_=_.slice(),_.push("morphTargetInfluences"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else u.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const O=e.bakedVertexAnimationManager;O&&O.isEnabled&&(u.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),this._options.uniforms.indexOf("bakedVertexAnimationSettings")===-1&&this._options.uniforms.push("bakedVertexAnimationSettings"),this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),this._options.uniforms.indexOf("bakedVertexAnimationTime")===-1&&this._options.uniforms.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Me.PrepareAttributesForBakedVertexAnimation(d,e,u)}for(const O in this._textures)if(!this._textures[O].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&u.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Ao(_),xh(this,h,u)),this._useLogarithmicDepth&&(u.push("#define LOGARITHMICDEPTH"),this._options.uniforms.indexOf("logarithmicDepthConstant")===-1&&this._options.uniforms.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(_=_.slice(),g=g.slice(),v=v.slice(),p=this.customShaderNameResolve(p,_,g,v,u,d));const S=l?i._getDrawWrapper():this._drawWrapper,b=(s=S==null?void 0:S.effect)!==null&&s!==void 0?s:null,R=(r=S==null?void 0:S.defines)!==null&&r!==void 0?r:null,I=u.join(` +`);let N=b;return R!==I&&(N=c.createEffect(p,{attributes:d,uniformsNames:_,uniformBuffersNames:g,samplers:v,defines:I,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:E},shaderLanguage:this._options.shaderLanguage},c),l?i.setEffect(N,I,this._materialContext):S&&S.setEffect(N,I),this._onEffectCreatedObservable&&(fv.effect=N,fv.subMesh=(n=i??(e==null?void 0:e.subMeshes[0]))!==null&&n!==void 0?n:null,this._onEffectCreatedObservable.notifyObservers(fv))),N._wasPreviouslyUsingInstances=!!t,!((a=!(N!=null&&N.isReady()))!==null&&a!==void 0)||a?!1:(b!==N&&h.resetCachedMaterial(),N._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(this._options.uniforms.indexOf("world")!==-1&&s.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)===null||s===void 0?void 0:s.effect,i)}bind(e,t,i,s){var r;const n=s&&this._storeEffectOnSubMeshes,a=i??(n?s.effect:this.getEffect());if(!a)return;const l=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const h=this._options.uniformBuffers;let c=!1;if(a&&h&&h.length>0&&l.getEngine().supportsUniformBuffers)for(let d=0;d0&&Me.BindMorphTargetParameters(t,a);const f=t.bakedVertexAnimationManager;f&&f.isEnabled&&((r=t.bakedVertexAnimationManager)===null||r===void 0||r.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;snew wa(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(i=>{const s=this._options[i];Array.isArray(s)&&(this._options[i]=s.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const r=this._textureArrays[s];for(let n=0;nnew wa(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,ee.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let l=0;l(h%3===0?a.push([l]):a[a.length-1].push(l),a),[]).map(a=>Te.FromArray(a));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,Ze.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((a,l,h)=>(h%4===0?a.push([l]):a[a.length-1].push(l),a),[]).map(a=>Ze.FromArray(a));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,Re.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,T.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,Dt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,Se.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,k.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const a=new Hs;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const l=JSON.parse(a.responseText),h=this.Parse(l,i||ht.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the ShaderMaterial")}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new Hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(a.shaderMaterial),h=this.Parse(l,t||ht.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()})}}wa.SnippetUrl="https://snippet.babylonjs.com";wa.CreateFromSnippetAsync=wa.ParseFromSnippetAsync;j("BABYLON.ShaderMaterial",wa);const FB="colorPixelShader",LB=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) #define VERTEXCOLOR varying vec4 vColor; #else @@ -2664,7 +2664,7 @@ gl_FragColor=vColor; gl_FragColor=color; #endif #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[OB]=NB;const wB="colorVertexShader",FB=`attribute vec3 position; +}`;ne.ShadersStore[FB]=LB;const BB="colorVertexShader",VB=`attribute vec3 position; #ifdef VERTEXCOLOR attribute vec4 color; #endif @@ -2694,37 +2694,37 @@ gl_Position=viewProjection*worldPos; #include #include #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[wB]=FB;se._LinesMeshParser=(o,e)=>fh.Parse(o,e);class fh extends se{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,r,n,a,l){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new Te(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:[P.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};a===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),n?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(P.ColorKind)):(c.uniforms.push("color"),this._color4=new Ze),l?this.material=l:(this.material=new wa("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=Ie.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(Ie.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(Ie.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 fh(e,this.getScene(),t,this,i)}createInstance(e){const t=new Kb(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 fh(e.name,t);return i.color=Te.FromArray(e.color),i.alpha=e.alpha,i}}class Kb extends dx{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function qb(o){const e=[],t=[],i=o.lines,s=o.colors,r=[];let n=0;for(let l=0;l0&&(e.push(n-1),e.push(n)),n++}}const a=new De;return a.indices=e,a.positions=t,s&&(a.colors=r),a}function jb(o){const e=o.dashSize||3,t=o.gapSize||1,i=o.dashNb||200,s=o.points,r=[],n=[],a=T.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,p=0;for(p=0;p{const u=T.Zero(),d=c.length/6;let f=0,p=0,_=0,g=0,v=0,E=0,C=0,S=0;for(C=0;Cym(o,{points:e,updatable:i,instance:s},t);se.CreateDashedLines=(o,e,t,i,s,r=null,n,a)=>Zb(o,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:a},r);class LB extends Re{constructor(e,t){super(e.x,e.y),this.index=t}}class pv{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new LB(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new Re(this.elements[0].x,this.elements[0].y),t=new Re(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class BB{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new pv,this._outlinepoints=new pv,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||ht.LastCreatedScene;let r;t instanceof Q_?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&G.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new pv;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 se(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(P.PositionKind,r.positions,e),s.setVerticesData(P.NormalKind,r.normals,e),s.setVerticesData(P.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new De,s=[],r=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),r.push(c.x,0,c.y),n.push((c.x-a.min.x)/a.width,(c.y-a.min.y)/a.height)});const l=[],h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){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-a.min.x)/a.width,1-(d.y-a.min.y)/a.height)});const u=l.length;for(let d=0;d{this._addSide(r,s,n,l,a,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,a,l,h){let c=e.length/3,u=0;for(let d=0;dh?I<$t-1?b=new T(f.x,0,f.y).subtract(new T(p.x,0,p.y)).normalize():b=E.add(v).normalize():b=S;const N=T.Dot(C,v);N>h?N<$t-1?R=new T(p.x,0,p.y).subtract(new T(f.x,0,f.y)).normalize():R=C.add(v).normalize():R=S,i.push(u/r.width,0),i.push(u/r.width,1),u+=v.length(),i.push(u/r.width,0),i.push(u/r.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(R.x,R.y,R.z),t.push(R.x,R.y,R.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 Jb(o,e,t,i,s,r,n){const a=t||new Array(3),l=i,h=[],c=n||!1;for(let O=0;O<3;O++)a[O]===void 0&&(a[O]=new Dt(0,0,1,1)),l&&l[O]===void 0&&(l[O]=new Ze(1,1,1,1));const u=o.getVerticesData(P.PositionKind),d=o.getVerticesData(P.NormalKind),f=o.getVerticesData(P.UVKind),p=o.getIndices(),_=u.length/9;let g=0,v=0,E=0,C=0,S=0;const b=[0];if(c)for(let O=_;OFx(o,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);se.ExtrudePolygon=(o,e,t,i,s,r,n,a=earcut)=>Lx(o,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,a);function Bx(o,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,a=e.cap===0?0:e.cap||se.NO_CAP,l=e.updatable,h=se._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return ty(o,s,i,r,n,null,null,f,d,a,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function ey(o,e,t=null){const i=e.path,s=e.shape,r=e.scaleFunction||(()=>1),n=e.rotationFunction||(()=>0),a=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||se.NO_CAP,c=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,f=se._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,_=e.invertUV||!1;return ty(o,s,i,null,null,r,n,a,l,h,!0,t,!!c,f,p||null,_,e.frontUVs||null,e.backUVs||null,u,d)}function ty(o,e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C){const S=(O,L,B,V,Z,ue,oe,me,le,ae,ce)=>{const ie=B.getTangents(),w=B.getNormals(),H=B.getBinormals(),X=B.getDistances();if(ce){for(let Le=0;Le0){let Ye=ie[Le-1];T.Dot(Ye,ie[Le])<0&&ie[Le].scaleInPlace(-1),Ye=w[Le-1],T.Dot(Ye,w[Le])<0&&w[Le].scaleInPlace(-1),Ye=H[Le-1],T.Dot(Ye,H[Le])<0&&H[Le].scaleInPlace(-1)}}let te=0;const Q=()=>Z!==null?Z:1,q=ae&&me?me:()=>ue!==null?ue:0,de=ae&&oe?oe:Q;let ge=le===se.NO_CAP||le===se.CAP_END?0:2;const ve=K.Matrix[0];for(let Le=0;Le{const Ye=Array(),He=T.Zero();let Be;for(Be=0;Be3?0:h,R=S(e,t,b,I,i,s,r,n,h,c,C);const N=Kh(o,{pathArray:R,closeArray:a,closePath:l,updatable:d,sideOrientation:f,invertUV:_,frontUVs:g||void 0,backUVs:v||void 0},u);return N._creationDataStorage.pathArray=R,N._creationDataStorage.path3D=b,N._creationDataStorage.cap=h,N}se.ExtrudeShape=(o,e,t,i,s,r,n=null,a,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||se.NO_CAP,sideOrientation:l,instance:h,updatable:a};return Bx(o,c,n)};se.ExtrudeShapeCustom=(o,e,t,i,s,r,n,a,l,h,c,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:a===0?0:a||se.NO_CAP,sideOrientation:c,instance:u,updatable:h};return ey(o,d,l)};function iy(o,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,a=e.tessellation||64,l=e.clip||0,h=e.updatable,c=se._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||se.NO_CAP,d=Math.PI*2,f=[],p=e.invertUV||!1;let _=0,g=0;const v=d/a*i;let E,C;for(_=0;_<=a-l;_++){for(C=[],(u==se.CAP_START||u==se.CAP_ALL)&&(C.push(new T(0,r[0].y,0)),C.push(new T(Math.cos(_*v)*r[0].x*n,r[0].y,Math.sin(_*v)*r[0].x*n))),g=0;giy(o,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function sy(o,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,a=e.radiusFunction||null;let l=e.cap||se.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=se._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(v,E,C,S,b,R,I,N)=>{const O=E.getTangents(),L=E.getNormals(),B=E.getDistances(),Z=Math.PI*2/b*N,oe=R||(()=>S);let me,le,ae,ce;const ie=K.Matrix[0];let w=I===se.NO_CAP||I===se.CAP_END?0:2;for(let X=0;X{const Q=Array();for(let _e=0;_e3?0:l,p=d(i,f,_,r,n,a,l,e.arc);const g=Kh(o,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=p,g._creationDataStorage.path3D=f,g._creationDataStorage.tessellation=n,g._creationDataStorage.cap=l,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=r,g}se.CreateTube=(o,e,t,i,s,r,n,a,l,h)=>sy(o,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:l,instance:h},n);function ry(o){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=o.type&&(o.type<0||o.type>=e.length)?0:o.type||0,i=o.size,s=o.sizeX||i||1,r=o.sizeY||i||1,n=o.sizeZ||i||1,a=o.custom||e[t],l=a.face.length,h=o.faceUV||new Array(l),c=o.faceColors,u=o.flat===void 0?!0:o.flat,d=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,f=[],p=[],_=[],g=[],v=[];let E=0,C=0;const S=[];let b=0,R=0,I,N,O,L,B,V;if(u)for(R=0;RVx(o,e,t);const VB=new T(1,0,0),UB=new T(-1,0,0),kB=new T(0,1,0),GB=new T(0,-1,0),zB=new T(0,0,1),WB=new T(0,0,-1);class D_{constructor(e=T.Zero(),t=T.Up(),i=Re.Zero(),s=0,r=0,n=null,a=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=a,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new D_(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)===null||e===void 0?void 0:e.slice(),(t=this.localNormalOverride)===null||t===void 0?void 0:t.slice(),(i=this.matrixIndicesOverride)===null||i===void 0?void 0:i.slice(),(s=this.matrixWeightsOverride)===null||s===void 0?void 0:s.slice())}}function ny(o,e,t){var i,s,r,n;const a=!!e.skeleton,l=t.localMode||a,h=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,c=e.getIndices(),u=a?e.getPositionData(!0,!0):e.getVerticesData(P.PositionKind),d=a?e.getNormalsData(!0,!0):e.getVerticesData(P.NormalKind),f=l?a?e.getVerticesData(P.PositionKind):u:null,p=l?a?e.getVerticesData(P.NormalKind):d:null,_=e.getVerticesData(P.UVKind),g=a?e.getVerticesData(P.MatricesIndicesKind):null,v=a?e.getVerticesData(P.MatricesWeightsKind):null,E=a?e.getVerticesData(P.MatricesIndicesExtraKind):null,C=a?e.getVerticesData(P.MatricesWeightsExtraKind):null,S=t.position||T.Zero();let b=t.normal||T.Up();const R=t.size||T.One(),I=t.angle||0;if(!b){const w=new T(0,0,1),H=e.getScene().activeCamera,X=T.TransformCoordinates(w,H.getWorldMatrix());b=H.globalPosition.subtract(X)}const N=-Math.atan2(b.z,b.x)-Math.PI/2,O=Math.sqrt(b.x*b.x+b.z*b.z),L=Math.atan2(b.y,O),B=new De;B.indices=[],B.positions=[],B.normals=[],B.uvs=[],B.matricesIndices=a?[]:null,B.matricesWeights=a?[]:null,B.matricesIndicesExtra=E?[]:null,B.matricesWeightsExtra=C?[]:null;let V=0;const Z=(w,H)=>{const X=new D_;if(!c||!u||!d)return X;const te=c[w];if(X.vertexIdx=te*3,X.vertexIdxForBones=te*4,X.position=new T(u[te*3],u[te*3+1],u[te*3+2]),T.TransformCoordinatesToRef(X.position,H,X.position),X.normal=new T(d[te*3],d[te*3+1],d[te*3+2]),T.TransformNormalToRef(X.normal,H,X.normal),t.captureUVS&&_){const Q=_[te*2+1];X.uv=new Re(_[te*2],pi.UseOpenGLOrientationForUV?1-Q:Q)}return X},ue=[0,0,0,0],oe=(w,H)=>{if(w.length===0)return w;const X=.5*Math.abs(T.Dot(R,H)),te=(q,de,ge,ve)=>{for(let be=0;be{var ge,ve,be,Le,Ye,He,Be,Ge,Lt,Mt,Vi,at,ei,di,ci,Yi;const Zt=T.GetClipFactor(q.position,de.position,H,X);let zi=ue,ti=ue;if(g&&v){const wn=q.matrixIndicesOverride?0:q.vertexIdxForBones,fa=(ge=q.matrixIndicesOverride)!==null&&ge!==void 0?ge:g,ao=(ve=q.matrixWeightsOverride)!==null&&ve!==void 0?ve:v,pa=de.matrixIndicesOverride?0:de.vertexIdxForBones,Zs=(be=de.matrixIndicesOverride)!==null&&be!==void 0?be:g,Ue=(Le=de.matrixWeightsOverride)!==null&&Le!==void 0?Le:v;zi=[0,0,0,0],ti=[0,0,0,0];let ke=0;for(let $e=0;$e<4;++$e)if(ao[wn+$e]>0){const Wt=te(Zs,fa[wn+$e],pa,4);zi[ke]=fa[wn+$e],ti[ke]=ye.Lerp(ao[wn+$e],Wt>=0?Ue[Wt]:0,Zt),ke++}for(let $e=0;$e<4&&ke<4;++$e){const Wt=Zs[pa+$e];te(fa,Wt,wn,4)===-1&&(zi[ke]=Wt,ti[ke]=ye.Lerp(0,Ue[pa+$e],Zt),ke++)}const Je=ti[0]+ti[1]+ti[2]+ti[3];ti[0]/=Je,ti[1]/=Je,ti[2]/=Je,ti[3]/=Je}const gs=q.localPositionOverride?q.localPositionOverride[0]:(Ye=f==null?void 0:f[q.vertexIdx])!==null&&Ye!==void 0?Ye:0,br=q.localPositionOverride?q.localPositionOverride[1]:(He=f==null?void 0:f[q.vertexIdx+1])!==null&&He!==void 0?He:0,gn=q.localPositionOverride?q.localPositionOverride[2]:(Be=f==null?void 0:f[q.vertexIdx+2])!==null&&Be!==void 0?Be:0,Yn=de.localPositionOverride?de.localPositionOverride[0]:(Ge=f==null?void 0:f[de.vertexIdx])!==null&&Ge!==void 0?Ge:0,Dn=de.localPositionOverride?de.localPositionOverride[1]:(Lt=f==null?void 0:f[de.vertexIdx+1])!==null&&Lt!==void 0?Lt:0,jr=de.localPositionOverride?de.localPositionOverride[2]:(Mt=f==null?void 0:f[de.vertexIdx+2])!==null&&Mt!==void 0?Mt:0,Wr=q.localNormalOverride?q.localNormalOverride[0]:(Vi=p==null?void 0:p[q.vertexIdx])!==null&&Vi!==void 0?Vi:0,$n=q.localNormalOverride?q.localNormalOverride[1]:(at=p==null?void 0:p[q.vertexIdx+1])!==null&&at!==void 0?at:0,On=q.localNormalOverride?q.localNormalOverride[2]:(ei=p==null?void 0:p[q.vertexIdx+2])!==null&&ei!==void 0?ei:0,vn=de.localNormalOverride?de.localNormalOverride[0]:(di=p==null?void 0:p[de.vertexIdx])!==null&&di!==void 0?di:0,Nn=de.localNormalOverride?de.localNormalOverride[1]:(ci=p==null?void 0:p[de.vertexIdx+1])!==null&&ci!==void 0?ci:0,hn=de.localNormalOverride?de.localNormalOverride[2]:(Yi=p==null?void 0:p[de.vertexIdx+2])!==null&&Yi!==void 0?Yi:0,xn=Wr+(vn-Wr)*Zt,Qr=$n+(Nn-$n)*Zt,ur=On+(hn-On)*Zt,da=Math.sqrt(xn*xn+Qr*Qr+ur*ur);return new D_(T.Lerp(q.position,de.position,Zt),T.Lerp(q.normal,de.normal,Zt).normalize(),Re.Lerp(q.uv,de.uv,Zt),-1,-1,f?[gs+(Yn-gs)*Zt,br+(Dn-br)*Zt,gn+(jr-gn)*Zt]:null,p?[xn/da,Qr/da,ur/da]:null,zi,ti)};let _e=null;w.length>3&&(_e=[]);for(let q=0;q0,Lt=He>0,Mt=Be>0;switch(de=(Ge?1:0)+(Lt?1:0)+(Mt?1:0),de){case 0:w.length>3?(_e.push(w[q]),_e.push(w[q+1]),_e.push(w[q+2])):_e=w;break;case 1:if(_e=_e??new Array,Ge&&(ge=w[q+1],ve=w[q+2],be=Q(w[q],ge),Le=Q(w[q],ve)),Lt){ge=w[q],ve=w[q+2],be=Q(w[q+1],ge),Le=Q(w[q+1],ve),_e.push(be),_e.push(ve.clone()),_e.push(ge.clone()),_e.push(ve.clone()),_e.push(be.clone()),_e.push(Le);break}Mt&&(ge=w[q],ve=w[q+1],be=Q(w[q+2],ge),Le=Q(w[q+2],ve)),ge&&ve&&be&&Le&&(_e.push(ge.clone()),_e.push(ve.clone()),_e.push(be),_e.push(Le),_e.push(be.clone()),_e.push(ve.clone()));break;case 2:_e=_e??new Array,Ge||(ge=w[q].clone(),ve=Q(ge,w[q+1]),be=Q(ge,w[q+2]),_e.push(ge),_e.push(ve),_e.push(be)),Lt||(ge=w[q+1].clone(),ve=Q(ge,w[q+2]),be=Q(ge,w[q]),_e.push(ge),_e.push(ve),_e.push(be)),Mt||(ge=w[q+2].clone(),ve=Q(ge,w[q]),be=Q(ge,w[q+1]),_e.push(ge),_e.push(ve),_e.push(be));break}}return _e},me=e instanceof se?e:null,le=me==null?void 0:me._thinInstanceDataStorage.matrixData,ae=(me==null?void 0:me.thinInstanceCount)||1,ce=K.Matrix[0];ce.copyFrom(k.IdentityReadOnly);for(let w=0;wny(o,e,{position:t,normal:i,size:s,angle:r});class Ts{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&G.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&G.Warn("y is not an integer, floor(y) used")}clone(){return new Ts(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&G.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&G.Warn("n not an integer only floor(n) used");const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&G.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&G.Warn("n is not an integer, floor(n) used");const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=T.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Ts(0,0)}}class ay{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Uv("icosahedron","Regular",[[0,Ks,-1],[-Ks,1,0],[-1,0,-Ks],[1,0,-Ks],[Ks,1,0],[0,Ks,1],[-1,0,Ks],[-Ks,-1,0],[0,-Ks,-1],[Ks,-1,0],[1,0,Ks],[0,-Ks,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r=i,n=1,a=0;s!==0&&(r=ye.HCF(i,s)),n=i/r,a=s/r;let l,h,c,u,d;const f=Ts.Zero(),p=new Ts(i,s),_=new Ts(-s,i+s),g=Ts.Zero(),v=Ts.Zero(),E=Ts.Zero();let C=[],S,b,R,I;const N=[],O=this.vertByDist,L=(B,V,Z,ue)=>{S=B+"|"+Z,b=V+"|"+ue,S in t||b in t?S in t&&!(b in t)?t[b]=t[S]:b in t&&!(S in t)&&(t[S]=t[b]):(t[S]=e,t[b]=e,e++),O[Z][0]>2?N[t[S]]=[-O[Z][0],O[Z][1],t[S]]:N[t[S]]=[C[O[Z][0]],O[Z][1],t[S]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let B=0;B<20;B++){if(C=this.IDATA.face[B],c=C[2],u=C[1],d=C[0],R=f.x+"|"+f.y,S=B+"|"+R,S in t||(t[S]=c,N[c]=[C[O[R][0]],O[R][1]]),R=p.x+"|"+p.y,S=B+"|"+R,S in t||(t[S]=u,N[u]=[C[O[R][0]],O[R][1]]),R=_.x+"|"+_.y,S=B+"|"+R,S in t||(t[S]=d,N[d]=[C[O[R][0]],O[R][1]]),l=this.IDATA.edgematch[B][0],h=this.IDATA.edgematch[B][1],h==="B")for(let V=1;V2?N[t[S]]=[-O[R][0],O[R][1],t[S]]:N[t[S]]=[C[O[R][0]],O[R][1],t[S]])}this.closestTo=N,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&s0){const b=ye.HCF(e,t),R=e/b,I=t/b;for(let O=1;Ob.x-R.x),i.sort((b,R)=>b.y-R.y);const a=new Array(e+t+1),l=new Array(e+t+1);for(let b=0;b{const I=b.clone();return R==="A"&&I.rotateNeg120(e,t),R==="B"&&I.rotate120(e,t),I.x<0?I.y:I.x+I.y},f=[],p=[],_=[],g=[],v={},E=[];let C=-1,S=-1;for(let b=0;bb[2]-R[2]),E.sort((b,R)=>b[3]-R[3]),E.sort((b,R)=>b[1]-R[1]),E.sort((b,R)=>b[0]-R[0]);for(let b=0;bt.vecToidx[e+s]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[n][1]>0&&t[i[n][0]].push([n,i[n][1]]):t[12].push([n,i[n][0]]);const s=[];for(let n=0;n<12;n++)s[n]=n;let r=12;for(let n=0;n<12;n++){t[n].sort((a,l)=>a[1]-l[1]);for(let a=0;an[3]-a[3]);for(let n=0;n0;)r=t[l],this.face[r].indexOf(a)>-1?(n=(this.face[r].indexOf(a)+1)%3,a=this.face[r][n],i.push(a),s.push(r),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new Uv("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let h=0;h{s=0,r=0,n=0,a=this.face[c];for(let u=0;u<3;u++)l=this.vertex[a[u]],s+=l[0],r+=l[1],n+=l[2];e.vertex[c]=[s/3,r/3,n/3]});return e}static BuildGeodesicData(e){const t=new Am("Geodesic-m-n","Geodesic",[[0,Ks,-1],[-Ks,1,0],[-1,0,-Ks],[1,0,-Ks],[Ks,1,0],[0,Ks,1],[-1,0,Ks],[-Ks,-1,0],[0,-Ks,-1],[Ks,-1,0],[1,0,Ks],[0,-Ks,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const h=s;s=i,i=h,G.Warn("n > m therefore m and n swapped")}const r=new ay;r.build(i,s);const a={custom:Am.BuildGeodesicData(r),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return Vx(o,a,t)}se._GoldbergMeshParser=(o,e)=>Rm.Parse(o,e);class Rm extends se{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&&(G.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(G.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(G.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(u=1),h.push(u,d);for(let f=0;f<6;f++)u=n.x+a*Math.cos(l+f*Math.PI/3),d=n.y+a*Math.sin(l+f*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,d);for(let f=s;fZe.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>T.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>T.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>T.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>T.FromArray(r));const s=new Rm(e.name,t);return s.goldbergData=i,s}}function XB(o,e){const t=o.size,i=o.sizeX||t||1,s=o.sizeY||t||1,r=o.sizeZ||t||1,n=o.sideOrientation===0?0:o.sideOrientation||De.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let v=0;va){const p=l;l=a,a=p,G.Warn("n > m therefore m and n swapped")}const h=new ay;h.build(a,l);const c=Am.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new Rm(o,t);e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,XB(e,u).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let p=0;p0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function KB(o,e,t,i,s,r){const n=r.glyphs[o]||r.glyphs["?"];if(!n)return null;const a=new $B(s);if(n.o){const l=n.o.split(" ");for(let h=0,c=l.length;h{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))};re.prototype._getGlAlgorithmType=function(o){return o===hi.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(hi.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(o){this._occlusionDataStorage.isOcclusionQueryInProgress=o},enumerable:!1,configurable:!0});Object.defineProperty(hi.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new QB),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(hi.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(o){this._occlusionDataStorage.isOccluded=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(o){this._occlusionDataStorage.occlusionQueryAlgorithmType=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(o){this._occlusionDataStorage.occlusionType=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(o){this._occlusionDataStorage.occlusionRetryCount=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(o){this._occlusionDataStorage.forceRenderingWhenOccluded=o},enumerable:!0,configurable:!0});hi.prototype._checkOcclusionQuery=function(){const o=this._occlusionDataStorage;if(o.occlusionType===hi.OCCLUSION_TYPE_NONE)return o.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return o.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);o.isOcclusionQueryInProgress=!1,o.occlusionInternalRetryCounter=0,o.isOccluded=!(s>0)}else if(o.occlusionInternalRetryCounter++,o.occlusionRetryCount!==-1&&o.occlusionInternalRetryCounter>o.occlusionRetryCount)o.isOcclusionQueryInProgress=!1,o.occlusionInternalRetryCounter=0,o.isOccluded=o.occlusionType===hi.OCCLUSION_TYPE_OPTIMISTIC?!1:o.isOccluded;else return o.occlusionType===hi.OCCLUSION_TYPE_OPTIMISTIC?!1:o.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),e.beginOcclusionQuery(o.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(o.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return o.isOccluded};re.prototype.createTransformFeedback=function(){const o=this._gl.createTransformFeedback();if(!o)throw new Error("Unable to create Transform Feedback");return o};re.prototype.deleteTransformFeedback=function(o){this._gl.deleteTransformFeedback(o)};re.prototype.bindTransformFeedback=function(o){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,o)};re.prototype.beginTransformFeedback=function(o=!0){this._gl.beginTransformFeedback(o?this._gl.POINTS:this._gl.TRIANGLES)};re.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};re.prototype.setTranformFeedbackVaryings=function(o,e){this._gl.transformFeedbackVaryings(o,e,this._gl.INTERLEAVED_ATTRIBS)};re.prototype.bindTransformFeedbackBuffer=function(o){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,o?o.underlyingResource:null)};We.prototype.createExternalTexture=function(o){return null};We.prototype.setExternalTexture=function(o,e){throw new Error("setExternalTexture: This engine does not support external textures!")};We.prototype.updateVideoTexture=function(o,e,t){if(!o||o._isDisabled)return;const i=this._getInternalFormat(o.format),s=this._getRGBABufferInternalSizedFormat(0,o.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,o,!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(!o._workingCanvas){o._workingCanvas=this.createCanvas(o.width,o.height);const n=o._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");o._workingContext=n,o._workingCanvas.width=o.width,o._workingCanvas.height=o.height}o._workingContext.clearRect(0,0,o.width,o.height),o._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,o.width,o.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,o._workingCanvas)}o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),o.isReady=!0}catch{o._isDisabled=!0}};We.prototype.restoreSingleAttachment=function(){const o=this._gl;this.bindAttachments([o.BACK])};We.prototype.restoreSingleAttachmentForRenderTarget=function(){const o=this._gl;this.bindAttachments([o.COLOR_ATTACHMENT0])};We.prototype.buildTextureLayout=function(o){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],i.readBuffer(s[n]),i.drawBuffers(s),i.blitFramebuffer(0,0,a.width,a.height,0,0,a.width,a.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let n=0;n1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"];i.drawBuffers(s)}for(let n=0;n1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(h=e.depthTextureFormat)),N.label=(i=e==null?void 0:e.label)!==null&&i!==void 0?i:"MultiRenderTargetWrapper";const O=this._gl,L=O.createFramebuffer();this._bindUnboundFramebuffer(L);const B=o.width||o,V=o.height||o,Z=[],ue=[],oe=this.webGLVersion>1&&l&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),me=this._setupFramebufferDepthAttachments(!oe&&a,!l&&n,B,V);N._framebuffer=L,N._depthStencilBuffer=me,N._generateDepthBuffer=!l&&n,N._generateStencilBuffer=!oe&&a,N._attachments=ue;for(let le=0;le1||this.isWebGPU);const Q=this.webGLVersion>1,_e=O[Q?"COLOR_ATTACHMENT"+le:"COLOR_ATTACHMENT"+le+"_WEBGL"];if(ue.push(_e),H===-1)continue;const q=new Ti(this,Vt.MultiRenderTarget);Z[le]=q,O.activeTexture(O["TEXTURE"+le]),O.bindTexture(H,q._hardwareTexture.underlyingResource),O.texParameteri(H,O.TEXTURE_MAG_FILTER,te.mag),O.texParameteri(H,O.TEXTURE_MIN_FILTER,te.min),O.texParameteri(H,O.TEXTURE_WRAP_S,O.CLAMP_TO_EDGE),O.texParameteri(H,O.TEXTURE_WRAP_T,O.CLAMP_TO_EDGE);const de=this._getRGBABufferInternalSizedFormat(ce,w,ie),ge=this._getInternalFormat(w),ve=this._getWebGLTextureType(ce);if(Q&&(H===35866||H===32879))H===35866?q.is2DArray=!0:q.is3D=!0,q.baseDepth=q.depth=X,O.texImage3D(H,0,de,B,V,X,0,ge,ve,null);else if(H===34067){for(let be=0;be<6;be++)O.texImage2D(O.TEXTURE_CUBE_MAP_POSITIVE_X+be,0,de,B,V,0,ge,ve,null);q.isCube=!0}else O.texImage2D(O.TEXTURE_2D,0,de,B,V,0,ge,ve,null);r&&O.generateMipmap(H),this._bindTextureDirectly(H,null),q.baseWidth=B,q.baseHeight=V,q.width=B,q.height=V,q.isReady=!0,q.samples=1,q.generateMipMaps=r,q.samplingMode=ae,q.type=ce,q._useSRGBBuffer=ie,q.format=w,this._internalTexturesCache.push(q)}if(l&&this._caps.depthTextureExtension){const le=new Ti(this,Vt.Depth);let ae=5,ce=O.DEPTH_COMPONENT16,ie=O.DEPTH_COMPONENT,w=O.UNSIGNED_SHORT,H=O.DEPTH_ATTACHMENT;this.webGLVersion<2?ce=O.DEPTH_COMPONENT:h===14?(ae=1,w=O.FLOAT,ce=O.DEPTH_COMPONENT32F):h===18?(ae=0,w=O.FLOAT_32_UNSIGNED_INT_24_8_REV,ce=O.DEPTH32F_STENCIL8,ie=O.DEPTH_STENCIL,H=O.DEPTH_STENCIL_ATTACHMENT):h===16?(ae=0,w=O.UNSIGNED_INT,ce=O.DEPTH_COMPONENT24,H=O.DEPTH_ATTACHMENT):(h===13||h===17)&&(ae=12,w=O.UNSIGNED_INT_24_8,ce=O.DEPTH24_STENCIL8,ie=O.DEPTH_STENCIL,H=O.DEPTH_STENCIL_ATTACHMENT),O.activeTexture(O.TEXTURE0),O.bindTexture(O.TEXTURE_2D,le._hardwareTexture.underlyingResource),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,O.NEAREST),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,O.NEAREST),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,O.CLAMP_TO_EDGE),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,O.CLAMP_TO_EDGE),O.texImage2D(O.TEXTURE_2D,0,ce,B,V,0,ie,w,null),O.framebufferTexture2D(O.FRAMEBUFFER,H,O.TEXTURE_2D,le._hardwareTexture.underlyingResource,0),le.baseWidth=B,le.baseHeight=V,le.width=B,le.height=V,le.isReady=!0,le.samples=1,le.generateMipMaps=r,le.samplingMode=1,le.format=h,le.type=ae,Z[c]=le,this._internalTexturesCache.push(le)}return N.setTextures(Z),t&&O.drawBuffers(ue),this._bindUnboundFramebuffer(null),N.setLayerAndFaceIndices(R,b),this.resetTextureCache(),N};We.prototype.updateMultipleRenderTargetTextureSampleCount=function(o,e,t=!0){if(this.webGLVersion<2||!o||!o.texture)return 1;if(o.samples===e)return e;const i=o._attachments.length;if(i===0)return 1;const s=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const r=!!o._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(o._depthStencilBuffer),o._depthStencilBuffer=null),o._MSAAFramebuffer&&(s.deleteFramebuffer(o._MSAAFramebuffer),o._MSAAFramebuffer=null),e>1&&typeof s.renderbufferStorageMultisample=="function"){const n=s.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");o._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const a=[];for(let l=0;l1?"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,a.push(u)}t&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(o._framebuffer);return r&&(o._depthStencilBuffer=this._setupFramebufferDepthAttachments(o._generateStencilBuffer,o._generateDepthBuffer,o.texture.width,o.texture.height,e)),this._bindUnboundFramebuffer(null),e};We.prototype._createDepthStencilCubeTexture=function(o,e,t){const i=new Ti(this,Vt.DepthStencil);if(i.isCube=!0,this.webGLVersion===1)return G.Error("Depth cube texture is not supported by WebGL 1."),i;const s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},e),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,o,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),t._depthStencilTexture=i,t._depthStencilTextureWithStencil=s.generateStencil;for(let n=0;n<6;n++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH24_STENCIL8,o,o,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH_COMPONENT24,o,o,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i};We.prototype._partialLoadFile=function(o,e,t,i,s=null){const r=a=>{t[e]=a,t._internalCount++,t._internalCount===6&&i(t)},n=(a,l)=>{s&&a&&s(a.status+" "+a.statusText,l)};this._loadFile(o,r,void 0,void 0,!0,n)};We.prototype._cascadeLoadFiles=function(o,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};We.prototype._cascadeLoadImgs=function(o,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(i[a],a,n,o,e,t,s,r)};We.prototype._partialLoadImg=function(o,e,t,i,s,r,n=null,a){const l=du();Zf(o,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,a),i&&i.addPendingData(l)};We.prototype._setCubeMapTextureParams=function(o,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),o.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),o._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};We.prototype.createCubeTextureBase=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d=null,f=null,p=!1){const _=u||new Ti(this,Vt.Cube);_.isCube=!0,_.url=o,_.generateMipMaps=!i,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!i),_!==u&&(_.label=o.substring(0,60)),this._doNotHandleContextLost||(_._extension=a,_._files=t);const g=o;this._transformTextureUrl&&!u&&(o=this._transformTextureUrl(o));const v=o.split("?")[0],E=v.lastIndexOf("."),C=a||(E>-1?v.substring(E).toLowerCase():"");let S=null;for(const R of We._TextureLoaders)if(R.canLoad(C)){S=R;break}const b=(R,I)=>{o===g?r&&R&&r(R.status+" "+R.statusText,I):(G.Warn(`Failed to load ${o}, falling back to the ${g}`),this.createCubeTextureBase(g,e,t,!!i,s,r,n,a,l,h,c,_,d,f,p))};if(S){const R=I=>{d&&d(_,I),S.loadCubeData(I,_,l,s,r)};t&&t.length===6?S.supportCascades?this._cascadeLoadFiles(e,I=>R(I.map(N=>new Uint8Array(N))),t,r):r?r("Textures type does not support cascades."):G.Warn("Texture loader does not support cascades."):this._loadFile(o,I=>R(new Uint8Array(I)),void 0,void 0,!0,b)}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,_,(R,I)=>{f&&f(R,I)},t,r)}return this._internalTexturesCache.push(_),_};We.prototype.createCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d,f=!1){const p=this._gl;return this.createCubeTextureBase(o,e,t,!!i,s,r,n,a,l,h,c,u,_=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),(_,g)=>{const v=this.needPOTTextures?We.GetExponentOfTwo(g[0].width,this._caps.maxCubemapTextureSize):g[0].width,E=v,C=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const S=n?this._getInternalFormat(n,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let b=n?this._getInternalFormat(n):p.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(b=S);for(let R=0;R{this.unRegisterView(o)}),s};re.prototype.unRegisterView=function(o){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===o){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};re.prototype._renderViewStep=function(o){const e=o.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();ly.notifyObservers(o);const s=o.camera;let r=null,n=null,a=null;if(s&&(a=Array.isArray(s)?s[0].getScene():s.getScene(),r=a.activeCamera,n=a.activeCameras,this.activeView=o,Array.isArray(s)?a.activeCameras=s:(a.activeCamera=s,a.activeCameras=null)),o.customResize)o.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(),o.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),a&&(a.activeCameras=n,a.activeCamera=r),hy.notifyObservers(o),!0)};re.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)};We.prototype.createStorageBuffer=function(o,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};We.prototype.updateStorageBuffer=function(o,e,t,i){};We.prototype.readFromStorageBuffer=function(o,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};We.prototype.setStorageBuffer=function(o,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function ZB(o){const e=r=>{const n="\\b"+r+"\\b";return o&&(o===r||o.match(new RegExp(n,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return o;const t=o.lastIndexOf("."),i=o.lastIndexOf("?"),s=i>-1?o.substring(i,o.length):"";return(t>-1?o.substring(0,t):o)+this._textureFormatInUse+s}Object.defineProperty(re.prototype,"texturesSupported",{get:function(){const o=[];return this._caps.astc&&o.push("-astc.ktx"),this._caps.s3tc&&o.push("-dxt.ktx"),this._caps.pvrtc&&o.push("-pvrtc.ktx"),this._caps.etc2&&o.push("-etc2.ktx"),this._caps.etc1&&o.push("-etc1.ktx"),o},enumerable:!0,configurable:!0});Object.defineProperty(re.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});re.prototype.setCompressedTextureExclusions=function(o){this._excludedCompressedTextures=o};re.prototype.setTextureFormatToUse=function(o){const e=this.texturesSupported;for(let t=0,i=e.length;t{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}}qh.DEFAULT_BUFFER_SIZE=65536;const No=[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))],JB=[()=>1,o=>o.y,o=>o.z,o=>o.x,o=>o.x*o.y,o=>o.y*o.z,o=>3*o.z*o.z-1,o=>o.x*o.z,o=>o.x*o.x-o.y*o.y],pl=(o,e)=>No[o]*JB[o](e),_l=[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 su{constructor(){this.preScaled=!1,this.l00=T.Zero(),this.l1_1=T.Zero(),this.l10=T.Zero(),this.l11=T.Zero(),this.l2_2=T.Zero(),this.l2_1=T.Zero(),this.l20=T.Zero(),this.l21=T.Zero(),this.l22=T.Zero()}addLight(e,t,i){K.Vector3[0].set(t.r,t.g,t.b);const s=K.Vector3[0],r=K.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(pl(0,e),K.Vector3[2]),this.l00.addInPlace(K.Vector3[2]),r.scaleToRef(pl(1,e),K.Vector3[2]),this.l1_1.addInPlace(K.Vector3[2]),r.scaleToRef(pl(2,e),K.Vector3[2]),this.l10.addInPlace(K.Vector3[2]),r.scaleToRef(pl(3,e),K.Vector3[2]),this.l11.addInPlace(K.Vector3[2]),r.scaleToRef(pl(4,e),K.Vector3[2]),this.l2_2.addInPlace(K.Vector3[2]),r.scaleToRef(pl(5,e),K.Vector3[2]),this.l2_1.addInPlace(K.Vector3[2]),r.scaleToRef(pl(6,e),K.Vector3[2]),this.l20.addInPlace(K.Vector3[2]),r.scaleToRef(pl(7,e),K.Vector3[2]),this.l21.addInPlace(K.Vector3[2]),r.scaleToRef(pl(8,e),K.Vector3[2]),this.l22.addInPlace(K.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(_l[0]),this.l1_1.scaleInPlace(_l[1]),this.l10.scaleInPlace(_l[2]),this.l11.scaleInPlace(_l[3]),this.l2_2.scaleInPlace(_l[4]),this.l2_1.scaleInPlace(_l[5]),this.l20.scaleInPlace(_l[6]),this.l21.scaleInPlace(_l[7]),this.l22.scaleInPlace(_l[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(No[0]),this.l1_1.scaleInPlace(No[1]),this.l10.scaleInPlace(No[2]),this.l11.scaleInPlace(No[3]),this.l2_2.scaleInPlace(No[4]),this.l2_1.scaleInPlace(No[5]),this.l20.scaleInPlace(No[6]),this.l21.scaleInPlace(No[7]),this.l22.scaleInPlace(No[8])}updateFromArray(e){return T.FromArrayToRef(e[0],0,this.l00),T.FromArrayToRef(e[1],0,this.l1_1),T.FromArrayToRef(e[2],0,this.l10),T.FromArrayToRef(e[3],0,this.l11),T.FromArrayToRef(e[4],0,this.l2_2),T.FromArrayToRef(e[5],0,this.l2_1),T.FromArrayToRef(e[6],0,this.l20),T.FromArrayToRef(e[7],0,this.l21),T.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return T.FromFloatsToRef(e[0],e[1],e[2],this.l00),T.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),T.FromFloatsToRef(e[6],e[7],e[8],this.l10),T.FromFloatsToRef(e[9],e[10],e[11],this.l11),T.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),T.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),T.FromFloatsToRef(e[18],e[19],e[20],this.l20),T.FromFloatsToRef(e[21],e[22],e[23],this.l21),T.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new su().updateFromArray(e)}static FromPolynomial(e){const t=new su;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 ph{constructor(){this.x=T.Zero(),this.y=T.Zero(),this.z=T.Zero(),this.xx=T.Zero(),this.yy=T.Zero(),this.zz=T.Zero(),this.xy=T.Zero(),this.yz=T.Zero(),this.zx=T.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=su.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){K.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=K.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),K.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),K.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(K.Vector3[0]).addInPlace(K.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(K.Vector3[0]).subtractInPlace(K.Vector3[1]),this.zz.copyFrom(e.l00),K.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(K.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 ph().updateFromHarmonics(e)}static FromArray(e){const t=new ph;return T.FromArrayToRef(e[0],0,t.x),T.FromArrayToRef(e[1],0,t.y),T.FromArrayToRef(e[2],0,t.z),T.FromArrayToRef(e[3],0,t.xx),T.FromArrayToRef(e[4],0,t.yy),T.FromArrayToRef(e[5],0,t.zz),T.FromArrayToRef(e[6],0,t.yz),T.FromArrayToRef(e[7],0,t.zx),T.FromArrayToRef(e[8],0,t.xy),t}}const e2="rgbdDecodePixelShader",t2=`varying vec2 vUV;uniform sampler2D textureSampler; +}`;ne.ShadersStore[BB]=VB;se._LinesMeshParser=(o,e)=>ph.Parse(o,e);class ph extends se{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,r,n,a,l){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new Te(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:[P.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};a===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),n?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(P.ColorKind)):(c.uniforms.push("color"),this._color4=new Ze),l?this.material=l:(this.material=new wa("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=Ie.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(Ie.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(Ie.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 ph(e,this.getScene(),t,this,i)}createInstance(e){const t=new jb(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 ph(e.name,t);return i.color=Te.FromArray(e.color),i.alpha=e.alpha,i}}class jb extends px{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Qb(o){const e=[],t=[],i=o.lines,s=o.colors,r=[];let n=0;for(let l=0;l0&&(e.push(n-1),e.push(n)),n++}}const a=new Oe;return a.indices=e,a.positions=t,s&&(a.colors=r),a}function Zb(o){const e=o.dashSize||3,t=o.gapSize||1,i=o.dashNb||200,s=o.points,r=[],n=[],a=T.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,p=0;for(p=0;p{const u=T.Zero(),d=c.length/6;let f=0,p=0,_=0,g=0,v=0,E=0,C=0,S=0;for(C=0;Cym(o,{points:e,updatable:i,instance:s},t);se.CreateDashedLines=(o,e,t,i,s,r=null,n,a)=>ey(o,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:a},r);class UB extends Re{constructor(e,t){super(e.x,e.y),this.index=t}}class pv{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new UB(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new Re(this.elements[0].x,this.elements[0].y),t=new Re(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class kB{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new pv,this._outlinepoints=new pv,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||ht.LastCreatedScene;let r;t instanceof Q_?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&G.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new pv;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 se(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(P.PositionKind,r.positions,e),s.setVerticesData(P.NormalKind,r.normals,e),s.setVerticesData(P.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Oe,s=[],r=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),r.push(c.x,0,c.y),n.push((c.x-a.min.x)/a.width,(c.y-a.min.y)/a.height)});const l=[],h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){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-a.min.x)/a.width,1-(d.y-a.min.y)/a.height)});const u=l.length;for(let d=0;d{this._addSide(r,s,n,l,a,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,a,l,h){let c=e.length/3,u=0;for(let d=0;dh?I<$t-1?b=new T(f.x,0,f.y).subtract(new T(p.x,0,p.y)).normalize():b=E.add(v).normalize():b=S;const N=T.Dot(C,v);N>h?N<$t-1?R=new T(p.x,0,p.y).subtract(new T(f.x,0,f.y)).normalize():R=C.add(v).normalize():R=S,i.push(u/r.width,0),i.push(u/r.width,1),u+=v.length(),i.push(u/r.width,0),i.push(u/r.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(R.x,R.y,R.z),t.push(R.x,R.y,R.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 ty(o,e,t,i,s,r,n){const a=t||new Array(3),l=i,h=[],c=n||!1;for(let O=0;O<3;O++)a[O]===void 0&&(a[O]=new Dt(0,0,1,1)),l&&l[O]===void 0&&(l[O]=new Ze(1,1,1,1));const u=o.getVerticesData(P.PositionKind),d=o.getVerticesData(P.NormalKind),f=o.getVerticesData(P.UVKind),p=o.getIndices(),_=u.length/9;let g=0,v=0,E=0,C=0,S=0;const b=[0];if(c)for(let O=_;OBx(o,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);se.ExtrudePolygon=(o,e,t,i,s,r,n,a=earcut)=>Vx(o,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,a);function Ux(o,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,a=e.cap===0?0:e.cap||se.NO_CAP,l=e.updatable,h=se._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return sy(o,s,i,r,n,null,null,f,d,a,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function iy(o,e,t=null){const i=e.path,s=e.shape,r=e.scaleFunction||(()=>1),n=e.rotationFunction||(()=>0),a=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||se.NO_CAP,c=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,f=se._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,_=e.invertUV||!1;return sy(o,s,i,null,null,r,n,a,l,h,!0,t,!!c,f,p||null,_,e.frontUVs||null,e.backUVs||null,u,d)}function sy(o,e,t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C){const S=(O,L,B,V,Z,ue,oe,me,le,ae,ce)=>{const ie=B.getTangents(),w=B.getNormals(),H=B.getBinormals(),X=B.getDistances();if(ce){for(let Le=0;Le0){let Ye=ie[Le-1];T.Dot(Ye,ie[Le])<0&&ie[Le].scaleInPlace(-1),Ye=w[Le-1],T.Dot(Ye,w[Le])<0&&w[Le].scaleInPlace(-1),Ye=H[Le-1],T.Dot(Ye,H[Le])<0&&H[Le].scaleInPlace(-1)}}let te=0;const Q=()=>Z!==null?Z:1,q=ae&&me?me:()=>ue!==null?ue:0,de=ae&&oe?oe:Q;let ge=le===se.NO_CAP||le===se.CAP_END?0:2;const ve=K.Matrix[0];for(let Le=0;Le{const Ye=Array(),He=T.Zero();let Be;for(Be=0;Be3?0:h,R=S(e,t,b,I,i,s,r,n,h,c,C);const N=qh(o,{pathArray:R,closeArray:a,closePath:l,updatable:d,sideOrientation:f,invertUV:_,frontUVs:g||void 0,backUVs:v||void 0},u);return N._creationDataStorage.pathArray=R,N._creationDataStorage.path3D=b,N._creationDataStorage.cap=h,N}se.ExtrudeShape=(o,e,t,i,s,r,n=null,a,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||se.NO_CAP,sideOrientation:l,instance:h,updatable:a};return Ux(o,c,n)};se.ExtrudeShapeCustom=(o,e,t,i,s,r,n,a,l,h,c,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:a===0?0:a||se.NO_CAP,sideOrientation:c,instance:u,updatable:h};return iy(o,d,l)};function ry(o,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,a=e.tessellation||64,l=e.clip||0,h=e.updatable,c=se._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||se.NO_CAP,d=Math.PI*2,f=[],p=e.invertUV||!1;let _=0,g=0;const v=d/a*i;let E,C;for(_=0;_<=a-l;_++){for(C=[],(u==se.CAP_START||u==se.CAP_ALL)&&(C.push(new T(0,r[0].y,0)),C.push(new T(Math.cos(_*v)*r[0].x*n,r[0].y,Math.sin(_*v)*r[0].x*n))),g=0;gry(o,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function ny(o,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,a=e.radiusFunction||null;let l=e.cap||se.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=se._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(v,E,C,S,b,R,I,N)=>{const O=E.getTangents(),L=E.getNormals(),B=E.getDistances(),Z=Math.PI*2/b*N,oe=R||(()=>S);let me,le,ae,ce;const ie=K.Matrix[0];let w=I===se.NO_CAP||I===se.CAP_END?0:2;for(let X=0;X{const Q=Array();for(let _e=0;_e3?0:l,p=d(i,f,_,r,n,a,l,e.arc);const g=qh(o,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return g._creationDataStorage.pathArray=p,g._creationDataStorage.path3D=f,g._creationDataStorage.tessellation=n,g._creationDataStorage.cap=l,g._creationDataStorage.arc=e.arc,g._creationDataStorage.radius=r,g}se.CreateTube=(o,e,t,i,s,r,n,a,l,h)=>ny(o,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:l,instance:h},n);function ay(o){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=o.type&&(o.type<0||o.type>=e.length)?0:o.type||0,i=o.size,s=o.sizeX||i||1,r=o.sizeY||i||1,n=o.sizeZ||i||1,a=o.custom||e[t],l=a.face.length,h=o.faceUV||new Array(l),c=o.faceColors,u=o.flat===void 0?!0:o.flat,d=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,f=[],p=[],_=[],g=[],v=[];let E=0,C=0;const S=[];let b=0,R=0,I,N,O,L,B,V;if(u)for(R=0;Rkx(o,e,t);const GB=new T(1,0,0),zB=new T(-1,0,0),WB=new T(0,1,0),HB=new T(0,-1,0),XB=new T(0,0,1),YB=new T(0,0,-1);class D_{constructor(e=T.Zero(),t=T.Up(),i=Re.Zero(),s=0,r=0,n=null,a=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=a,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new D_(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)===null||e===void 0?void 0:e.slice(),(t=this.localNormalOverride)===null||t===void 0?void 0:t.slice(),(i=this.matrixIndicesOverride)===null||i===void 0?void 0:i.slice(),(s=this.matrixWeightsOverride)===null||s===void 0?void 0:s.slice())}}function oy(o,e,t){var i,s,r,n;const a=!!e.skeleton,l=t.localMode||a,h=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,c=e.getIndices(),u=a?e.getPositionData(!0,!0):e.getVerticesData(P.PositionKind),d=a?e.getNormalsData(!0,!0):e.getVerticesData(P.NormalKind),f=l?a?e.getVerticesData(P.PositionKind):u:null,p=l?a?e.getVerticesData(P.NormalKind):d:null,_=e.getVerticesData(P.UVKind),g=a?e.getVerticesData(P.MatricesIndicesKind):null,v=a?e.getVerticesData(P.MatricesWeightsKind):null,E=a?e.getVerticesData(P.MatricesIndicesExtraKind):null,C=a?e.getVerticesData(P.MatricesWeightsExtraKind):null,S=t.position||T.Zero();let b=t.normal||T.Up();const R=t.size||T.One(),I=t.angle||0;if(!b){const w=new T(0,0,1),H=e.getScene().activeCamera,X=T.TransformCoordinates(w,H.getWorldMatrix());b=H.globalPosition.subtract(X)}const N=-Math.atan2(b.z,b.x)-Math.PI/2,O=Math.sqrt(b.x*b.x+b.z*b.z),L=Math.atan2(b.y,O),B=new Oe;B.indices=[],B.positions=[],B.normals=[],B.uvs=[],B.matricesIndices=a?[]:null,B.matricesWeights=a?[]:null,B.matricesIndicesExtra=E?[]:null,B.matricesWeightsExtra=C?[]:null;let V=0;const Z=(w,H)=>{const X=new D_;if(!c||!u||!d)return X;const te=c[w];if(X.vertexIdx=te*3,X.vertexIdxForBones=te*4,X.position=new T(u[te*3],u[te*3+1],u[te*3+2]),T.TransformCoordinatesToRef(X.position,H,X.position),X.normal=new T(d[te*3],d[te*3+1],d[te*3+2]),T.TransformNormalToRef(X.normal,H,X.normal),t.captureUVS&&_){const Q=_[te*2+1];X.uv=new Re(_[te*2],pi.UseOpenGLOrientationForUV?1-Q:Q)}return X},ue=[0,0,0,0],oe=(w,H)=>{if(w.length===0)return w;const X=.5*Math.abs(T.Dot(R,H)),te=(q,de,ge,ve)=>{for(let be=0;be{var ge,ve,be,Le,Ye,He,Be,Ge,Bt,Mt,Vi,at,ei,di,ci,Yi;const Zt=T.GetClipFactor(q.position,de.position,H,X);let zi=ue,ti=ue;if(g&&v){const wn=q.matrixIndicesOverride?0:q.vertexIdxForBones,fa=(ge=q.matrixIndicesOverride)!==null&&ge!==void 0?ge:g,ao=(ve=q.matrixWeightsOverride)!==null&&ve!==void 0?ve:v,pa=de.matrixIndicesOverride?0:de.vertexIdxForBones,Zs=(be=de.matrixIndicesOverride)!==null&&be!==void 0?be:g,Ue=(Le=de.matrixWeightsOverride)!==null&&Le!==void 0?Le:v;zi=[0,0,0,0],ti=[0,0,0,0];let ke=0;for(let $e=0;$e<4;++$e)if(ao[wn+$e]>0){const Wt=te(Zs,fa[wn+$e],pa,4);zi[ke]=fa[wn+$e],ti[ke]=ye.Lerp(ao[wn+$e],Wt>=0?Ue[Wt]:0,Zt),ke++}for(let $e=0;$e<4&&ke<4;++$e){const Wt=Zs[pa+$e];te(fa,Wt,wn,4)===-1&&(zi[ke]=Wt,ti[ke]=ye.Lerp(0,Ue[pa+$e],Zt),ke++)}const Je=ti[0]+ti[1]+ti[2]+ti[3];ti[0]/=Je,ti[1]/=Je,ti[2]/=Je,ti[3]/=Je}const gs=q.localPositionOverride?q.localPositionOverride[0]:(Ye=f==null?void 0:f[q.vertexIdx])!==null&&Ye!==void 0?Ye:0,br=q.localPositionOverride?q.localPositionOverride[1]:(He=f==null?void 0:f[q.vertexIdx+1])!==null&&He!==void 0?He:0,vn=q.localPositionOverride?q.localPositionOverride[2]:(Be=f==null?void 0:f[q.vertexIdx+2])!==null&&Be!==void 0?Be:0,Yn=de.localPositionOverride?de.localPositionOverride[0]:(Ge=f==null?void 0:f[de.vertexIdx])!==null&&Ge!==void 0?Ge:0,Dn=de.localPositionOverride?de.localPositionOverride[1]:(Bt=f==null?void 0:f[de.vertexIdx+1])!==null&&Bt!==void 0?Bt:0,jr=de.localPositionOverride?de.localPositionOverride[2]:(Mt=f==null?void 0:f[de.vertexIdx+2])!==null&&Mt!==void 0?Mt:0,Wr=q.localNormalOverride?q.localNormalOverride[0]:(Vi=p==null?void 0:p[q.vertexIdx])!==null&&Vi!==void 0?Vi:0,$n=q.localNormalOverride?q.localNormalOverride[1]:(at=p==null?void 0:p[q.vertexIdx+1])!==null&&at!==void 0?at:0,On=q.localNormalOverride?q.localNormalOverride[2]:(ei=p==null?void 0:p[q.vertexIdx+2])!==null&&ei!==void 0?ei:0,xn=de.localNormalOverride?de.localNormalOverride[0]:(di=p==null?void 0:p[de.vertexIdx])!==null&&di!==void 0?di:0,Nn=de.localNormalOverride?de.localNormalOverride[1]:(ci=p==null?void 0:p[de.vertexIdx+1])!==null&&ci!==void 0?ci:0,hn=de.localNormalOverride?de.localNormalOverride[2]:(Yi=p==null?void 0:p[de.vertexIdx+2])!==null&&Yi!==void 0?Yi:0,Tn=Wr+(xn-Wr)*Zt,Qr=$n+(Nn-$n)*Zt,ur=On+(hn-On)*Zt,da=Math.sqrt(Tn*Tn+Qr*Qr+ur*ur);return new D_(T.Lerp(q.position,de.position,Zt),T.Lerp(q.normal,de.normal,Zt).normalize(),Re.Lerp(q.uv,de.uv,Zt),-1,-1,f?[gs+(Yn-gs)*Zt,br+(Dn-br)*Zt,vn+(jr-vn)*Zt]:null,p?[Tn/da,Qr/da,ur/da]:null,zi,ti)};let _e=null;w.length>3&&(_e=[]);for(let q=0;q0,Bt=He>0,Mt=Be>0;switch(de=(Ge?1:0)+(Bt?1:0)+(Mt?1:0),de){case 0:w.length>3?(_e.push(w[q]),_e.push(w[q+1]),_e.push(w[q+2])):_e=w;break;case 1:if(_e=_e??new Array,Ge&&(ge=w[q+1],ve=w[q+2],be=Q(w[q],ge),Le=Q(w[q],ve)),Bt){ge=w[q],ve=w[q+2],be=Q(w[q+1],ge),Le=Q(w[q+1],ve),_e.push(be),_e.push(ve.clone()),_e.push(ge.clone()),_e.push(ve.clone()),_e.push(be.clone()),_e.push(Le);break}Mt&&(ge=w[q],ve=w[q+1],be=Q(w[q+2],ge),Le=Q(w[q+2],ve)),ge&&ve&&be&&Le&&(_e.push(ge.clone()),_e.push(ve.clone()),_e.push(be),_e.push(Le),_e.push(be.clone()),_e.push(ve.clone()));break;case 2:_e=_e??new Array,Ge||(ge=w[q].clone(),ve=Q(ge,w[q+1]),be=Q(ge,w[q+2]),_e.push(ge),_e.push(ve),_e.push(be)),Bt||(ge=w[q+1].clone(),ve=Q(ge,w[q+2]),be=Q(ge,w[q]),_e.push(ge),_e.push(ve),_e.push(be)),Mt||(ge=w[q+2].clone(),ve=Q(ge,w[q]),be=Q(ge,w[q+1]),_e.push(ge),_e.push(ve),_e.push(be));break}}return _e},me=e instanceof se?e:null,le=me==null?void 0:me._thinInstanceDataStorage.matrixData,ae=(me==null?void 0:me.thinInstanceCount)||1,ce=K.Matrix[0];ce.copyFrom(k.IdentityReadOnly);for(let w=0;woy(o,e,{position:t,normal:i,size:s,angle:r});class Ts{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&G.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&G.Warn("y is not an integer, floor(y) used")}clone(){return new Ts(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&G.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&G.Warn("n not an integer only floor(n) used");const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&G.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&G.Warn("n is not an integer, floor(n) used");const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=T.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Ts(0,0)}}class ly{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Uv("icosahedron","Regular",[[0,Ks,-1],[-Ks,1,0],[-1,0,-Ks],[1,0,-Ks],[Ks,1,0],[0,Ks,1],[-1,0,Ks],[-Ks,-1,0],[0,-Ks,-1],[Ks,-1,0],[1,0,Ks],[0,-Ks,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r=i,n=1,a=0;s!==0&&(r=ye.HCF(i,s)),n=i/r,a=s/r;let l,h,c,u,d;const f=Ts.Zero(),p=new Ts(i,s),_=new Ts(-s,i+s),g=Ts.Zero(),v=Ts.Zero(),E=Ts.Zero();let C=[],S,b,R,I;const N=[],O=this.vertByDist,L=(B,V,Z,ue)=>{S=B+"|"+Z,b=V+"|"+ue,S in t||b in t?S in t&&!(b in t)?t[b]=t[S]:b in t&&!(S in t)&&(t[S]=t[b]):(t[S]=e,t[b]=e,e++),O[Z][0]>2?N[t[S]]=[-O[Z][0],O[Z][1],t[S]]:N[t[S]]=[C[O[Z][0]],O[Z][1],t[S]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let B=0;B<20;B++){if(C=this.IDATA.face[B],c=C[2],u=C[1],d=C[0],R=f.x+"|"+f.y,S=B+"|"+R,S in t||(t[S]=c,N[c]=[C[O[R][0]],O[R][1]]),R=p.x+"|"+p.y,S=B+"|"+R,S in t||(t[S]=u,N[u]=[C[O[R][0]],O[R][1]]),R=_.x+"|"+_.y,S=B+"|"+R,S in t||(t[S]=d,N[d]=[C[O[R][0]],O[R][1]]),l=this.IDATA.edgematch[B][0],h=this.IDATA.edgematch[B][1],h==="B")for(let V=1;V2?N[t[S]]=[-O[R][0],O[R][1],t[S]]:N[t[S]]=[C[O[R][0]],O[R][1],t[S]])}this.closestTo=N,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&s0){const b=ye.HCF(e,t),R=e/b,I=t/b;for(let O=1;Ob.x-R.x),i.sort((b,R)=>b.y-R.y);const a=new Array(e+t+1),l=new Array(e+t+1);for(let b=0;b{const I=b.clone();return R==="A"&&I.rotateNeg120(e,t),R==="B"&&I.rotate120(e,t),I.x<0?I.y:I.x+I.y},f=[],p=[],_=[],g=[],v={},E=[];let C=-1,S=-1;for(let b=0;bb[2]-R[2]),E.sort((b,R)=>b[3]-R[3]),E.sort((b,R)=>b[1]-R[1]),E.sort((b,R)=>b[0]-R[0]);for(let b=0;bt.vecToidx[e+s]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[n][1]>0&&t[i[n][0]].push([n,i[n][1]]):t[12].push([n,i[n][0]]);const s=[];for(let n=0;n<12;n++)s[n]=n;let r=12;for(let n=0;n<12;n++){t[n].sort((a,l)=>a[1]-l[1]);for(let a=0;an[3]-a[3]);for(let n=0;n0;)r=t[l],this.face[r].indexOf(a)>-1?(n=(this.face[r].indexOf(a)+1)%3,a=this.face[r][n],i.push(a),s.push(r),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new Uv("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let h=0;h{s=0,r=0,n=0,a=this.face[c];for(let u=0;u<3;u++)l=this.vertex[a[u]],s+=l[0],r+=l[1],n+=l[2];e.vertex[c]=[s/3,r/3,n/3]});return e}static BuildGeodesicData(e){const t=new Am("Geodesic-m-n","Geodesic",[[0,Ks,-1],[-Ks,1,0],[-1,0,-Ks],[1,0,-Ks],[Ks,1,0],[0,Ks,1],[-1,0,Ks],[-Ks,-1,0],[0,-Ks,-1],[Ks,-1,0],[1,0,Ks],[0,-Ks,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const h=s;s=i,i=h,G.Warn("n > m therefore m and n swapped")}const r=new ly;r.build(i,s);const a={custom:Am.BuildGeodesicData(r),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return kx(o,a,t)}se._GoldbergMeshParser=(o,e)=>Rm.Parse(o,e);class Rm extends se{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&&(G.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(G.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(G.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(u=1),h.push(u,d);for(let f=0;f<6;f++)u=n.x+a*Math.cos(l+f*Math.PI/3),d=n.y+a*Math.sin(l+f*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,d);for(let f=s;fZe.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>T.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>T.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>T.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>T.FromArray(r));const s=new Rm(e.name,t);return s.goldbergData=i,s}}function KB(o,e){const t=o.size,i=o.sizeX||t||1,s=o.sizeY||t||1,r=o.sizeZ||t||1,n=o.sideOrientation===0?0:o.sideOrientation||Oe.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let v=0;va){const p=l;l=a,a=p,G.Warn("n > m therefore m and n swapped")}const h=new ly;h.build(a,l);const c=Am.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new Rm(o,t);e.sideOrientation=se._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,KB(e,u).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let p=0;p0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function QB(o,e,t,i,s,r){const n=r.glyphs[o]||r.glyphs["?"];if(!n)return null;const a=new jB(s);if(n.o){const l=n.o.split(" ");for(let h=0,c=l.length;h{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))};re.prototype._getGlAlgorithmType=function(o){return o===hi.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};Object.defineProperty(hi.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(o){this._occlusionDataStorage.isOcclusionQueryInProgress=o},enumerable:!1,configurable:!0});Object.defineProperty(hi.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new e2),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(hi.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(o){this._occlusionDataStorage.isOccluded=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(o){this._occlusionDataStorage.occlusionQueryAlgorithmType=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(o){this._occlusionDataStorage.occlusionType=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(o){this._occlusionDataStorage.occlusionRetryCount=o},enumerable:!0,configurable:!0});Object.defineProperty(hi.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(o){this._occlusionDataStorage.forceRenderingWhenOccluded=o},enumerable:!0,configurable:!0});hi.prototype._checkOcclusionQuery=function(){const o=this._occlusionDataStorage;if(o.occlusionType===hi.OCCLUSION_TYPE_NONE)return o.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return o.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);o.isOcclusionQueryInProgress=!1,o.occlusionInternalRetryCounter=0,o.isOccluded=!(s>0)}else if(o.occlusionInternalRetryCounter++,o.occlusionRetryCount!==-1&&o.occlusionInternalRetryCounter>o.occlusionRetryCount)o.isOcclusionQueryInProgress=!1,o.occlusionInternalRetryCounter=0,o.isOccluded=o.occlusionType===hi.OCCLUSION_TYPE_OPTIMISTIC?!1:o.isOccluded;else return o.occlusionType===hi.OCCLUSION_TYPE_OPTIMISTIC?!1:o.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),e.beginOcclusionQuery(o.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(o.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return o.isOccluded};re.prototype.createTransformFeedback=function(){const o=this._gl.createTransformFeedback();if(!o)throw new Error("Unable to create Transform Feedback");return o};re.prototype.deleteTransformFeedback=function(o){this._gl.deleteTransformFeedback(o)};re.prototype.bindTransformFeedback=function(o){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,o)};re.prototype.beginTransformFeedback=function(o=!0){this._gl.beginTransformFeedback(o?this._gl.POINTS:this._gl.TRIANGLES)};re.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};re.prototype.setTranformFeedbackVaryings=function(o,e){this._gl.transformFeedbackVaryings(o,e,this._gl.INTERLEAVED_ATTRIBS)};re.prototype.bindTransformFeedbackBuffer=function(o){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,o?o.underlyingResource:null)};We.prototype.createExternalTexture=function(o){return null};We.prototype.setExternalTexture=function(o,e){throw new Error("setExternalTexture: This engine does not support external textures!")};We.prototype.updateVideoTexture=function(o,e,t){if(!o||o._isDisabled)return;const i=this._getInternalFormat(o.format),s=this._getRGBABufferInternalSizedFormat(0,o.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,o,!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(!o._workingCanvas){o._workingCanvas=this.createCanvas(o.width,o.height);const n=o._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");o._workingContext=n,o._workingCanvas.width=o.width,o._workingCanvas.height=o.height}o._workingContext.clearRect(0,0,o.width,o.height),o._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,o.width,o.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,o._workingCanvas)}o.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),o.isReady=!0}catch{o._isDisabled=!0}};We.prototype.restoreSingleAttachment=function(){const o=this._gl;this.bindAttachments([o.BACK])};We.prototype.restoreSingleAttachmentForRenderTarget=function(){const o=this._gl;this.bindAttachments([o.COLOR_ATTACHMENT0])};We.prototype.buildTextureLayout=function(o){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],i.readBuffer(s[n]),i.drawBuffers(s),i.blitFramebuffer(0,0,a.width,a.height,0,0,a.width,a.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let n=0;n1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"];i.drawBuffers(s)}for(let n=0;n1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(h=e.depthTextureFormat)),N.label=(i=e==null?void 0:e.label)!==null&&i!==void 0?i:"MultiRenderTargetWrapper";const O=this._gl,L=O.createFramebuffer();this._bindUnboundFramebuffer(L);const B=o.width||o,V=o.height||o,Z=[],ue=[],oe=this.webGLVersion>1&&l&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),me=this._setupFramebufferDepthAttachments(!oe&&a,!l&&n,B,V);N._framebuffer=L,N._depthStencilBuffer=me,N._generateDepthBuffer=!l&&n,N._generateStencilBuffer=!oe&&a,N._attachments=ue;for(let le=0;le1||this.isWebGPU);const Q=this.webGLVersion>1,_e=O[Q?"COLOR_ATTACHMENT"+le:"COLOR_ATTACHMENT"+le+"_WEBGL"];if(ue.push(_e),H===-1)continue;const q=new Ti(this,Ut.MultiRenderTarget);Z[le]=q,O.activeTexture(O["TEXTURE"+le]),O.bindTexture(H,q._hardwareTexture.underlyingResource),O.texParameteri(H,O.TEXTURE_MAG_FILTER,te.mag),O.texParameteri(H,O.TEXTURE_MIN_FILTER,te.min),O.texParameteri(H,O.TEXTURE_WRAP_S,O.CLAMP_TO_EDGE),O.texParameteri(H,O.TEXTURE_WRAP_T,O.CLAMP_TO_EDGE);const de=this._getRGBABufferInternalSizedFormat(ce,w,ie),ge=this._getInternalFormat(w),ve=this._getWebGLTextureType(ce);if(Q&&(H===35866||H===32879))H===35866?q.is2DArray=!0:q.is3D=!0,q.baseDepth=q.depth=X,O.texImage3D(H,0,de,B,V,X,0,ge,ve,null);else if(H===34067){for(let be=0;be<6;be++)O.texImage2D(O.TEXTURE_CUBE_MAP_POSITIVE_X+be,0,de,B,V,0,ge,ve,null);q.isCube=!0}else O.texImage2D(O.TEXTURE_2D,0,de,B,V,0,ge,ve,null);r&&O.generateMipmap(H),this._bindTextureDirectly(H,null),q.baseWidth=B,q.baseHeight=V,q.width=B,q.height=V,q.isReady=!0,q.samples=1,q.generateMipMaps=r,q.samplingMode=ae,q.type=ce,q._useSRGBBuffer=ie,q.format=w,this._internalTexturesCache.push(q)}if(l&&this._caps.depthTextureExtension){const le=new Ti(this,Ut.Depth);let ae=5,ce=O.DEPTH_COMPONENT16,ie=O.DEPTH_COMPONENT,w=O.UNSIGNED_SHORT,H=O.DEPTH_ATTACHMENT;this.webGLVersion<2?ce=O.DEPTH_COMPONENT:h===14?(ae=1,w=O.FLOAT,ce=O.DEPTH_COMPONENT32F):h===18?(ae=0,w=O.FLOAT_32_UNSIGNED_INT_24_8_REV,ce=O.DEPTH32F_STENCIL8,ie=O.DEPTH_STENCIL,H=O.DEPTH_STENCIL_ATTACHMENT):h===16?(ae=0,w=O.UNSIGNED_INT,ce=O.DEPTH_COMPONENT24,H=O.DEPTH_ATTACHMENT):(h===13||h===17)&&(ae=12,w=O.UNSIGNED_INT_24_8,ce=O.DEPTH24_STENCIL8,ie=O.DEPTH_STENCIL,H=O.DEPTH_STENCIL_ATTACHMENT),O.activeTexture(O.TEXTURE0),O.bindTexture(O.TEXTURE_2D,le._hardwareTexture.underlyingResource),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,O.NEAREST),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,O.NEAREST),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,O.CLAMP_TO_EDGE),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,O.CLAMP_TO_EDGE),O.texImage2D(O.TEXTURE_2D,0,ce,B,V,0,ie,w,null),O.framebufferTexture2D(O.FRAMEBUFFER,H,O.TEXTURE_2D,le._hardwareTexture.underlyingResource,0),le.baseWidth=B,le.baseHeight=V,le.width=B,le.height=V,le.isReady=!0,le.samples=1,le.generateMipMaps=r,le.samplingMode=1,le.format=h,le.type=ae,Z[c]=le,this._internalTexturesCache.push(le)}return N.setTextures(Z),t&&O.drawBuffers(ue),this._bindUnboundFramebuffer(null),N.setLayerAndFaceIndices(R,b),this.resetTextureCache(),N};We.prototype.updateMultipleRenderTargetTextureSampleCount=function(o,e,t=!0){if(this.webGLVersion<2||!o||!o.texture)return 1;if(o.samples===e)return e;const i=o._attachments.length;if(i===0)return 1;const s=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const r=!!o._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(o._depthStencilBuffer),o._depthStencilBuffer=null),o._MSAAFramebuffer&&(s.deleteFramebuffer(o._MSAAFramebuffer),o._MSAAFramebuffer=null),e>1&&typeof s.renderbufferStorageMultisample=="function"){const n=s.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");o._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const a=[];for(let l=0;l1?"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,a.push(u)}t&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(o._framebuffer);return r&&(o._depthStencilBuffer=this._setupFramebufferDepthAttachments(o._generateStencilBuffer,o._generateDepthBuffer,o.texture.width,o.texture.height,e)),this._bindUnboundFramebuffer(null),e};We.prototype._createDepthStencilCubeTexture=function(o,e,t){const i=new Ti(this,Ut.DepthStencil);if(i.isCube=!0,this.webGLVersion===1)return G.Error("Depth cube texture is not supported by WebGL 1."),i;const s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},e),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,o,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),t._depthStencilTexture=i,t._depthStencilTextureWithStencil=s.generateStencil;for(let n=0;n<6;n++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH24_STENCIL8,o,o,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,r.DEPTH_COMPONENT24,o,o,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i};We.prototype._partialLoadFile=function(o,e,t,i,s=null){const r=a=>{t[e]=a,t._internalCount++,t._internalCount===6&&i(t)},n=(a,l)=>{s&&a&&s(a.status+" "+a.statusText,l)};this._loadFile(o,r,void 0,void 0,!0,n)};We.prototype._cascadeLoadFiles=function(o,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};We.prototype._cascadeLoadImgs=function(o,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(i[a],a,n,o,e,t,s,r)};We.prototype._partialLoadImg=function(o,e,t,i,s,r,n=null,a){const l=du();Zf(o,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,a),i&&i.addPendingData(l)};We.prototype._setCubeMapTextureParams=function(o,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),o.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),o._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};We.prototype.createCubeTextureBase=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d=null,f=null,p=!1){const _=u||new Ti(this,Ut.Cube);_.isCube=!0,_.url=o,_.generateMipMaps=!i,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!i),_!==u&&(_.label=o.substring(0,60)),this._doNotHandleContextLost||(_._extension=a,_._files=t);const g=o;this._transformTextureUrl&&!u&&(o=this._transformTextureUrl(o));const v=o.split("?")[0],E=v.lastIndexOf("."),C=a||(E>-1?v.substring(E).toLowerCase():"");let S=null;for(const R of We._TextureLoaders)if(R.canLoad(C)){S=R;break}const b=(R,I)=>{o===g?r&&R&&r(R.status+" "+R.statusText,I):(G.Warn(`Failed to load ${o}, falling back to the ${g}`),this.createCubeTextureBase(g,e,t,!!i,s,r,n,a,l,h,c,_,d,f,p))};if(S){const R=I=>{d&&d(_,I),S.loadCubeData(I,_,l,s,r)};t&&t.length===6?S.supportCascades?this._cascadeLoadFiles(e,I=>R(I.map(N=>new Uint8Array(N))),t,r):r?r("Textures type does not support cascades."):G.Warn("Texture loader does not support cascades."):this._loadFile(o,I=>R(new Uint8Array(I)),void 0,void 0,!0,b)}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,_,(R,I)=>{f&&f(R,I)},t,r)}return this._internalTexturesCache.push(_),_};We.prototype.createCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d,f=!1){const p=this._gl;return this.createCubeTextureBase(o,e,t,!!i,s,r,n,a,l,h,c,u,_=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),(_,g)=>{const v=this.needPOTTextures?We.GetExponentOfTwo(g[0].width,this._caps.maxCubemapTextureSize):g[0].width,E=v,C=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const S=n?this._getInternalFormat(n,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let b=n?this._getInternalFormat(n):p.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(b=S);for(let R=0;R{this.unRegisterView(o)}),s};re.prototype.unRegisterView=function(o){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===o){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};re.prototype._renderViewStep=function(o){const e=o.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();cy.notifyObservers(o);const s=o.camera;let r=null,n=null,a=null;if(s&&(a=Array.isArray(s)?s[0].getScene():s.getScene(),r=a.activeCamera,n=a.activeCameras,this.activeView=o,Array.isArray(s)?a.activeCameras=s:(a.activeCamera=s,a.activeCameras=null)),o.customResize)o.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(),o.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),a&&(a.activeCameras=n,a.activeCamera=r),uy.notifyObservers(o),!0)};re.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)};We.prototype.createStorageBuffer=function(o,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};We.prototype.updateStorageBuffer=function(o,e,t,i){};We.prototype.readFromStorageBuffer=function(o,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};We.prototype.setStorageBuffer=function(o,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function t2(o){const e=r=>{const n="\\b"+r+"\\b";return o&&(o===r||o.match(new RegExp(n,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return o;const t=o.lastIndexOf("."),i=o.lastIndexOf("?"),s=i>-1?o.substring(i,o.length):"";return(t>-1?o.substring(0,t):o)+this._textureFormatInUse+s}Object.defineProperty(re.prototype,"texturesSupported",{get:function(){const o=[];return this._caps.astc&&o.push("-astc.ktx"),this._caps.s3tc&&o.push("-dxt.ktx"),this._caps.pvrtc&&o.push("-pvrtc.ktx"),this._caps.etc2&&o.push("-etc2.ktx"),this._caps.etc1&&o.push("-etc1.ktx"),o},enumerable:!0,configurable:!0});Object.defineProperty(re.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});re.prototype.setCompressedTextureExclusions=function(o){this._excludedCompressedTextures=o};re.prototype.setTextureFormatToUse=function(o){const e=this.texturesSupported;for(let t=0,i=e.length;t{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}}jh.DEFAULT_BUFFER_SIZE=65536;const No=[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))],i2=[()=>1,o=>o.y,o=>o.z,o=>o.x,o=>o.x*o.y,o=>o.y*o.z,o=>3*o.z*o.z-1,o=>o.x*o.z,o=>o.x*o.x-o.y*o.y],pl=(o,e)=>No[o]*i2[o](e),_l=[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 su{constructor(){this.preScaled=!1,this.l00=T.Zero(),this.l1_1=T.Zero(),this.l10=T.Zero(),this.l11=T.Zero(),this.l2_2=T.Zero(),this.l2_1=T.Zero(),this.l20=T.Zero(),this.l21=T.Zero(),this.l22=T.Zero()}addLight(e,t,i){K.Vector3[0].set(t.r,t.g,t.b);const s=K.Vector3[0],r=K.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(pl(0,e),K.Vector3[2]),this.l00.addInPlace(K.Vector3[2]),r.scaleToRef(pl(1,e),K.Vector3[2]),this.l1_1.addInPlace(K.Vector3[2]),r.scaleToRef(pl(2,e),K.Vector3[2]),this.l10.addInPlace(K.Vector3[2]),r.scaleToRef(pl(3,e),K.Vector3[2]),this.l11.addInPlace(K.Vector3[2]),r.scaleToRef(pl(4,e),K.Vector3[2]),this.l2_2.addInPlace(K.Vector3[2]),r.scaleToRef(pl(5,e),K.Vector3[2]),this.l2_1.addInPlace(K.Vector3[2]),r.scaleToRef(pl(6,e),K.Vector3[2]),this.l20.addInPlace(K.Vector3[2]),r.scaleToRef(pl(7,e),K.Vector3[2]),this.l21.addInPlace(K.Vector3[2]),r.scaleToRef(pl(8,e),K.Vector3[2]),this.l22.addInPlace(K.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(_l[0]),this.l1_1.scaleInPlace(_l[1]),this.l10.scaleInPlace(_l[2]),this.l11.scaleInPlace(_l[3]),this.l2_2.scaleInPlace(_l[4]),this.l2_1.scaleInPlace(_l[5]),this.l20.scaleInPlace(_l[6]),this.l21.scaleInPlace(_l[7]),this.l22.scaleInPlace(_l[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(No[0]),this.l1_1.scaleInPlace(No[1]),this.l10.scaleInPlace(No[2]),this.l11.scaleInPlace(No[3]),this.l2_2.scaleInPlace(No[4]),this.l2_1.scaleInPlace(No[5]),this.l20.scaleInPlace(No[6]),this.l21.scaleInPlace(No[7]),this.l22.scaleInPlace(No[8])}updateFromArray(e){return T.FromArrayToRef(e[0],0,this.l00),T.FromArrayToRef(e[1],0,this.l1_1),T.FromArrayToRef(e[2],0,this.l10),T.FromArrayToRef(e[3],0,this.l11),T.FromArrayToRef(e[4],0,this.l2_2),T.FromArrayToRef(e[5],0,this.l2_1),T.FromArrayToRef(e[6],0,this.l20),T.FromArrayToRef(e[7],0,this.l21),T.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return T.FromFloatsToRef(e[0],e[1],e[2],this.l00),T.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),T.FromFloatsToRef(e[6],e[7],e[8],this.l10),T.FromFloatsToRef(e[9],e[10],e[11],this.l11),T.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),T.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),T.FromFloatsToRef(e[18],e[19],e[20],this.l20),T.FromFloatsToRef(e[21],e[22],e[23],this.l21),T.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new su().updateFromArray(e)}static FromPolynomial(e){const t=new su;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 _h{constructor(){this.x=T.Zero(),this.y=T.Zero(),this.z=T.Zero(),this.xx=T.Zero(),this.yy=T.Zero(),this.zz=T.Zero(),this.xy=T.Zero(),this.yz=T.Zero(),this.zx=T.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=su.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){K.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=K.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),K.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),K.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(K.Vector3[0]).addInPlace(K.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(K.Vector3[0]).subtractInPlace(K.Vector3[1]),this.zz.copyFrom(e.l00),K.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(K.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 _h().updateFromHarmonics(e)}static FromArray(e){const t=new _h;return T.FromArrayToRef(e[0],0,t.x),T.FromArrayToRef(e[1],0,t.y),T.FromArrayToRef(e[2],0,t.z),T.FromArrayToRef(e[3],0,t.xx),T.FromArrayToRef(e[4],0,t.yy),T.FromArrayToRef(e[5],0,t.zz),T.FromArrayToRef(e[6],0,t.yz),T.FromArrayToRef(e[7],0,t.zx),T.FromArrayToRef(e[8],0,t.xy),t}}const s2="rgbdDecodePixelShader",r2=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;ne.ShadersStore[e2]=t2;function i2(o,e,t,i=!0){const s=o.getScene(),r=s.getEngine(),n=new ms("resized"+o.name,{width:e,height:t},s,!o.noMipmap,!0,o._texture.type,!1,o.samplingMode,!1);n.wrapU=o.wrapU,n.wrapV=o.wrapV,n.uOffset=o.uOffset,n.vOffset=o.vOffset,n.uScale=o.uScale,n.vScale=o.vScale,n.uAng=o.uAng,n.vAng=o.vAng,n.wAng=o.wAng,n.coordinatesIndex=o.coordinatesIndex,n.level=o.level,n.anisotropicFilteringLevel=o.anisotropicFilteringLevel,n._texture.isReady=!1,o.wrapU=ee.CLAMP_ADDRESSMODE,o.wrapV=ee.CLAMP_ADDRESSMODE;const a=new el("pass",1,null,i?ee.BILINEAR_SAMPLINGMODE:ee.NEAREST_SAMPLINGMODE,r,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled(()=>{a.onApply=function(h){h.setTexture("textureSampler",o)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([a],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),a.dispose(),n.getInternalTexture().isReady=!0)}),n}function Ux(o,e,t,i,s,r,n,a){const l=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,a=a??e.height,i===-1&&(i=0),new Promise(h=>{const c=new lt("postprocess",o,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:a},{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 o_,p0;function Uo(o){o_||(o_=new Float32Array(1),p0=new Int32Array(o_.buffer)),o_[0]=o;const e=p0[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 wo(o){const e=(o&32768)>>15,t=(o&31744)>>10,i=o&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 s2=async(o,e,t,i,s)=>{const r=o.getScene(),n=r.getEngine();let a;if(!o.isCube)a=new lt("lod","lod",["lod","gamma"],null,1,null,ee.NEAREST_NEAREST_MIPNEAREST,n);else{const c=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new lt("lodCube","lodCube",["lod","gamma"],null,1,null,ee.NEAREST_NEAREST_MIPNEAREST,n,!1,c[i])}await new Promise(c=>{a.getEffect().executeWhenCompiled(()=>{c(0)})});const l=new ms("temp",{width:e,height:t},r,!1);a.onApply=function(c){c.setTexture("textureSampler",o),c.setFloat("lod",s),c.setBool("gamma",o.gammaSpace)};const h=o.getInternalTexture();try{if(l.renderTarget&&h){const c=h.samplingMode;s!==0?o.updateSamplingMode(ee.NEAREST_NEAREST_MIPNEAREST):o.updateSamplingMode(ee.NEAREST_NEAREST),r.postProcessManager.directRender([a],l.renderTarget,!0),o.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(),a.dispose()}};async function r2(o,e,t,i=0,s=0){return!o.isReady()&&o._texture&&await new Promise((r,n)=>{if(o._texture===null){n(0);return}o._texture.onLoadedObservable.addOnce(()=>{r(0)})}),await s2(o,e,t,i,s)}const n2={CreateResizedCopy:i2,ApplyPostProcess:Ux,ToHalfFloat:Uo,FromHalfFloat:wo,GetTextureDataAsync:r2};class _0{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 a=()=>{if(n){const l=new lt("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})}};r?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return Ux("rgbdEncode",e,t,i,1,5)}}class yc{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class vu{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;(t=e.getScene())===null||t===void 0||t.getEngine().flushFramebuffer();const i=e.getSize().width,s=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let n,a;e.isRenderTarget?(n=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(n=e.readPixels(2,void 0,void 0,!1),a=e.readPixels(3,void 0,void 0,!1));const l=e.readPixels(4,void 0,void 0,!1),h=e.readPixels(5,void 0,void 0,!1),c=e.gammaSpace,u=5;let d=0;return(e.textureType==1||e.textureType==2)&&(d=1),new Promise(f=>{Promise.all([r,s,n,a,l,h]).then(([p,_,g,v,E,C])=>{const S={size:i,right:_,left:p,up:g,down:v,front:E,back:C,format:u,type:d,gammaSpace:c};f(this.ConvertCubeMapToSphericalPolynomial(S))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new su;let i=0;const s=2/e.size,r=s,n=.5*s,a=n-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],p=e[f.name];let _=a;const g=e.format===5?4:3;for(let v=0;vO){const V=O/B;R*=V,I*=V,N*=V}}else R=ye.Clamp(R,0,O),I=ye.Clamp(I,0,O),N=ye.Clamp(N,0,O);const L=new Te(R,I,N);t.addLight(S,L,b),i+=b,E+=s}_+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),ph.FromHarmonics(t)}}vu._FileFaces=[new yc("right",new T(1,0,0),new T(0,0,-1),new T(0,-1,0)),new yc("left",new T(-1,0,0),new T(0,0,1),new T(0,-1,0)),new yc("up",new T(0,1,0),new T(1,0,0),new T(0,0,1)),new yc("down",new T(0,-1,0),new T(1,0,0),new T(0,0,-1)),new yc("front",new T(0,0,1),new T(1,0,0),new T(0,-1,0)),new yc("back",new T(0,0,-1),new T(-1,0,0),new T(0,-1,0))];vu.MAX_HDRI_VALUE=4096;vu.PRESERVE_CLAMPED_COLORS=!1;Ei.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Ei.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=vu.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(o=>{this._texture._sphericalPolynomial=o,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(o){this._texture&&(this._texture._sphericalPolynomial=o)},enumerable:!0,configurable:!0});const a2="rgbdEncodePixelShader",o2=`varying vec2 vUV;uniform sampler2D textureSampler; +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;ne.ShadersStore[s2]=r2;function n2(o,e,t,i=!0){const s=o.getScene(),r=s.getEngine(),n=new ms("resized"+o.name,{width:e,height:t},s,!o.noMipmap,!0,o._texture.type,!1,o.samplingMode,!1);n.wrapU=o.wrapU,n.wrapV=o.wrapV,n.uOffset=o.uOffset,n.vOffset=o.vOffset,n.uScale=o.uScale,n.vScale=o.vScale,n.uAng=o.uAng,n.vAng=o.vAng,n.wAng=o.wAng,n.coordinatesIndex=o.coordinatesIndex,n.level=o.level,n.anisotropicFilteringLevel=o.anisotropicFilteringLevel,n._texture.isReady=!1,o.wrapU=ee.CLAMP_ADDRESSMODE,o.wrapV=ee.CLAMP_ADDRESSMODE;const a=new el("pass",1,null,i?ee.BILINEAR_SAMPLINGMODE:ee.NEAREST_SAMPLINGMODE,r,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled(()=>{a.onApply=function(h){h.setTexture("textureSampler",o)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([a],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),a.dispose(),n.getInternalTexture().isReady=!0)}),n}function Gx(o,e,t,i,s,r,n,a){const l=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,a=a??e.height,i===-1&&(i=0),new Promise(h=>{const c=new lt("postprocess",o,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:a},{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 o_,m0;function Uo(o){o_||(o_=new Float32Array(1),m0=new Int32Array(o_.buffer)),o_[0]=o;const e=m0[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 wo(o){const e=(o&32768)>>15,t=(o&31744)>>10,i=o&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 a2=async(o,e,t,i,s)=>{const r=o.getScene(),n=r.getEngine();let a;if(!o.isCube)a=new lt("lod","lod",["lod","gamma"],null,1,null,ee.NEAREST_NEAREST_MIPNEAREST,n);else{const c=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new lt("lodCube","lodCube",["lod","gamma"],null,1,null,ee.NEAREST_NEAREST_MIPNEAREST,n,!1,c[i])}await new Promise(c=>{a.getEffect().executeWhenCompiled(()=>{c(0)})});const l=new ms("temp",{width:e,height:t},r,!1);a.onApply=function(c){c.setTexture("textureSampler",o),c.setFloat("lod",s),c.setBool("gamma",o.gammaSpace)};const h=o.getInternalTexture();try{if(l.renderTarget&&h){const c=h.samplingMode;s!==0?o.updateSamplingMode(ee.NEAREST_NEAREST_MIPNEAREST):o.updateSamplingMode(ee.NEAREST_NEAREST),r.postProcessManager.directRender([a],l.renderTarget,!0),o.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(),a.dispose()}};async function o2(o,e,t,i=0,s=0){return!o.isReady()&&o._texture&&await new Promise((r,n)=>{if(o._texture===null){n(0);return}o._texture.onLoadedObservable.addOnce(()=>{r(0)})}),await a2(o,e,t,i,s)}const l2={CreateResizedCopy:n2,ApplyPostProcess:Gx,ToHalfFloat:Uo,FromHalfFloat:wo,GetTextureDataAsync:o2};class g0{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 a=()=>{if(n){const l=new lt("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})}};r?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return Gx("rgbdEncode",e,t,i,1,5)}}class yc{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class vu{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;(t=e.getScene())===null||t===void 0||t.getEngine().flushFramebuffer();const i=e.getSize().width,s=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let n,a;e.isRenderTarget?(n=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(n=e.readPixels(2,void 0,void 0,!1),a=e.readPixels(3,void 0,void 0,!1));const l=e.readPixels(4,void 0,void 0,!1),h=e.readPixels(5,void 0,void 0,!1),c=e.gammaSpace,u=5;let d=0;return(e.textureType==1||e.textureType==2)&&(d=1),new Promise(f=>{Promise.all([r,s,n,a,l,h]).then(([p,_,g,v,E,C])=>{const S={size:i,right:_,left:p,up:g,down:v,front:E,back:C,format:u,type:d,gammaSpace:c};f(this.ConvertCubeMapToSphericalPolynomial(S))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new su;let i=0;const s=2/e.size,r=s,n=.5*s,a=n-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],p=e[f.name];let _=a;const g=e.format===5?4:3;for(let v=0;vO){const V=O/B;R*=V,I*=V,N*=V}}else R=ye.Clamp(R,0,O),I=ye.Clamp(I,0,O),N=ye.Clamp(N,0,O);const L=new Te(R,I,N);t.addLight(S,L,b),i+=b,E+=s}_+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),_h.FromHarmonics(t)}}vu._FileFaces=[new yc("right",new T(1,0,0),new T(0,0,-1),new T(0,-1,0)),new yc("left",new T(-1,0,0),new T(0,0,1),new T(0,-1,0)),new yc("up",new T(0,1,0),new T(1,0,0),new T(0,0,1)),new yc("down",new T(0,-1,0),new T(1,0,0),new T(0,0,-1)),new yc("front",new T(0,0,1),new T(1,0,0),new T(0,-1,0)),new yc("back",new T(0,0,-1),new T(-1,0,0),new T(0,-1,0))];vu.MAX_HDRI_VALUE=4096;vu.PRESERVE_CLAMPED_COLORS=!1;Ei.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Ei.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=vu.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(o=>{this._texture._sphericalPolynomial=o,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(o){this._texture&&(this._texture._sphericalPolynomial=o)},enumerable:!0,configurable:!0});const h2="rgbdEncodePixelShader",c2=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;ne.ShadersStore[a2]=o2;const cy="image/png",m0=2,g0=[134,22,135,150,246,214,150,54];function uy(o){const e=new DataView(o.buffer,o.byteOffset,o.byteLength);let t=0;for(let n=0;nm0)throw new Error(`Unsupported babylon environment map version "${o.version}". Latest supported version is "${m0}".`);return o.version===2||(o=Object.assign(Object.assign({},o),{version:2,imageType:cy})),o}function dy(o,e){e=Im(e);const t=e.specular;let i=ye.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{if(t){const f=e.createTexture(null,!0,!0,null,1,null,p=>{d(p)},o);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=p=>{p._bindTexture("textureSampler",f),p.setFloat2("scale",1,e._features.needsInvertingBitmap&&o 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,o,r,n),a){const f=l[n];f&&e._uploadImageToTexture(f._texture,o,r,0)}u()}})}function h2(o,e,t=cy){if(!fe.IsExponentOfTwo(o.width))throw new Error("Texture size must be a power of two");const i=ye.ILog2(o.width)+1,s=o.getEngine();let r=!1,n=!1,a=null,l=null,h=null;const c=s.getCaps();if(o.format=5,o.type=0,o.generateMipMaps=!0,o._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,o),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,o.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,o.type=1):r=!1:(r=!1,n=!0,h={}),r)a=new lt("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,o.type,void 0,null,!1),o._isRGBD=!1,o.invertY=!1,l=s.createRenderTargetCubeTexture(o.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:o.type,format:5});else if(o._isRGBD=!0,o.invertY=!0,n){const f=o._lodGenerationScale,p=o._lodGenerationOffset;for(let _=0;_<3;_++){const v=1-_/2,E=p,C=(i-1)*f+p,S=E+(C-E)*v,b=Math.round(Math.min(Math.max(S,0),C)),R=new Ti(s,Vt.Temp);R.isCube=!0,R.invertY=!0,R.generateMipMaps=!1,s.updateTextureSamplingMode(2,R);const I=new Ei(null);switch(I._isCube=!0,I._texture=R,h[b]=I,_){case 0:o._lodTextureLow=I;break;case 1:o._lodTextureMid=I;break;case 2:o._lodTextureHigh=I;break}}}const u=[];for(let d=0;dv0(E,s,r,a,g,f,d,n,h,l,o));else{const E=new Image;E.src=g,v=new Promise((C,S)=>{E.onload=()=>{v0(E,s,r,a,g,f,d,n,h,l,o).then(()=>C()).catch(b=>{S(b)})},E.onerror=b=>{S(b)}})}u.push(v)}if(e.length{l&&(s._releaseTexture(o),l._swapAndDie(o)),a&&a.dispose(),n&&(o._lodTextureHigh&&o._lodTextureHigh._texture&&(o._lodTextureHigh._texture.isReady=!0),o._lodTextureMid&&o._lodTextureMid._texture&&(o._lodTextureMid._texture.isReady=!0),o._lodTextureLow&&o._lodTextureLow._texture&&(o._lodTextureLow._texture.isReady=!0))})}function fy(o,e){e=Im(e);const t=e.irradiance;if(!t)return;const i=new ph;T.FromArrayToRef(t.x,0,i.x),T.FromArrayToRef(t.y,0,i.y),T.FromArrayToRef(t.z,0,i.z),T.FromArrayToRef(t.xx,0,i.xx),T.FromArrayToRef(t.yy,0,i.yy),T.FromArrayToRef(t.zz,0,i.zz),T.FromArrayToRef(t.yz,0,i.yz),T.FromArrayToRef(t.zx,0,i.zx),T.FromArrayToRef(t.xy,0,i.xy),o._sphericalPolynomial=i}function l_(o,e,t,i){let s=i,r=0,n="";for(;sv0)throw new Error(`Unsupported babylon environment map version "${o.version}". Latest supported version is "${v0}".`);return o.version===2||(o=Object.assign(Object.assign({},o),{version:2,imageType:dy})),o}function py(o,e){e=Im(e);const t=e.specular;let i=ye.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{if(t){const f=e.createTexture(null,!0,!0,null,1,null,p=>{d(p)},o);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=p=>{p._bindTexture("textureSampler",f),p.setFloat2("scale",1,e._features.needsInvertingBitmap&&o 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,o,r,n),a){const f=l[n];f&&e._uploadImageToTexture(f._texture,o,r,0)}u()}})}function d2(o,e,t=dy){if(!fe.IsExponentOfTwo(o.width))throw new Error("Texture size must be a power of two");const i=ye.ILog2(o.width)+1,s=o.getEngine();let r=!1,n=!1,a=null,l=null,h=null;const c=s.getCaps();if(o.format=5,o.type=0,o.generateMipMaps=!0,o._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,o),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,o.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,o.type=1):r=!1:(r=!1,n=!0,h={}),r)a=new lt("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,o.type,void 0,null,!1),o._isRGBD=!1,o.invertY=!1,l=s.createRenderTargetCubeTexture(o.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:o.type,format:5});else if(o._isRGBD=!0,o.invertY=!0,n){const f=o._lodGenerationScale,p=o._lodGenerationOffset;for(let _=0;_<3;_++){const v=1-_/2,E=p,C=(i-1)*f+p,S=E+(C-E)*v,b=Math.round(Math.min(Math.max(S,0),C)),R=new Ti(s,Ut.Temp);R.isCube=!0,R.invertY=!0,R.generateMipMaps=!1,s.updateTextureSamplingMode(2,R);const I=new Ei(null);switch(I._isCube=!0,I._texture=R,h[b]=I,_){case 0:o._lodTextureLow=I;break;case 1:o._lodTextureMid=I;break;case 2:o._lodTextureHigh=I;break}}}const u=[];for(let d=0;dT0(E,s,r,a,g,f,d,n,h,l,o));else{const E=new Image;E.src=g,v=new Promise((C,S)=>{E.onload=()=>{T0(E,s,r,a,g,f,d,n,h,l,o).then(()=>C()).catch(b=>{S(b)})},E.onerror=b=>{S(b)}})}u.push(v)}if(e.length{l&&(s._releaseTexture(o),l._swapAndDie(o)),a&&a.dispose(),n&&(o._lodTextureHigh&&o._lodTextureHigh._texture&&(o._lodTextureHigh._texture.isReady=!0),o._lodTextureMid&&o._lodTextureMid._texture&&(o._lodTextureMid._texture.isReady=!0),o._lodTextureLow&&o._lodTextureLow._texture&&(o._lodTextureLow._texture.isReady=!0))})}function _y(o,e){e=Im(e);const t=e.irradiance;if(!t)return;const i=new _h;T.FromArrayToRef(t.x,0,i.x),T.FromArrayToRef(t.y,0,i.y),T.FromArrayToRef(t.z,0,i.z),T.FromArrayToRef(t.xx,0,i.xx),T.FromArrayToRef(t.yy,0,i.yy),T.FromArrayToRef(t.zz,0,i.zz),T.FromArrayToRef(t.yz,0,i.yz),T.FromArrayToRef(t.zx,0,i.zx),T.FromArrayToRef(t.xy,0,i.xy),o._sphericalPolynomial=i}function l_(o,e,t,i){let s=i,r=0,n="";for(;s=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function kv(o){let e=0,t="",i=!1;const s=[];for(;e=0&&o.charAt(e)!==t&&(!i||o.charAt(e)!==i);)e--;return e}function u2(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class Hh{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&&G.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&G.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&f.push(v.substring(E+1))}r!=="void"&&f.push("return"),this._functionDescr.push({name:n,type:r,parameters:f,body:u,callIndex:0}),e=c+1;const p=t>0?this._sourceCode.substring(0,t):"",_=c+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&G.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 a=0;for(;a{const S=[];let b=0,R=0;for(;b0?this._sourceCode.substring(0,l):"";const E=c+1=0&&o.charAt(e)!==t&&(!i||o.charAt(e)!==i);)e--;return e}function p2(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class Xh{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&&G.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&G.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&f.push(v.substring(E+1))}r!=="void"&&f.push("return"),this._functionDescr.push({name:n,type:r,parameters:f,body:u,callIndex:0}),e=c+1;const p=t>0?this._sourceCode.substring(0,t):"",_=c+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&G.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 a=0;for(;a{const S=[];let b=0,R=0;for(;b0?this._sourceCode.substring(0,l):"";const E=c+1{const c=h[0];return _v(e.charAt(c-1))||_v(e.charAt(c+n))?t[s]:a})}return e}}Hh._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class d2{get isAsync(){return this.isParallelCompiled}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}_handlesSpectorRebuildCallback(e){throw new Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,s,r,n,a,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{n[d]=f}),l.push(...h.getAttributes(this,a))}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 a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}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.toArray())||(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 f2 extends px{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 T0{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 mv(o,e){switch(o){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 Ko(`Unsupported texture format or type: format ${o}, type ${e}.`,sh.UnsupportedTextureError)}function qu(o){switch(o){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: ${o}.`)}}function gv(o){switch(o){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: "+o+".")}}function p2(o){switch(o){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: ${o}.`)}}function _2(o){switch(o){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: ${o}.`)}}function m2(o){switch(o){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: ${o}.`)}}function g2(o){switch(o){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: ${o}.`)}}function v2(o){switch(o){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: ${o}.`)}}function x2(o){switch(o){case P.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case P.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case P.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case P.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case P.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${o}.`)}}const py=new he;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let o;Object.defineProperty(self,"_native",{get:()=>o,set:e=>{o=e,o&&py.notifyObservers(o)}})}function T2(){return new Promise(o=>{typeof _native>"u"?py.addOnce(e=>o(e)):o(_native)})}async function E2(o,e){(await T2())[o]=e}class E0 extends Zh{}class S2{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=ru._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 ru extends re{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 S2(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!==ru.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${ru.PROTOCOL_VERSION} (JS)`);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,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},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,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},fe.Log("Babylon Native (v"+re.Version+") launched"),fe.LoadScript=function(s,r,n,a){fe.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,a){return Array.isArray(a)?n.push.apply(n,s.call(a,r-1)):n.push(a),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 lb,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 qh}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_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 E0;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 E0;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 a=0;a=0){const h=n[a];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(),x2(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.nativeProgram,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(){return new d2(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,a,l){const h=e;s?h.nativeProgram=this.createRawShaderProgram():h.nativeProgram=this.createShaderProgram(e,t,i,l)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e)){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;if(r.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Hh(t);n.processCode(),t=n.code;const a=new Hh(i);a.processCode(),i=a.code,t=We._ConcatenateShader(t,s),i=We._ConcatenateShader(i,s);const l=()=>{var h;r.isCompiled=!0,(h=r.onCompiled)===null||h===void 0||h.call(r),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,l,h=>{r.compilationError=h});try{const h=r.nativeProgram=this._engine.createProgram(t,i);return l(),h}catch(h){const c=h==null?void 0:h.message;throw new Error("SHADER ERROR"+(typeof c=="string"?` -`+c:""))}}inlineShaderCode(e){const t=new Hh(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.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.nativeProgram,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.nativeProgram);const i=e.getSamplers();for(let s=0;s{}}}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,_2(this._stencilOpStencilFail),m2(this._stencilOpDepthFail),g2(this._stencilOpStencilDepthPass),p2(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=v2(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(),a=e._hardwareTexture.underlyingResource;this._engine.copyTexture(a,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,a,l=null,h=0,c=0,u=!1){const d=new Ti(this,Vt.Raw);if(d.format=s,d.generateMipMaps=r,d.samplingMode=a,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,p=qu(a);this._setTextureSampling(f,p)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,s,r,n,a,l,h=null,c=0){const u=new Ti(this,Vt.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,mv(r,c),n,a);const f=qu(l);this._setTextureSampling(d,f)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,s,r=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,mv(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_=!1){e=e||"";const g=e.substr(0,5)==="data:",v=g&&e.indexOf(";base64,")!==-1,E=h||new Ti(this,Vt.Url),C=e;this._transformTextureUrl&&!v&&!h&&!l&&(e=this._transformTextureUrl(e));const S=e.lastIndexOf("."),b=u||(S>-1?e.substring(S).toLowerCase():"");let R=null;for(const O of re._TextureLoaders)if(O.canLoad(b)){R=O;break}s&&s.addPendingData(E),E.url=e,E.generateMipMaps=!t,E.samplingMode=r,E.invertY=i,E._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(E._buffer=l);let I=null;n&&!h&&(I=E.onLoadedObservable.add(n)),h||this._internalTexturesCache.push(E);const N=(O,L)=>{s&&s.removePendingData(E),e===C?(I&&E.onLoadedObservable.remove(I),ht.UseFallbackTexture&&this.createTexture(ht.FallbackTexture,t,E.invertY,s,r,null,a,l,E),a&&a((O||"Unknown error")+(ht.UseFallbackTexture?" - Fallback texture was used":""),L)):(G.Warn(`Failed to load ${e}, falling back to ${C}`),this.createTexture(C,t,E.invertY,s,r,n,a,l,E,c,u,d,f))};if(R)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const O=L=>{if(!E._hardwareTexture){s&&s.removePendingData(E);return}const B=E._hardwareTexture.underlyingResource;this._engine.loadTexture(B,L,!t,i,E._useSRGBBuffer,()=>{E.baseWidth=this._engine.getTextureWidth(B),E.baseHeight=this._engine.getTextureHeight(B),E.width=E.baseWidth,E.height=E.baseHeight,E.isReady=!0;const V=qu(r);this._setTextureSampling(B,V),s&&s.removePendingData(E),E.onLoadedObservable.notifyObservers(E),E.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(g&&l)if(l instanceof ArrayBuffer)O(new Uint8Array(l));else if(ArrayBuffer.isView(l))O(l);else if(typeof l=="string")O(new Uint8Array(fe.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else v?O(new Uint8Array(fe.DecodeBase64(e))):this._loadFile(e,L=>O(new Uint8Array(L)),void 0,void 0,!0,(L,B)=>{N("Unable to load "+(L&&L.responseURL,B))})}return E}wrapNativeTexture(e,t=!1,i=3){const s=new T0(e,this._engine),r=new Ti(this,Vt.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){var s,r;const n=t.generateStencil||!1,a=t.samples||1,l=i,h=new Ti(this,Vt.DepthStencil),c=(s=e.width)!==null&&s!==void 0?s:e,u=(r=e.height)!==null&&r!==void 0?r:e,d=this._engine.createFrameBuffer(h._hardwareTexture.underlyingResource,c,u,n,!0,a);return l._framebufferDepthStencil=d,h}_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 a=this._engine.createImageBitmap(n);s(a)}catch(a){r(`Error loading image ${n.src} with exception: ${a}`)}},n.onerror=a=>{r(`Error loading image ${n.src} with exception: ${a}`)},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,a,l=null,h=!1,c=0,u=0,d=null,f,p=!1){const _=d||new Ti(this,Vt.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!s,_._lodGenerationScale=c,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!s),this._doNotHandleContextLost||(_._extension=l,_._files=i);const g=e.lastIndexOf(".");if((l||(g>-1?e.substring(g).toLowerCase():""))===".env"){const E=C=>{const S=uy(C);_.width=S.width,_.height=S.width,fy(_,S);const b=S.specular;if(!b)throw new Error("Nothing else parsed so far");_._lodGenerationScale=b.lodGenerationScale;const R=dy(C,S);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(ee.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,R,!1,_._useSRGBBuffer,()=>{_.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 C=(S,b)=>{n&&S&&n(S.status+" "+S.statusText,b)};this._loadFile(e,S=>{E(new Uint8Array(S,0,S.byteLength))},void 0,void 0,!0,C)}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const E=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(E.map(C=>this._loadFileAsync(C,void 0,!0).then(S=>new Uint8Array(S,0,S.byteLength)))).then(C=>new Promise((S,b)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,C,!s,!0,_._useSRGBBuffer,S,b)})).then(()=>{_.isReady=!0,r&&r()},C=>{n&&n(`Failed to load cubemap: ${C.message}`,C)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new T0(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new f2(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=Vt.Unknown){var r,n,a;let l=!1,h=0,c=3,u=5,d=!1,f=1,p;t!==void 0&&typeof t=="object"?(l=!!t.generateMipMaps,h=t.type===void 0?0:t.type,c=t.samplingMode===void 0?3:t.samplingMode,u=t.format===void 0?5:t.format,d=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,f=(r=t.samples)!==null&&r!==void 0?r:1,p=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(h===1&&!this._caps.textureFloatLinearFiltering||h===2&&!this._caps.textureHalfFloatLinearFiltering)&&(c=1),h===1&&!this._caps.textureFloat&&(h=0,G.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const _=new Ti(this,s),g=(n=e.width)!==null&&n!==void 0?n:e,v=(a=e.height)!==null&&a!==void 0?a:e,E=e.layers||0;if(E!==0)throw new Error("Texture layers are not supported in Babylon Native");const C=_._hardwareTexture.underlyingResource,S=mv(u,h);return this._engine.initializeTexture(C,g,v,l,S,!0,d,f),this._setTextureSampling(C,qu(c)),_._useSRGBBuffer=d,_.baseWidth=g,_.baseHeight=v,_.width=g,_.height=v,_.depth=E,_.isReady=!0,_.samples=f,_.generateMipMaps=l,_.samplingMode=c,_.type=h,_.format=u,_.label=p,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,s,r,n;const a=this._createHardwareRenderTargetWrapper(!1,!1,e);let l=!0,h=!1,c=!1,u,d=1;t!==void 0&&typeof t=="object"&&(l=(i=t.generateDepthBuffer)!==null&&i!==void 0?i:!0,h=!!t.generateStencilBuffer,c=!!t.noColorAttachment,u=t.colorAttachment,d=(s=t.samples)!==null&&s!==void 0?s:1);const f=u||(c?null:this._createInternalTexture(e,t,!0,Vt.RenderTarget)),p=(r=e.width)!==null&&r!==void 0?r:e,_=(n=e.height)!==null&&n!==void 0?n:e,g=this._engine.createFrameBuffer(f?f._hardwareTexture.underlyingResource:null,p,_,h,l,d);return a._framebuffer=g,a._generateDepthBuffer=l,a._generateStencilBuffer=h,a._samples=d,a.setTextures(f),a}updateRenderTargetTextureSampleCount(e,t){return G.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=qu(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,s){const r=e,n=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,n.buffer,n.byteOffset+(i??0),s??n.byteLength)}_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,gv(t.wrapU),gv(t.wrapV),gv(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,a=0,l=0,h=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=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}}_readTexturePixels(e,t,i,s,r,n,a,l,h,c){var u,d,f,p;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||u===void 0?void 0:u.underlyingResource,r??0,h??0,c??0,t,i,(d=n==null?void 0:n.buffer)!==null&&d!==void 0?d:null,(f=n==null?void 0:n.byteOffset)!==null&&f!==void 0?f:0,(p=n==null?void 0:n.byteLength)!==null&&p!==void 0?p:0).then(_=>(n||(n=new Uint8Array(_)),n))}}ru.PROTOCOL_VERSION=8;ru._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new C2:new qh};class C2 extends qh{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 S0;(function(o){o.LowPower="low-power",o.HighPerformance="high-performance"})(S0||(S0={}));var Tl;(function(o){o.DepthClipControl="depth-clip-control",o.Depth32FloatStencil8="depth32float-stencil8",o.TextureCompressionBC="texture-compression-bc",o.TextureCompressionETC2="texture-compression-etc2",o.TextureCompressionASTC="texture-compression-astc",o.TimestampQuery="timestamp-query",o.IndirectFirstInstance="indirect-first-instance",o.ShaderF16="shader-f16",o.RG11B10UFloatRenderable="rg11b10ufloat-renderable",o.BGRA8UnormStorage="bgra8unorm-storage",o.Float32Filterable="float32-filterable"})(Tl||(Tl={}));var C0;(function(o){o.Unmapped="unmapped",o.Pending="pending",o.Mapped="mapped"})(C0||(C0={}));var Hi;(function(o){o[o.MapRead=1]="MapRead",o[o.MapWrite=2]="MapWrite",o[o.CopySrc=4]="CopySrc",o[o.CopyDst=8]="CopyDst",o[o.Index=16]="Index",o[o.Vertex=32]="Vertex",o[o.Uniform=64]="Uniform",o[o.Storage=128]="Storage",o[o.Indirect=256]="Indirect",o[o.QueryResolve=512]="QueryResolve"})(Hi||(Hi={}));var Xh;(function(o){o[o.Read=1]="Read",o[o.Write=2]="Write"})(Xh||(Xh={}));var to;(function(o){o.E1d="1d",o.E2d="2d",o.E3d="3d"})(to||(to={}));var ls;(function(o){o[o.CopySrc=1]="CopySrc",o[o.CopyDst=2]="CopyDst",o[o.TextureBinding=4]="TextureBinding",o[o.StorageBinding=8]="StorageBinding",o[o.RenderAttachment=16]="RenderAttachment"})(ls||(ls={}));var qi;(function(o){o.E1d="1d",o.E2d="2d",o.E2dArray="2d-array",o.Cube="cube",o.CubeArray="cube-array",o.E3d="3d"})(qi||(qi={}));var Go;(function(o){o.All="all",o.StencilOnly="stencil-only",o.DepthOnly="depth-only"})(Go||(Go={}));var U;(function(o){o.R8Unorm="r8unorm",o.R8Snorm="r8snorm",o.R8Uint="r8uint",o.R8Sint="r8sint",o.R16Uint="r16uint",o.R16Sint="r16sint",o.R16Float="r16float",o.RG8Unorm="rg8unorm",o.RG8Snorm="rg8snorm",o.RG8Uint="rg8uint",o.RG8Sint="rg8sint",o.R32Uint="r32uint",o.R32Sint="r32sint",o.R32Float="r32float",o.RG16Uint="rg16uint",o.RG16Sint="rg16sint",o.RG16Float="rg16float",o.RGBA8Unorm="rgba8unorm",o.RGBA8UnormSRGB="rgba8unorm-srgb",o.RGBA8Snorm="rgba8snorm",o.RGBA8Uint="rgba8uint",o.RGBA8Sint="rgba8sint",o.BGRA8Unorm="bgra8unorm",o.BGRA8UnormSRGB="bgra8unorm-srgb",o.RGB9E5UFloat="rgb9e5ufloat",o.RGB10A2UINT="rgb10a2uint",o.RGB10A2Unorm="rgb10a2unorm",o.RG11B10UFloat="rg11b10ufloat",o.RG32Uint="rg32uint",o.RG32Sint="rg32sint",o.RG32Float="rg32float",o.RGBA16Uint="rgba16uint",o.RGBA16Sint="rgba16sint",o.RGBA16Float="rgba16float",o.RGBA32Uint="rgba32uint",o.RGBA32Sint="rgba32sint",o.RGBA32Float="rgba32float",o.Stencil8="stencil8",o.Depth16Unorm="depth16unorm",o.Depth24Plus="depth24plus",o.Depth24PlusStencil8="depth24plus-stencil8",o.Depth32Float="depth32float",o.BC1RGBAUnorm="bc1-rgba-unorm",o.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",o.BC2RGBAUnorm="bc2-rgba-unorm",o.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",o.BC3RGBAUnorm="bc3-rgba-unorm",o.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",o.BC4RUnorm="bc4-r-unorm",o.BC4RSnorm="bc4-r-snorm",o.BC5RGUnorm="bc5-rg-unorm",o.BC5RGSnorm="bc5-rg-snorm",o.BC6HRGBUFloat="bc6h-rgb-ufloat",o.BC6HRGBFloat="bc6h-rgb-float",o.BC7RGBAUnorm="bc7-rgba-unorm",o.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",o.ETC2RGB8Unorm="etc2-rgb8unorm",o.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",o.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",o.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",o.ETC2RGBA8Unorm="etc2-rgba8unorm",o.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",o.EACR11Unorm="eac-r11unorm",o.EACR11Snorm="eac-r11snorm",o.EACRG11Unorm="eac-rg11unorm",o.EACRG11Snorm="eac-rg11snorm",o.ASTC4x4Unorm="astc-4x4-unorm",o.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",o.ASTC5x4Unorm="astc-5x4-unorm",o.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",o.ASTC5x5Unorm="astc-5x5-unorm",o.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",o.ASTC6x5Unorm="astc-6x5-unorm",o.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",o.ASTC6x6Unorm="astc-6x6-unorm",o.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",o.ASTC8x5Unorm="astc-8x5-unorm",o.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",o.ASTC8x6Unorm="astc-8x6-unorm",o.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",o.ASTC8x8Unorm="astc-8x8-unorm",o.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",o.ASTC10x5Unorm="astc-10x5-unorm",o.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",o.ASTC10x6Unorm="astc-10x6-unorm",o.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",o.ASTC10x8Unorm="astc-10x8-unorm",o.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",o.ASTC10x10Unorm="astc-10x10-unorm",o.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",o.ASTC12x10Unorm="astc-12x10-unorm",o.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",o.ASTC12x12Unorm="astc-12x12-unorm",o.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",o.Depth32FloatStencil8="depth32float-stencil8"})(U||(U={}));var Nc;(function(o){o.ClampToEdge="clamp-to-edge",o.Repeat="repeat",o.MirrorRepeat="mirror-repeat"})(Nc||(Nc={}));var ri;(function(o){o.Nearest="nearest",o.Linear="linear"})(ri||(ri={}));var b0;(function(o){o.Nearest="nearest",o.Linear="linear"})(b0||(b0={}));var Mr;(function(o){o.Never="never",o.Less="less",o.Equal="equal",o.LessEqual="less-equal",o.Greater="greater",o.NotEqual="not-equal",o.GreaterEqual="greater-equal",o.Always="always"})(Mr||(Mr={}));var ql;(function(o){o[o.Vertex=1]="Vertex",o[o.Fragment=2]="Fragment",o[o.Compute=4]="Compute"})(ql||(ql={}));var rh;(function(o){o.Uniform="uniform",o.Storage="storage",o.ReadOnlyStorage="read-only-storage"})(rh||(rh={}));var _h;(function(o){o.Filtering="filtering",o.NonFiltering="non-filtering",o.Comparison="comparison"})(_h||(_h={}));var oa;(function(o){o.Float="float",o.UnfilterableFloat="unfilterable-float",o.Depth="depth",o.Sint="sint",o.Uint="uint"})(oa||(oa={}));var Gv;(function(o){o.WriteOnly="write-only"})(Gv||(Gv={}));var y0;(function(o){o.Error="error",o.Warning="warning",o.Info="info"})(y0||(y0={}));var A0;(function(o){o.Validation="validation",o.Internal="internal"})(A0||(A0={}));var Pd;(function(o){o.Auto="auto"})(Pd||(Pd={}));var sa;(function(o){o.PointList="point-list",o.LineList="line-list",o.LineStrip="line-strip",o.TriangleList="triangle-list",o.TriangleStrip="triangle-strip"})(sa||(sa={}));var O_;(function(o){o.CCW="ccw",o.CW="cw"})(O_||(O_={}));var sd;(function(o){o.None="none",o.Front="front",o.Back="back"})(sd||(sd={}));var R0;(function(o){o[o.Red=1]="Red",o[o.Green=2]="Green",o[o.Blue=4]="Blue",o[o.Alpha=8]="Alpha",o[o.All=15]="All"})(R0||(R0={}));var en;(function(o){o.Zero="zero",o.One="one",o.Src="src",o.OneMinusSrc="one-minus-src",o.SrcAlpha="src-alpha",o.OneMinusSrcAlpha="one-minus-src-alpha",o.Dst="dst",o.OneMinusDst="one-minus-dst",o.DstAlpha="dst-alpha",o.OneMinusDstAlpha="one-minus-dst-alpha",o.SrcAlphaSaturated="src-alpha-saturated",o.Constant="constant",o.OneMinusConstant="one-minus-constant"})(en||(en={}));var jl;(function(o){o.Add="add",o.Subtract="subtract",o.ReverseSubtract="reverse-subtract",o.Min="min",o.Max="max"})(jl||(jl={}));var go;(function(o){o.Keep="keep",o.Zero="zero",o.Replace="replace",o.Invert="invert",o.IncrementClamp="increment-clamp",o.DecrementClamp="decrement-clamp",o.IncrementWrap="increment-wrap",o.DecrementWrap="decrement-wrap"})(go||(go={}));var mh;(function(o){o.Uint16="uint16",o.Uint32="uint32"})(mh||(mh={}));var ps;(function(o){o.Uint8x2="uint8x2",o.Uint8x4="uint8x4",o.Sint8x2="sint8x2",o.Sint8x4="sint8x4",o.Unorm8x2="unorm8x2",o.Unorm8x4="unorm8x4",o.Snorm8x2="snorm8x2",o.Snorm8x4="snorm8x4",o.Uint16x2="uint16x2",o.Uint16x4="uint16x4",o.Sint16x2="sint16x2",o.Sint16x4="sint16x4",o.Unorm16x2="unorm16x2",o.Unorm16x4="unorm16x4",o.Snorm16x2="snorm16x2",o.Snorm16x4="snorm16x4",o.Float16x2="float16x2",o.Float16x4="float16x4",o.Float32="float32",o.Float32x2="float32x2",o.Float32x3="float32x3",o.Float32x4="float32x4",o.Uint32="uint32",o.Uint32x2="uint32x2",o.Uint32x3="uint32x3",o.Uint32x4="uint32x4",o.Sint32="sint32",o.Sint32x2="sint32x2",o.Sint32x3="sint32x3",o.Sint32x4="sint32x4",o.UNORM10x10x10x2="unorm10-10-10-2"})(ps||(ps={}));var N_;(function(o){o.Vertex="vertex",o.Instance="instance"})(N_||(N_={}));var I0;(function(o){o.Beginning="beginning",o.End="end"})(I0||(I0={}));var P0;(function(o){o.Beginning="beginning",o.End="end"})(P0||(P0={}));var ir;(function(o){o.Load="load",o.Clear="clear"})(ir||(ir={}));var ba;(function(o){o.Store="store",o.Discard="discard"})(ba||(ba={}));var w_;(function(o){o.Occlusion="occlusion",o.Timestamp="timestamp"})(w_||(w_={}));var F_;(function(o){o.Opaque="opaque",o.Premultiplied="premultiplied"})(F_||(F_={}));var M0;(function(o){o.Unknown="unknown",o.Destroyed="destroyed"})(M0||(M0={}));var D0;(function(o){o.Validation="validation",o.OutOfMemory="out-of-memory",o.Internal="internal"})(D0||(D0={}));class us{constructor(){this.shaderLanguage=is.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let r=0;r=0&&(d.push(a[u]),f.push(p))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new it(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=us.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||e===void 0?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)===null||e===void 0?void 0:e.fragment}}const y2=4,A2=65536,O0={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Ma{static get KnownUBOs(){return Ma._SimplifiedKnownBindings?Ma._SimplifiedKnownUBOs:Ma._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=Ma.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;const s=this._attributeNextLocation;return this._attributeNextLocation+=((i=O0[e])!==null&&i!==void 0?i:1)*(t||1),s}getVaryingNextLocation(e,t=0){var i;const s=this._varyingNextLocation;return this._varyingNextLocation+=((i=O0[e])!==null&&i!==void 0?i:1)*(t||1),s}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>A2-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===y2)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}}Ma._SimplifiedKnownBindings=!0;Ma._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}}};Ma._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 R2 extends us{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=is.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const a=e.substring(r+1,n);s=+a,isNaN(s)&&(s=+i[a.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 +`+S+_+E,this.debug&&G.Log(`Replace function call by code. Function '${i}' (type=${s}). injectDeclarationIndex=${C}, call parameters=${p}`)}else this._sourceCode=v+g+E,a+=g.length-(c+1-l),this.debug&&G.Log(`Replace function call by code. Function '${i}' (type=${s}). functionCallIndex=${l}, call parameters=${p}`);e=!0}}return e}_replaceNames(e,t,i){for(let s=0;s{const c=h[0];return _v(e.charAt(c-1))||_v(e.charAt(c+n))?t[s]:a})}return e}}Xh._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class _2{get isAsync(){return this.isParallelCompiled}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}_handlesSpectorRebuildCallback(e){throw new Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,s,r,n,a,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{n[d]=f}),l.push(...h.getAttributes(this,a))}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 a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}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.toArray())||(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 m2 extends mx{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 S0{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 mv(o,e){switch(o){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 Ko(`Unsupported texture format or type: format ${o}, type ${e}.`,rh.UnsupportedTextureError)}function qu(o){switch(o){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: ${o}.`)}}function gv(o){switch(o){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: "+o+".")}}function g2(o){switch(o){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: ${o}.`)}}function v2(o){switch(o){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: ${o}.`)}}function x2(o){switch(o){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: ${o}.`)}}function T2(o){switch(o){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: ${o}.`)}}function E2(o){switch(o){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: ${o}.`)}}function S2(o){switch(o){case P.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case P.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case P.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case P.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case P.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${o}.`)}}const my=new he;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let o;Object.defineProperty(self,"_native",{get:()=>o,set:e=>{o=e,o&&my.notifyObservers(o)}})}function C2(){return new Promise(o=>{typeof _native>"u"?my.addOnce(e=>o(e)):o(_native)})}async function b2(o,e){(await C2())[o]=e}class C0 extends Jh{}class y2{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=ru._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 ru extends re{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 y2(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!==ru.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${ru.PROTOCOL_VERSION} (JS)`);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,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},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,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},fe.Log("Babylon Native (v"+re.Version+") launched"),fe.LoadScript=function(s,r,n,a){fe.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,a){return Array.isArray(a)?n.push.apply(n,s.call(a,r-1)):n.push(a),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 cb,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 jh}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_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 C0;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 C0;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 a=0;a=0){const h=n[a];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(),S2(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.nativeProgram,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(){return new _2(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,a,l){const h=e;s?h.nativeProgram=this.createRawShaderProgram():h.nativeProgram=this.createShaderProgram(e,t,i,l)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e)){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;if(r.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Xh(t);n.processCode(),t=n.code;const a=new Xh(i);a.processCode(),i=a.code,t=We._ConcatenateShader(t,s),i=We._ConcatenateShader(i,s);const l=()=>{var h;r.isCompiled=!0,(h=r.onCompiled)===null||h===void 0||h.call(r),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,l,h=>{r.compilationError=h});try{const h=r.nativeProgram=this._engine.createProgram(t,i);return l(),h}catch(h){const c=h==null?void 0:h.message;throw new Error("SHADER ERROR"+(typeof c=="string"?` +`+c:""))}}inlineShaderCode(e){const t=new Xh(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.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.nativeProgram,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.nativeProgram);const i=e.getSamplers();for(let s=0;s{}}}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,v2(this._stencilOpStencilFail),x2(this._stencilOpDepthFail),T2(this._stencilOpStencilDepthPass),g2(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=E2(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(),a=e._hardwareTexture.underlyingResource;this._engine.copyTexture(a,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,a,l=null,h=0,c=0,u=!1){const d=new Ti(this,Ut.Raw);if(d.format=s,d.generateMipMaps=r,d.samplingMode=a,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,p=qu(a);this._setTextureSampling(f,p)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,s,r,n,a,l,h=null,c=0){const u=new Ti(this,Ut.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,mv(r,c),n,a);const f=qu(l);this._setTextureSampling(d,f)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,s,r=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,mv(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_=!1){e=e||"";const g=e.substr(0,5)==="data:",v=g&&e.indexOf(";base64,")!==-1,E=h||new Ti(this,Ut.Url),C=e;this._transformTextureUrl&&!v&&!h&&!l&&(e=this._transformTextureUrl(e));const S=e.lastIndexOf("."),b=u||(S>-1?e.substring(S).toLowerCase():"");let R=null;for(const O of re._TextureLoaders)if(O.canLoad(b)){R=O;break}s&&s.addPendingData(E),E.url=e,E.generateMipMaps=!t,E.samplingMode=r,E.invertY=i,E._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(E._buffer=l);let I=null;n&&!h&&(I=E.onLoadedObservable.add(n)),h||this._internalTexturesCache.push(E);const N=(O,L)=>{s&&s.removePendingData(E),e===C?(I&&E.onLoadedObservable.remove(I),ht.UseFallbackTexture&&this.createTexture(ht.FallbackTexture,t,E.invertY,s,r,null,a,l,E),a&&a((O||"Unknown error")+(ht.UseFallbackTexture?" - Fallback texture was used":""),L)):(G.Warn(`Failed to load ${e}, falling back to ${C}`),this.createTexture(C,t,E.invertY,s,r,n,a,l,E,c,u,d,f))};if(R)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const O=L=>{if(!E._hardwareTexture){s&&s.removePendingData(E);return}const B=E._hardwareTexture.underlyingResource;this._engine.loadTexture(B,L,!t,i,E._useSRGBBuffer,()=>{E.baseWidth=this._engine.getTextureWidth(B),E.baseHeight=this._engine.getTextureHeight(B),E.width=E.baseWidth,E.height=E.baseHeight,E.isReady=!0;const V=qu(r);this._setTextureSampling(B,V),s&&s.removePendingData(E),E.onLoadedObservable.notifyObservers(E),E.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(g&&l)if(l instanceof ArrayBuffer)O(new Uint8Array(l));else if(ArrayBuffer.isView(l))O(l);else if(typeof l=="string")O(new Uint8Array(fe.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else v?O(new Uint8Array(fe.DecodeBase64(e))):this._loadFile(e,L=>O(new Uint8Array(L)),void 0,void 0,!0,(L,B)=>{N("Unable to load "+(L&&L.responseURL,B))})}return E}wrapNativeTexture(e,t=!1,i=3){const s=new S0(e,this._engine),r=new Ti(this,Ut.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){var s,r;const n=t.generateStencil||!1,a=t.samples||1,l=i,h=new Ti(this,Ut.DepthStencil),c=(s=e.width)!==null&&s!==void 0?s:e,u=(r=e.height)!==null&&r!==void 0?r:e,d=this._engine.createFrameBuffer(h._hardwareTexture.underlyingResource,c,u,n,!0,a);return l._framebufferDepthStencil=d,h}_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 a=this._engine.createImageBitmap(n);s(a)}catch(a){r(`Error loading image ${n.src} with exception: ${a}`)}},n.onerror=a=>{r(`Error loading image ${n.src} with exception: ${a}`)},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,a,l=null,h=!1,c=0,u=0,d=null,f,p=!1){const _=d||new Ti(this,Ut.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!s,_._lodGenerationScale=c,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!s),this._doNotHandleContextLost||(_._extension=l,_._files=i);const g=e.lastIndexOf(".");if((l||(g>-1?e.substring(g).toLowerCase():""))===".env"){const E=C=>{const S=fy(C);_.width=S.width,_.height=S.width,_y(_,S);const b=S.specular;if(!b)throw new Error("Nothing else parsed so far");_._lodGenerationScale=b.lodGenerationScale;const R=py(C,S);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(ee.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,R,!1,_._useSRGBBuffer,()=>{_.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 C=(S,b)=>{n&&S&&n(S.status+" "+S.statusText,b)};this._loadFile(e,S=>{E(new Uint8Array(S,0,S.byteLength))},void 0,void 0,!0,C)}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const E=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(E.map(C=>this._loadFileAsync(C,void 0,!0).then(S=>new Uint8Array(S,0,S.byteLength)))).then(C=>new Promise((S,b)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,C,!s,!0,_._useSRGBBuffer,S,b)})).then(()=>{_.isReady=!0,r&&r()},C=>{n&&n(`Failed to load cubemap: ${C.message}`,C)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new S0(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new m2(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=Ut.Unknown){var r,n,a;let l=!1,h=0,c=3,u=5,d=!1,f=1,p;t!==void 0&&typeof t=="object"?(l=!!t.generateMipMaps,h=t.type===void 0?0:t.type,c=t.samplingMode===void 0?3:t.samplingMode,u=t.format===void 0?5:t.format,d=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,f=(r=t.samples)!==null&&r!==void 0?r:1,p=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(h===1&&!this._caps.textureFloatLinearFiltering||h===2&&!this._caps.textureHalfFloatLinearFiltering)&&(c=1),h===1&&!this._caps.textureFloat&&(h=0,G.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const _=new Ti(this,s),g=(n=e.width)!==null&&n!==void 0?n:e,v=(a=e.height)!==null&&a!==void 0?a:e,E=e.layers||0;if(E!==0)throw new Error("Texture layers are not supported in Babylon Native");const C=_._hardwareTexture.underlyingResource,S=mv(u,h);return this._engine.initializeTexture(C,g,v,l,S,!0,d,f),this._setTextureSampling(C,qu(c)),_._useSRGBBuffer=d,_.baseWidth=g,_.baseHeight=v,_.width=g,_.height=v,_.depth=E,_.isReady=!0,_.samples=f,_.generateMipMaps=l,_.samplingMode=c,_.type=h,_.format=u,_.label=p,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,s,r,n;const a=this._createHardwareRenderTargetWrapper(!1,!1,e);let l=!0,h=!1,c=!1,u,d=1;t!==void 0&&typeof t=="object"&&(l=(i=t.generateDepthBuffer)!==null&&i!==void 0?i:!0,h=!!t.generateStencilBuffer,c=!!t.noColorAttachment,u=t.colorAttachment,d=(s=t.samples)!==null&&s!==void 0?s:1);const f=u||(c?null:this._createInternalTexture(e,t,!0,Ut.RenderTarget)),p=(r=e.width)!==null&&r!==void 0?r:e,_=(n=e.height)!==null&&n!==void 0?n:e,g=this._engine.createFrameBuffer(f?f._hardwareTexture.underlyingResource:null,p,_,h,l,d);return a._framebuffer=g,a._generateDepthBuffer=l,a._generateStencilBuffer=h,a._samples=d,a.setTextures(f),a}updateRenderTargetTextureSampleCount(e,t){return G.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=qu(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,s){const r=e,n=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,n.buffer,n.byteOffset+(i??0),s??n.byteLength)}_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,gv(t.wrapU),gv(t.wrapV),gv(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,a=0,l=0,h=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=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}}_readTexturePixels(e,t,i,s,r,n,a,l,h,c){var u,d,f,p;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||u===void 0?void 0:u.underlyingResource,r??0,h??0,c??0,t,i,(d=n==null?void 0:n.buffer)!==null&&d!==void 0?d:null,(f=n==null?void 0:n.byteOffset)!==null&&f!==void 0?f:0,(p=n==null?void 0:n.byteLength)!==null&&p!==void 0?p:0).then(_=>(n||(n=new Uint8Array(_)),n))}}ru.PROTOCOL_VERSION=8;ru._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new A2:new jh};class A2 extends jh{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 b0;(function(o){o.LowPower="low-power",o.HighPerformance="high-performance"})(b0||(b0={}));var Tl;(function(o){o.DepthClipControl="depth-clip-control",o.Depth32FloatStencil8="depth32float-stencil8",o.TextureCompressionBC="texture-compression-bc",o.TextureCompressionETC2="texture-compression-etc2",o.TextureCompressionASTC="texture-compression-astc",o.TimestampQuery="timestamp-query",o.IndirectFirstInstance="indirect-first-instance",o.ShaderF16="shader-f16",o.RG11B10UFloatRenderable="rg11b10ufloat-renderable",o.BGRA8UnormStorage="bgra8unorm-storage",o.Float32Filterable="float32-filterable"})(Tl||(Tl={}));var y0;(function(o){o.Unmapped="unmapped",o.Pending="pending",o.Mapped="mapped"})(y0||(y0={}));var Hi;(function(o){o[o.MapRead=1]="MapRead",o[o.MapWrite=2]="MapWrite",o[o.CopySrc=4]="CopySrc",o[o.CopyDst=8]="CopyDst",o[o.Index=16]="Index",o[o.Vertex=32]="Vertex",o[o.Uniform=64]="Uniform",o[o.Storage=128]="Storage",o[o.Indirect=256]="Indirect",o[o.QueryResolve=512]="QueryResolve"})(Hi||(Hi={}));var Yh;(function(o){o[o.Read=1]="Read",o[o.Write=2]="Write"})(Yh||(Yh={}));var to;(function(o){o.E1d="1d",o.E2d="2d",o.E3d="3d"})(to||(to={}));var ls;(function(o){o[o.CopySrc=1]="CopySrc",o[o.CopyDst=2]="CopyDst",o[o.TextureBinding=4]="TextureBinding",o[o.StorageBinding=8]="StorageBinding",o[o.RenderAttachment=16]="RenderAttachment"})(ls||(ls={}));var qi;(function(o){o.E1d="1d",o.E2d="2d",o.E2dArray="2d-array",o.Cube="cube",o.CubeArray="cube-array",o.E3d="3d"})(qi||(qi={}));var Go;(function(o){o.All="all",o.StencilOnly="stencil-only",o.DepthOnly="depth-only"})(Go||(Go={}));var U;(function(o){o.R8Unorm="r8unorm",o.R8Snorm="r8snorm",o.R8Uint="r8uint",o.R8Sint="r8sint",o.R16Uint="r16uint",o.R16Sint="r16sint",o.R16Float="r16float",o.RG8Unorm="rg8unorm",o.RG8Snorm="rg8snorm",o.RG8Uint="rg8uint",o.RG8Sint="rg8sint",o.R32Uint="r32uint",o.R32Sint="r32sint",o.R32Float="r32float",o.RG16Uint="rg16uint",o.RG16Sint="rg16sint",o.RG16Float="rg16float",o.RGBA8Unorm="rgba8unorm",o.RGBA8UnormSRGB="rgba8unorm-srgb",o.RGBA8Snorm="rgba8snorm",o.RGBA8Uint="rgba8uint",o.RGBA8Sint="rgba8sint",o.BGRA8Unorm="bgra8unorm",o.BGRA8UnormSRGB="bgra8unorm-srgb",o.RGB9E5UFloat="rgb9e5ufloat",o.RGB10A2UINT="rgb10a2uint",o.RGB10A2Unorm="rgb10a2unorm",o.RG11B10UFloat="rg11b10ufloat",o.RG32Uint="rg32uint",o.RG32Sint="rg32sint",o.RG32Float="rg32float",o.RGBA16Uint="rgba16uint",o.RGBA16Sint="rgba16sint",o.RGBA16Float="rgba16float",o.RGBA32Uint="rgba32uint",o.RGBA32Sint="rgba32sint",o.RGBA32Float="rgba32float",o.Stencil8="stencil8",o.Depth16Unorm="depth16unorm",o.Depth24Plus="depth24plus",o.Depth24PlusStencil8="depth24plus-stencil8",o.Depth32Float="depth32float",o.BC1RGBAUnorm="bc1-rgba-unorm",o.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",o.BC2RGBAUnorm="bc2-rgba-unorm",o.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",o.BC3RGBAUnorm="bc3-rgba-unorm",o.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",o.BC4RUnorm="bc4-r-unorm",o.BC4RSnorm="bc4-r-snorm",o.BC5RGUnorm="bc5-rg-unorm",o.BC5RGSnorm="bc5-rg-snorm",o.BC6HRGBUFloat="bc6h-rgb-ufloat",o.BC6HRGBFloat="bc6h-rgb-float",o.BC7RGBAUnorm="bc7-rgba-unorm",o.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",o.ETC2RGB8Unorm="etc2-rgb8unorm",o.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",o.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",o.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",o.ETC2RGBA8Unorm="etc2-rgba8unorm",o.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",o.EACR11Unorm="eac-r11unorm",o.EACR11Snorm="eac-r11snorm",o.EACRG11Unorm="eac-rg11unorm",o.EACRG11Snorm="eac-rg11snorm",o.ASTC4x4Unorm="astc-4x4-unorm",o.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",o.ASTC5x4Unorm="astc-5x4-unorm",o.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",o.ASTC5x5Unorm="astc-5x5-unorm",o.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",o.ASTC6x5Unorm="astc-6x5-unorm",o.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",o.ASTC6x6Unorm="astc-6x6-unorm",o.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",o.ASTC8x5Unorm="astc-8x5-unorm",o.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",o.ASTC8x6Unorm="astc-8x6-unorm",o.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",o.ASTC8x8Unorm="astc-8x8-unorm",o.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",o.ASTC10x5Unorm="astc-10x5-unorm",o.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",o.ASTC10x6Unorm="astc-10x6-unorm",o.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",o.ASTC10x8Unorm="astc-10x8-unorm",o.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",o.ASTC10x10Unorm="astc-10x10-unorm",o.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",o.ASTC12x10Unorm="astc-12x10-unorm",o.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",o.ASTC12x12Unorm="astc-12x12-unorm",o.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",o.Depth32FloatStencil8="depth32float-stencil8"})(U||(U={}));var Nc;(function(o){o.ClampToEdge="clamp-to-edge",o.Repeat="repeat",o.MirrorRepeat="mirror-repeat"})(Nc||(Nc={}));var ri;(function(o){o.Nearest="nearest",o.Linear="linear"})(ri||(ri={}));var A0;(function(o){o.Nearest="nearest",o.Linear="linear"})(A0||(A0={}));var Mr;(function(o){o.Never="never",o.Less="less",o.Equal="equal",o.LessEqual="less-equal",o.Greater="greater",o.NotEqual="not-equal",o.GreaterEqual="greater-equal",o.Always="always"})(Mr||(Mr={}));var jl;(function(o){o[o.Vertex=1]="Vertex",o[o.Fragment=2]="Fragment",o[o.Compute=4]="Compute"})(jl||(jl={}));var nh;(function(o){o.Uniform="uniform",o.Storage="storage",o.ReadOnlyStorage="read-only-storage"})(nh||(nh={}));var mh;(function(o){o.Filtering="filtering",o.NonFiltering="non-filtering",o.Comparison="comparison"})(mh||(mh={}));var oa;(function(o){o.Float="float",o.UnfilterableFloat="unfilterable-float",o.Depth="depth",o.Sint="sint",o.Uint="uint"})(oa||(oa={}));var Gv;(function(o){o.WriteOnly="write-only"})(Gv||(Gv={}));var R0;(function(o){o.Error="error",o.Warning="warning",o.Info="info"})(R0||(R0={}));var I0;(function(o){o.Validation="validation",o.Internal="internal"})(I0||(I0={}));var Md;(function(o){o.Auto="auto"})(Md||(Md={}));var sa;(function(o){o.PointList="point-list",o.LineList="line-list",o.LineStrip="line-strip",o.TriangleList="triangle-list",o.TriangleStrip="triangle-strip"})(sa||(sa={}));var O_;(function(o){o.CCW="ccw",o.CW="cw"})(O_||(O_={}));var sd;(function(o){o.None="none",o.Front="front",o.Back="back"})(sd||(sd={}));var P0;(function(o){o[o.Red=1]="Red",o[o.Green=2]="Green",o[o.Blue=4]="Blue",o[o.Alpha=8]="Alpha",o[o.All=15]="All"})(P0||(P0={}));var en;(function(o){o.Zero="zero",o.One="one",o.Src="src",o.OneMinusSrc="one-minus-src",o.SrcAlpha="src-alpha",o.OneMinusSrcAlpha="one-minus-src-alpha",o.Dst="dst",o.OneMinusDst="one-minus-dst",o.DstAlpha="dst-alpha",o.OneMinusDstAlpha="one-minus-dst-alpha",o.SrcAlphaSaturated="src-alpha-saturated",o.Constant="constant",o.OneMinusConstant="one-minus-constant"})(en||(en={}));var Ql;(function(o){o.Add="add",o.Subtract="subtract",o.ReverseSubtract="reverse-subtract",o.Min="min",o.Max="max"})(Ql||(Ql={}));var go;(function(o){o.Keep="keep",o.Zero="zero",o.Replace="replace",o.Invert="invert",o.IncrementClamp="increment-clamp",o.DecrementClamp="decrement-clamp",o.IncrementWrap="increment-wrap",o.DecrementWrap="decrement-wrap"})(go||(go={}));var gh;(function(o){o.Uint16="uint16",o.Uint32="uint32"})(gh||(gh={}));var ps;(function(o){o.Uint8x2="uint8x2",o.Uint8x4="uint8x4",o.Sint8x2="sint8x2",o.Sint8x4="sint8x4",o.Unorm8x2="unorm8x2",o.Unorm8x4="unorm8x4",o.Snorm8x2="snorm8x2",o.Snorm8x4="snorm8x4",o.Uint16x2="uint16x2",o.Uint16x4="uint16x4",o.Sint16x2="sint16x2",o.Sint16x4="sint16x4",o.Unorm16x2="unorm16x2",o.Unorm16x4="unorm16x4",o.Snorm16x2="snorm16x2",o.Snorm16x4="snorm16x4",o.Float16x2="float16x2",o.Float16x4="float16x4",o.Float32="float32",o.Float32x2="float32x2",o.Float32x3="float32x3",o.Float32x4="float32x4",o.Uint32="uint32",o.Uint32x2="uint32x2",o.Uint32x3="uint32x3",o.Uint32x4="uint32x4",o.Sint32="sint32",o.Sint32x2="sint32x2",o.Sint32x3="sint32x3",o.Sint32x4="sint32x4",o.UNORM10x10x10x2="unorm10-10-10-2"})(ps||(ps={}));var N_;(function(o){o.Vertex="vertex",o.Instance="instance"})(N_||(N_={}));var M0;(function(o){o.Beginning="beginning",o.End="end"})(M0||(M0={}));var D0;(function(o){o.Beginning="beginning",o.End="end"})(D0||(D0={}));var ir;(function(o){o.Load="load",o.Clear="clear"})(ir||(ir={}));var ba;(function(o){o.Store="store",o.Discard="discard"})(ba||(ba={}));var w_;(function(o){o.Occlusion="occlusion",o.Timestamp="timestamp"})(w_||(w_={}));var F_;(function(o){o.Opaque="opaque",o.Premultiplied="premultiplied"})(F_||(F_={}));var O0;(function(o){o.Unknown="unknown",o.Destroyed="destroyed"})(O0||(O0={}));var N0;(function(o){o.Validation="validation",o.OutOfMemory="out-of-memory",o.Internal="internal"})(N0||(N0={}));class us{constructor(){this.shaderLanguage=is.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let r=0;r=0&&(d.push(a[u]),f.push(p))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new it(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=us.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||e===void 0?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)===null||e===void 0?void 0:e.fragment}}const I2=4,P2=65536,w0={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Ma{static get KnownUBOs(){return Ma._SimplifiedKnownBindings?Ma._SimplifiedKnownUBOs:Ma._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=Ma.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;const s=this._attributeNextLocation;return this._attributeNextLocation+=((i=w0[e])!==null&&i!==void 0?i:1)*(t||1),s}getVaryingNextLocation(e,t=0){var i;const s=this._varyingNextLocation;return this._varyingNextLocation+=((i=w0[e])!==null&&i!==void 0?i:1)*(t||1),s}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>P2-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===I2)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}}Ma._SimplifiedKnownBindings=!0;Ma._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}}};Ma._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 M2 extends us{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=is.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const a=e.substring(r+1,n);s=+a,isNaN(s)&&(s=+i[a.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 ${us.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){var s;this._preProcessors=i;const r=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,a=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,h=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?r:a).exec(e);if(h!==null){const c=(s=h[1])!==null&&s!==void 0?s:"",u=h[2],d=h[3];let f;t?(f=this._webgpuProcessingContext.availableVaryings[d],this._missingVaryings[f]="",f===void 0&&G.Warn(`Invalid fragment shader: The varying named "${d}" is not declared in the vertex shader! This declaration will be ignored.`)):(f=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(d,u,i)[2]),this._webgpuProcessingContext.availableVaryings[d]=f,this._missingVaryings[f]=`layout(location = ${f}) ${c} in ${u} ${d};`),e=e.replace(h[0],f===void 0?"":`layout(location = ${f}) ${c} ${t?"in":"out"} ${u} ${d};`)}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 a=n[1],l=n[2],h=this._webgpuProcessingContext.getAttributeNextLocation(a,this._getArraySize(l,a,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}; ${a} ${l} = ${a}(${d});`)}else e=e.replace(n[0],`layout(location = ${h}) in ${a} ${l};`)}return e}uniformProcessor(e,t,i){var s;this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let a=n[1],l=n[2];if(a.indexOf("sampler")===0||a.indexOf("sampler")===1){let h=0;[l,a,h]=this._getArraySize(l,a,i);let c=this._webgpuProcessingContext.availableTextures[l];if(!c){c={autoBindSampler:!0,isTextureArray:h>0,isStorageTexture:!1,textures:[],sampleType:oa.Float};for(let N=0;N<(h||1);++N)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(s=us._SamplerTypeByWebGLSamplerType[a])!==null&&s!==void 0?s:"sampler",d=!!us._IsComparisonSamplerByWebGPUSamplerType[u],f=d?_h.Comparison:_h.Filtering,p=l+us.AutoSamplerSuffix;let _=this._webgpuProcessingContext.availableSamplers[p];_||(_={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:f});const g=a.charAt(0)==="u"?"u":a.charAt(0)==="i"?"i":"";g&&(a=a.substr(1));const v=d?oa.Depth:g==="u"?oa.Uint:g==="i"?oa.Sint:oa.Float;c.sampleType=v;const E=h>0,C=_.binding.groupIndex,S=_.binding.bindingIndex,b=us._SamplerFunctionByWebGLSamplerType[a],R=us._TextureTypeByWebGLSamplerType[a],I=us._GpuTextureViewDimensionByWebGPUTextureType[R];if(!E)h=1,e=`layout(set = ${C}, binding = ${S}) uniform ${u} ${p}; +`+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){var s;this._preProcessors=i;const r=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,a=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,h=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?r:a).exec(e);if(h!==null){const c=(s=h[1])!==null&&s!==void 0?s:"",u=h[2],d=h[3];let f;t?(f=this._webgpuProcessingContext.availableVaryings[d],this._missingVaryings[f]="",f===void 0&&G.Warn(`Invalid fragment shader: The varying named "${d}" is not declared in the vertex shader! This declaration will be ignored.`)):(f=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(d,u,i)[2]),this._webgpuProcessingContext.availableVaryings[d]=f,this._missingVaryings[f]=`layout(location = ${f}) ${c} in ${u} ${d};`),e=e.replace(h[0],f===void 0?"":`layout(location = ${f}) ${c} ${t?"in":"out"} ${u} ${d};`)}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 a=n[1],l=n[2],h=this._webgpuProcessingContext.getAttributeNextLocation(a,this._getArraySize(l,a,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}; ${a} ${l} = ${a}(${d});`)}else e=e.replace(n[0],`layout(location = ${h}) in ${a} ${l};`)}return e}uniformProcessor(e,t,i){var s;this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let a=n[1],l=n[2];if(a.indexOf("sampler")===0||a.indexOf("sampler")===1){let h=0;[l,a,h]=this._getArraySize(l,a,i);let c=this._webgpuProcessingContext.availableTextures[l];if(!c){c={autoBindSampler:!0,isTextureArray:h>0,isStorageTexture:!1,textures:[],sampleType:oa.Float};for(let N=0;N<(h||1);++N)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(s=us._SamplerTypeByWebGLSamplerType[a])!==null&&s!==void 0?s:"sampler",d=!!us._IsComparisonSamplerByWebGPUSamplerType[u],f=d?mh.Comparison:mh.Filtering,p=l+us.AutoSamplerSuffix;let _=this._webgpuProcessingContext.availableSamplers[p];_||(_={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:f});const g=a.charAt(0)==="u"?"u":a.charAt(0)==="i"?"i":"";g&&(a=a.substr(1));const v=d?oa.Depth:g==="u"?oa.Uint:g==="i"?oa.Sint:oa.Float;c.sampleType=v;const E=h>0,C=_.binding.groupIndex,S=_.binding.bindingIndex,b=us._SamplerFunctionByWebGLSamplerType[a],R=us._TextureTypeByWebGLSamplerType[a],I=us._GpuTextureViewDimensionByWebGPUTextureType[R];if(!E)h=1,e=`layout(set = ${C}, binding = ${S}) uniform ${u} ${p}; layout(set = ${c.textures[0].groupIndex}, binding = ${c.textures[0].bindingIndex}) uniform ${g}${R} ${l}Texture; #define ${l} ${g}${b}(${l}Texture, ${p})`;else{const N=[];N.push(`layout(set = ${C}, binding = ${S}) uniform ${g}${u} ${p};`),e=` `;for(let O=0;O0?` `:""}#define ${l}${O} ${g}${b}(${l}Texture${O}, ${p})`}e=N.join(` -`)+e,this._textureArrayProcessing.push(l)}this._webgpuProcessingContext.availableTextures[l]=c,this._webgpuProcessingContext.availableSamplers[p]=_,this._addSamplerBindingDescription(p,_,!t);for(let N=0;N=0,h=` +`)+e,this._textureArrayProcessing.push(l)}this._webgpuProcessingContext.availableTextures[l]=c,this._webgpuProcessingContext.availableSamplers[p]=_,this._addSamplerBindingDescription(p,_,!t);for(let N=0;N=0,h=` glFragCoord_ = gl_FragCoord; if (yFactor_ == 1.) { glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; @@ -2741,7 +2741,7 @@ layout (num_views = 2) in; `;return i+=`}; `,i}finalizeShaders(e,t){for(let s=0;s0&&(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 I2="bonesDeclaration",P2=`#if NUM_BONE_INFLUENCERS>0 +`+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 D2="bonesDeclaration",O2=`#if NUM_BONE_INFLUENCERS>0 attribute matricesIndices : vec4;attribute matricesWeights : vec4; #if NUM_BONE_INFLUENCERS>4 attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; @@ -2762,7 +2762,7 @@ let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2 #endif #endif #endif -`;ne.IncludesShadersStoreWGSL[I2]=P2;const M2="bonesVertex",D2=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStoreWGSL[D2]=O2;const N2="bonesVertex",w2=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4; #ifdef BONETEXTURE @@ -2815,7 +2815,7 @@ influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*v finalWorld=finalWorld*influence; #endif #endif -`;ne.IncludesShadersStoreWGSL[M2]=D2;const O2="bakedVertexAnimationDeclaration",N2=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStoreWGSL[N2]=w2;const F2="bakedVertexAnimationDeclaration",L2=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; #ifdef INSTANCES attribute bakedVertexAnimationSettingsInstanced : vec4; @@ -2823,7 +2823,7 @@ attribute bakedVertexAnimationSettingsInstanced : vec4; fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 {let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} #endif -`;ne.IncludesShadersStoreWGSL[O2]=N2;const w2="bakedVertexAnimation",F2=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;ne.IncludesShadersStoreWGSL[F2]=L2;const B2="bakedVertexAnimation",V2=`#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; @@ -2854,7 +2854,7 @@ VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTextur #endif finalWorld=finalWorld*VATInfluence;} #endif -`;ne.IncludesShadersStoreWGSL[w2]=F2;const L2="clipPlaneFragment",B2=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +`;ne.IncludesShadersStoreWGSL[B2]=V2;const U2="clipPlaneFragment",k2=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE @@ -2881,7 +2881,7 @@ else if (fragmentInputs.fClipDistance5>0.0) else if (fragmentInputs.fClipDistance6>0.0) {discard;} #endif -`;ne.IncludesShadersStoreWGSL[L2]=B2;const V2="clipPlaneFragmentDeclaration",U2=`#ifdef CLIPPLANE +`;ne.IncludesShadersStoreWGSL[U2]=k2;const G2="clipPlaneFragmentDeclaration",z2=`#ifdef CLIPPLANE varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 @@ -2899,7 +2899,7 @@ varying fClipDistance5: f32; #ifdef CLIPPLANE6 varying fClipDistance6: f32; #endif -`;ne.IncludesShadersStoreWGSL[V2]=U2;const k2="clipPlaneVertex",G2=`#ifdef CLIPPLANE +`;ne.IncludesShadersStoreWGSL[G2]=z2;const W2="clipPlaneVertex",H2=`#ifdef CLIPPLANE vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); #endif #ifdef CLIPPLANE2 @@ -2917,7 +2917,7 @@ vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); #ifdef CLIPPLANE6 vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); #endif -`;ne.IncludesShadersStoreWGSL[k2]=G2;const z2="clipPlaneVertexDeclaration",W2=`#ifdef CLIPPLANE +`;ne.IncludesShadersStoreWGSL[W2]=H2;const X2="clipPlaneVertexDeclaration",Y2=`#ifdef CLIPPLANE uniform vClipPlane: vec4;varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 @@ -2935,7 +2935,7 @@ uniform vClipPlane5: vec4;varying fClipDistance5: f32; #ifdef CLIPPLANE6 uniform vClipPlane6: vec4;varying fClipDistance6: f32; #endif -`;ne.IncludesShadersStoreWGSL[z2]=W2;const H2="instancesDeclaration",X2=`#ifdef INSTANCES +`;ne.IncludesShadersStoreWGSL[X2]=Y2;const $2="instancesDeclaration",K2=`#ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #ifdef INSTANCESCOLOR attribute instanceColor : vec4; @@ -2957,7 +2957,7 @@ uniform world : mat4x4; uniform previousWorld : mat4x4; #endif #endif -`;ne.IncludesShadersStoreWGSL[H2]=X2;const Y2="instancesVertex",$2=`#ifdef INSTANCES +`;ne.IncludesShadersStoreWGSL[$2]=K2;const q2="instancesVertex",j2=`#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); @@ -2982,10 +2982,10 @@ var finalWorld=mesh.world; var finalPreviousWorld=previousWorld; #endif #endif -`;ne.IncludesShadersStoreWGSL[Y2]=$2;const K2="meshUboDeclaration",q2=`struct Mesh {world : mat4x4, +`;ne.IncludesShadersStoreWGSL[q2]=j2;const Q2="meshUboDeclaration",Z2=`struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO -`;ne.IncludesShadersStoreWGSL[K2]=q2;const j2="morphTargetsVertex",Q2=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStoreWGSL[Q2]=Z2;const J2="morphTargetsVertex",eV=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; #ifdef MORPHTARGETS_NORMAL @@ -3010,7 +3010,7 @@ uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}] #endif #endif #endif -`;ne.IncludesShadersStoreWGSL[j2]=Q2;const Z2="morphTargetsVertexDeclaration",J2=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStoreWGSL[J2]=eV;const tV="morphTargetsVertexDeclaration",iV=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE attribute position{X} : vec3; #ifdef MORPHTARGETS_NORMAL @@ -3024,12 +3024,12 @@ attribute uv_{X} : vec2; #endif #endif #endif -`;ne.IncludesShadersStoreWGSL[Z2]=J2;const eV="morphTargetsVertexGlobal",tV=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStoreWGSL[tV]=iV;const sV="morphTargetsVertexGlobal",rV=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif -`;ne.IncludesShadersStoreWGSL[eV]=tV;const iV="morphTargetsVertexGlobalDeclaration",sV=`#ifdef MORPHTARGETS +`;ne.IncludesShadersStoreWGSL[sV]=rV;const nV="morphTargetsVertexGlobalDeclaration",aV=`#ifdef MORPHTARGETS uniform morphTargetInfluences : array; #ifdef MORPHTARGETS_TEXTURE uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 @@ -3037,19 +3037,19 @@ uniform morphTargetTextureIndices : array;uniform mor let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} #endif #endif -`;ne.IncludesShadersStoreWGSL[iV]=sV;const rV="sceneUboDeclaration",nV=`struct Scene {viewProjection : mat4x4, +`;ne.IncludesShadersStoreWGSL[nV]=aV;const oV="sceneUboDeclaration",lV=`struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif view : mat4x4, projection : mat4x4, vEyePosition : vec4,};var scene : Scene; -`;ne.IncludesShadersStoreWGSL[rV]=nV;const N0="fragmentOutputs.fragDepth",aV="uniforms",oV="internals",lV={texture_1d:qi.E1d,texture_2d:qi.E2d,texture_2d_array:qi.E2dArray,texture_3d:qi.E3d,texture_cube:qi.Cube,texture_cube_array:qi.CubeArray,texture_multisampled_2d:qi.E2d,texture_depth_2d:qi.E2d,texture_depth_2d_array:qi.E2dArray,texture_depth_cube:qi.Cube,texture_depth_cube_array:qi.CubeArray,texture_depth_multisampled_2d:qi.E2d,texture_storage_1d:qi.E1d,texture_storage_2d:qi.E2d,texture_storage_2d_array:qi.E2dArray,texture_storage_3d:qi.E3d,texture_external:null};class hV extends us{constructor(){super(...arguments),this.shaderLanguage=is.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 a=t.substring(n+1,r);for(s=+a,isNaN(s)&&(s=+i[a.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){return`struct ${us.InternalsUBOName} { +`;ne.IncludesShadersStoreWGSL[oV]=lV;const F0="fragmentOutputs.fragDepth",hV="uniforms",cV="internals",uV={texture_1d:qi.E1d,texture_2d:qi.E2d,texture_2d_array:qi.E2dArray,texture_3d:qi.E3d,texture_cube:qi.Cube,texture_cube_array:qi.CubeArray,texture_multisampled_2d:qi.E2d,texture_depth_2d:qi.E2d,texture_depth_2d_array:qi.E2dArray,texture_depth_cube:qi.Cube,texture_depth_cube_array:qi.CubeArray,texture_depth_multisampled_2d:qi.E2d,texture_storage_1d:qi.E1d,texture_storage_2d:qi.E2d,texture_storage_2d_array:qi.E2dArray,texture_storage_3d:qi.E3d,texture_external:null};class dV extends us{constructor(){super(...arguments),this.shaderLanguage=is.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 a=t.substring(n+1,r);for(s=+a,isNaN(s)&&(s=+i[a.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){return`struct ${us.InternalsUBOName} { yFactor_: f32, textureOutputHeight_: f32, }; -var ${oV} : ${us.InternalsUBOName}; -`+kv(e)}varyingProcessor(e,t,i){const r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[2],a=r[1];let l;t?(l=this._webgpuProcessingContext.availableVaryings[a],l===void 0&&G.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(l=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=l,this._varyingsWGSL.push(` @location(${l}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),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],a=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=a,this._webgpuProcessingContext.orderedAttributes[a]=n;const l=this.vertexBufferKindToNumberOfComponents[n];if(l!==void 0){const h=l<0?l===-1?"i32":"vec"+-l+"":l===1?"u32":"vec"+l+"",c=`_int_${n}_`;this._attributesInputWGSL.push(`@location(${a}) ${c} : ${h},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = ${r}(vertexInputs_.${c});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${a}) ${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],a=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let d=a?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:oa.Float},d=d||1;for(let v=0;v0,_=lV[l],g=p?oa.Depth:c==="u32"?oa.Uint:c==="i32"?oa.Sint:oa.Float;if(f.sampleType=g,_===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let v=0;v=0?` +var ${cV} : ${us.InternalsUBOName}; +`+kv(e)}varyingProcessor(e,t,i){const r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[2],a=r[1];let l;t?(l=this._webgpuProcessingContext.availableVaryings[a],l===void 0&&G.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(l=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=l,this._varyingsWGSL.push(` @location(${l}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),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],a=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=a,this._webgpuProcessingContext.orderedAttributes[a]=n;const l=this.vertexBufferKindToNumberOfComponents[n];if(l!==void 0){const h=l<0?l===-1?"i32":"vec"+-l+"":l===1?"u32":"vec"+l+"",c=`_int_${n}_`;this._attributesInputWGSL.push(`@location(${a}) ${c} : ${h},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = ${r}(vertexInputs_.${c});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${a}) ${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],a=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let d=a?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:oa.Float},d=d||1;for(let v=0;v0,_=uV[l],g=p?oa.Depth:c==="u32"?oa.Uint:c==="i32"?oa.Sint:oa.Float;if(f.sampleType=g,_===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let v=0;v=0?` if (internals.yFactor_ == 1.) { fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; } @@ -3088,8 +3088,8 @@ vertexInputs.instanceIndex = vertexInputs_.instanceIndex; var fragmentInputs : FragmentInputs; `;let c=`struct FragmentOutputs { @location(0) color : vec4, -`,u=!1,d=0;for(;!u&&(d=t.indexOf(N0,d),!(d<0));){const _=d;for(u=!0;d>1&&t.charAt(d)!==` -`;){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=_+N0.length}u&&(c+=` @builtin(frag_depth) fragDepth: f32, +`,u=!1,d=0;for(;!u&&(d=t.indexOf(F0,d),!(d<0));){const _=d;for(u=!0;d>1&&t.charAt(d)!==` +`;){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=_+F0.length}u&&(c+=` @builtin(frag_depth) fragDepth: f32, `),c+=`}; var fragmentOutputs : FragmentOutputs; `,t=h+c+t;const f=` fragmentInputs = input; @@ -3102,8 +3102,8 @@ var fragmentOutputs : FragmentOutputs; `;else s+=` ${r.name} : ${r.type}, `}return s+=`}; `,s=`${i} -${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${aV} : ${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],a=r.indexOf(us.AutoSamplerSuffix)===r.length-us.AutoSamplerSuffix.length?r.substring(0,r.indexOf(us.AutoSamplerSuffix)):null,l=n==="sampler_comparison"?_h.Comparison:_h.Filtering;if(a){const f=this._webgpuProcessingContext.availableTextures[a];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 a=s[4];const l=s[5];let h=this._webgpuProcessingContext.availableBuffers[a];if(!h){const _=r==="uniform"?Ma.KnownUBOs[l]:null;let g;_?(a=l,g=_.binding,g.groupIndex===-1&&(g=this._webgpuProcessingContext.getNextFreeUBOBinding())):g=this._webgpuProcessingContext.getNextFreeUBOBinding(),h={binding:g},this._webgpuProcessingContext.availableBuffers[a]=h}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],n==="read_write"?rh.Storage:r==="storage"?rh.ReadOnlyStorage:rh.Uniform,t);const c=h.binding.groupIndex,u=h.binding.bindingIndex,d=e.substring(0,s.index),f=`@group(${c}) @binding(${u}) `,p=e.substring(s.index);e=d+f+p,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 T_{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return(i=(t=this._webgpuMSAATexture)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=U.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){this.createView({format:this.format,dimension:i?qi.Cube:qi.E2d,mipLevelCount:t?ye.ILog2(Math.max(s,r))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:Go.All})}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===void 0||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)===null||t===void 0||t.destroy(),this.reset()}}const cV=` +${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${hV} : ${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],a=r.indexOf(us.AutoSamplerSuffix)===r.length-us.AutoSamplerSuffix.length?r.substring(0,r.indexOf(us.AutoSamplerSuffix)):null,l=n==="sampler_comparison"?mh.Comparison:mh.Filtering;if(a){const f=this._webgpuProcessingContext.availableTextures[a];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 a=s[4];const l=s[5];let h=this._webgpuProcessingContext.availableBuffers[a];if(!h){const _=r==="uniform"?Ma.KnownUBOs[l]:null;let g;_?(a=l,g=_.binding,g.groupIndex===-1&&(g=this._webgpuProcessingContext.getNextFreeUBOBinding())):g=this._webgpuProcessingContext.getNextFreeUBOBinding(),h={binding:g},this._webgpuProcessingContext.availableBuffers[a]=h}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],n==="read_write"?nh.Storage:r==="storage"?nh.ReadOnlyStorage:nh.Uniform,t);const c=h.binding.groupIndex,u=h.binding.bindingIndex,d=e.substring(0,s.index),f=`@group(${c}) @binding(${u}) `,p=e.substring(s.index);e=d+f+p,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 T_{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return(i=(t=this._webgpuMSAATexture)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=U.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){this.createView({format:this.format,dimension:i?qi.Cube:qi.E2d,mipLevelCount:t?ye.ILog2(Math.max(s,r))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:Go.All})}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===void 0||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)===null||t===void 0||t.destroy(),this.reset()}}const fV=` 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)); @@ -3113,7 +3113,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va vTex = tex[gl_VertexIndex]; gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); } - `,uV=` + `,pV=` layout(set = 0, binding = 0) uniform sampler imgSampler; layout(set = 0, binding = 1) uniform texture2D img; @@ -3123,7 +3123,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va void main() { outColor = texture(sampler2D(img, imgSampler), vTex); } - `,_y=` + `,gy=` #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)); @@ -3141,7 +3141,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va #endif gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); } - `,dV=` + `,_V=` #extension GL_EXT_samplerless_texture_functions : enable layout(set = 0, binding = 0) uniform texture2D img; @@ -3162,7 +3162,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va #endif outColor = color; } - `,fV=_y,pV=` + `,mV=gy,gV=` #extension GL_EXT_samplerless_texture_functions : enable layout(set = 0, binding = 0) uniform texture2D img; @@ -3195,13 +3195,13 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va #endif outColor = color; } - `,_V=` + `,vV=` 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); } - `,mV=` + `,xV=` layout(set = 0, binding = 0) uniform Uniforms { uniform vec4 color; }; @@ -3211,7 +3211,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va void main() { outColor = color; } - `,gV=` + `,TV=` struct VertexOutput { @builtin(position) Position : vec4, @location(0) fragUV : vec2 @@ -3241,7 +3241,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va return output; } - `,vV=` + `,EV=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @@ -3251,7 +3251,7 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); } - `,xV=` + `,SV=` @group(0) @binding(0) var videoSampler: sampler; @group(0) @binding(1) var videoTexture: texture_external; @@ -3261,10 +3261,10 @@ ${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) va ) -> @location(0) vec4 { return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); } - `;var Za;(function(o){o[o.MipMap=0]="MipMap",o[o.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",o[o.Clear=2]="Clear",o[o.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Za||(Za={}));var wc;(function(o){o[o.DontInvertY=0]="DontInvertY",o[o.InvertY=1]="InvertY"})(wc||(wc={}));const w0=[{vertex:cV,fragment:uV},{vertex:_y,fragment:dV},{vertex:_V,fragment:mV},{vertex:fV,fragment:pV}],zo={"":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 Ri{static ComputeNumMipmapLevels(e,t){return ye.ILog2(Math.max(e,t))+1}constructor(e,t,i,s,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=s,r.indexOf(Tl.RG11B10UFloatRenderable)!==-1){const n=Object.keys(zo);zo[U.RG11B10UFloat]=zo[n[n.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:ri.Linear}),this._videoSampler=e.createSampler({minFilter:ri.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,Hi.Uniform|Hi.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(U.RGBA8Unorm),this._getVideoPipeline(U.RGBA8Unorm)}_getPipeline(e,t=Za.MipMap,i){const s=t===Za.MipMap?1:t===Za.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Za.Clear?8:t===Za.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 + `;var Za;(function(o){o[o.MipMap=0]="MipMap",o[o.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",o[o.Clear=2]="Clear",o[o.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Za||(Za={}));var wc;(function(o){o[o.DontInvertY=0]="DontInvertY",o[o.InvertY=1]="InvertY"})(wc||(wc={}));const L0=[{vertex:fV,fragment:pV},{vertex:gy,fragment:_V},{vertex:vV,fragment:xV},{vertex:mV,fragment:gV}],zo={"":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 Ri{static ComputeNumMipmapLevels(e,t){return ye.ILog2(Math.max(e,t))+1}constructor(e,t,i,s,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=s,r.indexOf(Tl.RG11B10UFloatRenderable)!==-1){const n=Object.keys(zo);zo[U.RG11B10UFloat]=zo[n[n.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:ri.Linear}),this._videoSampler=e.createSampler({minFilter:ri.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,Hi.Uniform|Hi.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(U.RGBA8Unorm),this._getVideoPipeline(U.RGBA8Unorm)}_getPipeline(e,t=Za.MipMap,i){const s=t===Za.MipMap?1:t===Za.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Za.Clear?8:t===Za.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===Za.InvertYPremultiplyAlpha||t===Za.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+=`#define INVERTY `),i.premultiplyAlpha&&(n+=`#define PREMULTIPLYALPHA -`));let a=this._compiledShaders[s];if(!a){let h=this._glslang.compileGLSL(n+w0[t].vertex,"vertex"),c=this._glslang.compileGLSL(n+w0[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});a=this._compiledShaders[s]=[u,d]}const l=this._device.createRenderPipeline({layout:Pd.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:sa.TriangleStrip,stripIndexFormat:mh.Uint16}});r=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=wc.DontInvertY){const i=t===wc.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 a=this._device.createShaderModule({code:gV}),l=this._device.createShaderModule({code:i===0?vV:xV});r=this._videoCompiledShaders[i]=[a,l]}const n=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:Pd.Auto,vertex:{module:r[0],entryPoint:"main"},fragment:{module:r[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:sa.TriangleStrip,stripIndexFormat:mh.Uint16}});s=this._videoPipelines[e][i]=[n,n.getBindGroupLayout(0)]}return s}static GetTextureTypeFromFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.RGB9E5UFloat:case U.RG11B10UFloat:case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC4RUnorm:case U.BC4RSnorm:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:case U.EACRG11Unorm:case U.EACRG11Snorm:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:case U.Stencil8:return 0;case U.R16Uint:case U.R16Sint:case U.RG16Uint:case U.RG16Sint:case U.RGBA16Uint:case U.RGBA16Sint:case U.Depth16Unorm:return 5;case U.R16Float:case U.RG16Float:case U.RGBA16Float:return 2;case U.R32Uint:case U.R32Sint:case U.RG32Uint:case U.RG32Sint:case U.RGBA32Uint:case U.RGBA32Sint:return 7;case U.R32Float:case U.RG32Float:case U.RGBA32Float:case U.Depth32Float:case U.Depth32FloatStencil8:case U.Depth24Plus:case U.Depth24PlusStencil8:return 1}return 0}static _GetBlockInformationFromFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:return{width:1,height:1,length:1};case U.R16Uint:case U.R16Sint:case U.R16Float:case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:return{width:1,height:1,length:2};case U.R32Uint:case U.R32Sint:case U.R32Float:case U.RG16Uint:case U.RG16Sint:case U.RG16Float:case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB9E5UFloat:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.RG11B10UFloat:return{width:1,height:1,length:4};case U.RG32Uint:case U.RG32Sint:case U.RG32Float:case U.RGBA16Uint:case U.RGBA16Sint:case U.RGBA16Float:return{width:1,height:1,length:8};case U.RGBA32Uint:case U.RGBA32Sint:case U.RGBA32Float:return{width:1,height:1,length:16};case U.Stencil8:throw"No fixed size for Stencil8 format!";case U.Depth16Unorm:return{width:1,height:1,length:2};case U.Depth24Plus:throw"No fixed size for Depth24Plus format!";case U.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case U.Depth32Float:return{width:1,height:1,length:4};case U.Depth32FloatStencil8:return{width:1,height:1,length:5};case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case U.BC4RUnorm:case U.BC4RSnorm:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:return{width:4,height:4,length:8};case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACRG11Unorm:case U.EACRG11Snorm:return{width:4,height:4,length:16};case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case U.ASTC12x12Unorm:case U.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}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case U.BC7RGBAUnormSRGB:case U.BC7RGBAUnorm:case U.BC6HRGBFloat:case U.BC6HRGBUFloat:case U.BC5RGSnorm:case U.BC5RGUnorm:case U.BC4RSnorm:case U.BC4RUnorm:case U.BC3RGBAUnormSRGB:case U.BC3RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.BC1RGBAUnorm:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:case U.EACRG11Unorm:case U.EACRG11Snorm:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return U.Depth16Unorm;case 16:return U.Depth24Plus;case 13:return U.Depth24PlusStencil8;case 14:return U.Depth32Float;case 18:return U.Depth32FloatStencil8;case 19:return U.Stencil8;case 36492:return i?U.BC7RGBAUnormSRGB:U.BC7RGBAUnorm;case 36495:return U.BC6HRGBUFloat;case 36494:return U.BC6HRGBFloat;case 33779:return i?U.BC3RGBAUnormSRGB:U.BC3RGBAUnorm;case 33778:return i?U.BC2RGBAUnormSRGB:U.BC2RGBAUnorm;case 33777:case 33776:return i?U.BC1RGBAUnormSRGB:U.BC1RGBAUnorm;case 37808:return i?U.ASTC4x4UnormSRGB:U.ASTC4x4Unorm;case 36196:case 37492:return i?U.ETC2RGB8UnormSRGB:U.ETC2RGB8Unorm;case 37496:return i?U.ETC2RGBA8UnormSRGB:U.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return U.R8Snorm;case 7:return U.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return U.R8Sint;case 9:return U.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA8Sint;default:return U.RGBA8Snorm}case 0:switch(t){case 6:return U.R8Unorm;case 7:return U.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?U.RGBA8UnormSRGB:U.RGBA8Unorm;case 12:return i?U.BGRA8UnormSRGB:U.BGRA8Unorm;case 8:return U.R8Uint;case 9:return U.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return U.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 U.RGBA8Unorm}case 4:switch(t){case 8:return U.R16Sint;case 9:return U.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA16Sint;default:return U.RGBA16Sint}case 5:switch(t){case 8:return U.R16Uint;case 9:return U.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA16Uint;default:return U.RGBA16Uint}case 6:switch(t){case 8:return U.R32Sint;case 9:return U.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA32Sint;default:return U.RGBA32Sint}case 7:switch(t){case 8:return U.R32Uint;case 9:return U.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA32Uint;default:return U.RGBA32Uint}case 1:switch(t){case 6:return U.R32Float;case 7:return U.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return U.RGBA32Float;default:return U.RGBA32Float}case 2:switch(t){case 6:return U.R16Float;case 7:return U.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return U.RGBA16Float;default:return U.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return U.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return U.RG11B10UFloat}case 14:switch(t){case 5:return U.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 U.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 U.RGB10A2Unorm;case 11:return U.RGB10A2UINT;default:return U.RGB10A2Unorm}}return i?U.RGBA8UnormSRGB:U.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:case U.BC4RUnorm:case U.BC4RSnorm:case U.R16Uint:case U.R16Sint:case U.Depth16Unorm:case U.R16Float:case U.R32Uint:case U.R32Sint:case U.R32Float:case U.Depth32Float:case U.Stencil8:case U.Depth24Plus:case U.EACR11Unorm:case U.EACR11Snorm:return 1;case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:case U.Depth32FloatStencil8:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.RG16Uint:case U.RG16Sint:case U.RG16Float:case U.RG32Uint:case U.RG32Sint:case U.RG32Float:case U.Depth24PlusStencil8:case U.EACRG11Unorm:case U.EACRG11Snorm:return 2;case U.RGB9E5UFloat:case U.RG11B10UFloat:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:return 3;case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.RGBA16Uint:case U.RGBA16Sint:case U.RGBA16Float:case U.RGBA32Uint:case U.RGBA32Sint:case U.RGBA32Float:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case U.Stencil8:case U.Depth32FloatStencil8:case U.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case U.Depth32FloatStencil8:case U.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case U.Depth16Unorm:return U.Depth16Unorm;case U.Depth24Plus:return U.Depth24Plus;case U.Depth24PlusStencil8:return U.Depth24Plus;case U.Depth32Float:return U.Depth32Float;case U.Depth32FloatStencil8:return U.Depth32Float}return e}static GetSample(e){return e>1?4:1}copyVideoToTexture(e,t,i,s=!1,r){var n,a,l,h;const c=r===void 0,[u,d]=this._getVideoPipeline(i,s?wc.InvertY:wc.DontInvertY);c&&(r=this._device.createCommandEncoder({})),(a=(n=r).pushDebugGroup)===null||a===void 0||a.call(n,`copy video to texture - invertY=${s}`);const p={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:qi.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:Go.All}),loadOp:ir.Load,storeOp:ba.Store}]},_=r.beginRenderPass(p),g={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},v=this._device.createBindGroup(g);_.setPipeline(u),_.setBindGroup(0,v),_.draw(4,1,0,0),_.end(),(h=(l=r).popDebugGroup)===null||h===void 0||h.call(l),c&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,a=0,l=0,h=1,c=0,u=0,d=0,f=0,p,_){var g,v,E,C,S,b;const R=d!==0,I=p===void 0,[N,O]=this._getPipeline(s,R?Za.InvertYPremultiplyAlphaWithOfst:Za.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});a=Math.max(a,0),I&&(p=this._device.createCommandEncoder({})),(v=(g=p).pushDebugGroup)===null||v===void 0||v.call(g,`internal process texture - invertY=${r} premultiplyAlpha=${n}`);let L;if(Ri._IsHardwareTexture(e)?(L=e.underlyingResource,r&&!n&&h===1&&a===0||(e=void 0)):(L=e,e=void 0),!L)return;R&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,d,f]),0,4*4);const B=e,V=(E=B==null?void 0:B._copyInvertYTempTexture)!==null&&E!==void 0?E:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,p,ls.CopySrc|ls.RenderAttachment|ls.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),Z=(C=B==null?void 0:B._copyInvertYRenderPassDescr)!==null&&C!==void 0?C:{colorAttachments:[{view:V.createView({format:s,dimension:qi.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:ir.Load,storeOp:ba.Store}]},ue=p.beginRenderPass(Z);let oe=R?B==null?void 0:B._copyInvertYBindGroupWithOfst:B==null?void 0:B._copyInvertYBindGroup;if(!oe){const me={layout:O,entries:[{binding:0,resource:L.createView({format:s,dimension:qi.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:a})}]};R&&me.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),oe=this._device.createBindGroup(me)}ue.setPipeline(N),ue.setBindGroup(0,oe),ue.draw(4,1,0,0),ue.end(),p.copyTextureToTexture({texture:V},{texture:L,mipLevel:l,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),B?(B._copyInvertYTempTexture=V,B._copyInvertYRenderPassDescr=Z,R?B._copyInvertYBindGroupWithOfst=oe:B._copyInvertYBindGroup=oe):this._deferredReleaseTextures.push([V,null]),(b=(S=p).popDebugGroup)===null||b===void 0||b.call(S),I&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,s){var r,n,a,l;const h=s===void 0,[c,u]=this._getPipeline(t,Za.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});h&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,"internal copy texture with invertY");const d=s.beginRenderPass(i),f=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});d.setPipeline(c),d.setBindGroup(0,f),d.draw(4,1,0,0),d.end(),(l=(a=s).popDebugGroup)===null||l===void 0||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,a=U.RGBA8Unorm,l=1,h,c=-1,u=0,d){l=Ri.GetSample(l);const f=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:f},_=zo[a]?ls.RenderAttachment:0,g=Ri.IsCompressedFormat(a),v=t?Ri.ComputeNumMipmapLevels(e.width,e.height):1,E=c>=0?c:ls.CopySrc|ls.CopyDst|ls.TextureBinding;u|=t&&!g?ls.CopySrc|_:0,!g&&!n&&(u|=_|ls.CopyDst);const C=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${l}`,size:p,dimension:n?to.E3d:to.E2d,format:a,usage:E|u,sampleCount:l,mipLevelCount:v});return Ri.IsImageBitmap(e)&&(this.updateTexture(e,C,e.width,e.height,f,a,0,0,s,r,0,0),t&&i&&this.generateMipmaps(C,a,v,0,h)),C}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=U.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Ri.GetSample(a);const d=Ri.IsImageBitmapArray(e)?e[0].width:e.width,f=Ri.IsImageBitmapArray(e)?e[0].height:e.height,p=zo[n]?ls.RenderAttachment:0,_=Ri.IsCompressedFormat(n),g=t?Ri.ComputeNumMipmapLevels(d,f):1,v=h>=0?h:ls.CopySrc|ls.CopyDst|ls.TextureBinding;c|=t&&!_?ls.CopySrc|p:0,_||(c|=p|ls.CopyDst);const E=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:to.E2d,format:n,usage:v|c,sampleCount:a,mipLevelCount:g});return Ri.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,E,d,f,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(E,n,g,l)),E}generateCubeMipmaps(e,t,i,s){var r,n,a,l;const h=s===void 0;h&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,`create cube mipmaps - ${i} levels`);for(let c=0;c<6;++c)this.generateMipmaps(e,t,i,c,s);(l=(a=s).popDebugGroup)===null||l===void 0||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r){var n,a,l,h,c,u,d,f;const p=r===void 0,[_,g]=this._getPipeline(t);s=Math.max(s,0),p&&(r=this._device.createCommandEncoder({})),(a=(n=r).pushDebugGroup)===null||a===void 0||a.call(n,`create mipmaps for face #${s} - ${i} levels`);let v;if(Ri._IsHardwareTexture(e)?(v=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(v=e,e=void 0),!v)return;const E=e;for(let C=1;Cc;)this._device.queue.writeBuffer(n,t+u,i.buffer,a+u,c),u+=c;this._device.queue.writeBuffer(n,t+u,i.buffer,a+u,r-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=wo(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,a=0,l=0,h=null,c=!0,u=!1){const d=a===1?2:a===2?1:0;return new Promise((f,p)=>{e.mapAsync(Xh.Read,l,t).then(()=>{const _=e.getMappedRange(l,t);let g=h;if(u)g===null?g=Fv(a,t,!0,_):g=Fv(a,g.buffer,void 0,_);else if(g===null)switch(d){case 0:g=new Uint8Array(t),g.set(new Uint8Array(_));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_);break;case 2:g=new Float32Array(t/4),g.set(new Float32Array(_));break}else switch(d){case 0:g=new Uint8Array(g.buffer),g.set(new Uint8Array(_));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_,h);break;case 2:g=new Float32Array(g.buffer),g.set(new Float32Array(_));break}if(r!==n){d===1&&!u&&(r*=2,n*=2);const v=new Uint8Array(g.buffer);let E=r,C=0;for(let S=1;S{this._engine.isDisposed?f(new Uint8Array):p(_)})})}releaseBuffer(e){return L_._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e1?4:1;return EV[e.samplingMode]+SV[(e._comparisonFunction||514)-512+1]+CV[e.samplingMode]+(((t=e._cachedWrapU)!==null&&t!==void 0?t:1)<<8)+(((i=e._cachedWrapV)!==null&&i!==void 0?i:1)<<10)+(((s=e._cachedWrapR)!==null&&s!==void 0?s:1)<<12)+((e.useMipMaps?1:0)<<14)+(r<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,a;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=ri.Linear,s=ri.Linear,r=ri.Nearest,l||(n=a=0);break;case 3:case 3:i=ri.Linear,s=ri.Linear,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 8:i=ri.Nearest,s=ri.Nearest,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 4:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,l||(n=a=0);break;case 5:i=ri.Nearest,s=ri.Linear,r=ri.Nearest,l||(n=a=0);break;case 6:i=ri.Nearest,s=ri.Linear,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 7:i=ri.Nearest,s=ri.Linear,r=ri.Nearest,n=a=0;break;case 1:case 1:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,n=a=0;break;case 9:i=ri.Linear,s=ri.Nearest,r=ri.Nearest,l||(n=a=0);break;case 10:i=ri.Linear,s=ri.Nearest,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 2:case 2:i=ri.Linear,s=ri.Linear,r=ri.Nearest,n=a=0;break;case 12:i=ri.Linear,s=ri.Nearest,r=ri.Nearest,n=a=0;break;default:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,n=a=0;break}return t>1&&(n!==0||a!==0)&&r!==ri.Nearest?{magFilter:ri.Linear,minFilter:ri.Linear,mipmapFilter:ri.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:return Nc.Repeat;case 0:return Nc.ClampToEdge;case 2:return Nc.MirrorRepeat}return Nc.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 Object.assign(Object.assign(Object.assign({label:t},s),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?Uh.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1})}static GetCompareFunction(e){switch(e){case 519:return Mr.Always;case 514:return Mr.Equal;case 516:return Mr.Greater;case 518:return Mr.GreaterEqual;case 513:return Mr.Less;case 515:return Mr.LessEqual;case 512:return Mr.Never;case 517:return Mr.NotEqual;default:return Mr.Less}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(Uh._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=Uh.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(Uh._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var Ls;(function(o){o[o.StencilReadMask=0]="StencilReadMask",o[o.StencilWriteMask=1]="StencilWriteMask",o[o.DepthBias=2]="DepthBias",o[o.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",o[o.DepthStencilState=4]="DepthStencilState",o[o.MRTAttachments1=5]="MRTAttachments1",o[o.MRTAttachments2=6]="MRTAttachments2",o[o.RasterizationState=7]="RasterizationState",o[o.ColorStates=8]="ColorStates",o[o.ShaderStage=9]="ShaderStage",o[o.TextureStage=10]="TextureStage",o[o.VertexState=11]="VertexState",o[o.NumStates=12]="NumStates"})(Ls||(Ls={}));const h_={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},Ac={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},bV={[P.PositionKind]:!0,[P.NormalKind]:!0,[P.TangentKind]:!0,[P.UVKind]:!0,[P.UV2Kind]:!0,[P.UV3Kind]:!0,[P.UV4Kind]:!0,[P.UV5Kind]:!0,[P.UV6Kind]:!0,[P.ColorKind]:!0,[P.ColorInstanceKind]:!0,[P.MatricesIndicesKind]:!0,[P.MatricesWeightsKind]:!0,[P.MatricesIndicesExtraKind]:!0,[P.MatricesWeightsExtraKind]:!0};class hs{static _IsSignedType(e){switch(e){case P.BYTE:case P.SHORT:case P.INT:case P.FLOAT:return!0;case P.UNSIGNED_BYTE:case P.UNSIGNED_SHORT:case P.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=[U.BGRA8Unorm],this.setColorFormat(U.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(U.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=Ri.GetSample(i),this.disabled){const n=hs._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,i),hs.NumCacheMiss++,hs._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,hs.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return hs.NumCacheHitWithHash++,this._parameter.pipeline;const r=hs._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),hs.NumCacheMiss++,hs._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){hs.NumPipelineCreationLastFrame=hs._NumPipelineCreationCurrentFrame,hs._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,a,l){this._depthWriteEnabled=a,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[Ls.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[Ls.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=zo[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const r=[0,0];let n=0,a=0,l=0;for(let h=0;h=32&&(a=0,n++)}this._mrtFormats.length=l,(this._mrtAttachments1!==r[0]||this._mrtAttachments2!==r[1])&&(this._mrtAttachments1=r[0],this._mrtAttachments2=r[1],this._states[Ls.MRTAttachments1]=r[0],this._states[Ls.MRTAttachments2]=r[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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:zo[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:Ac[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:Ac[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:Ac[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[Ls.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[Ls.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:Ac[i],this._stencilFrontPassOp=s===null?2:Ac[s],this._stencilFrontFailOp=r===null?1:Ac[r],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return sa.TriangleList;case 2:return sa.PointList;case 1:return sa.LineList;case 3:return sa.PointList;case 4:return sa.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return sa.LineStrip;case 7:return sa.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return sa.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return jl.Add;case 32778:return jl.Subtract;case 32779:return jl.ReverseSubtract;case 32775:return jl.Min;case 32776:return jl.Max;default:return jl.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return en.Zero;case 1:return en.One;case 768:return en.Src;case 769:return en.OneMinusSrc;case 770:return en.SrcAlpha;case 771:return en.OneMinusSrcAlpha;case 772:return en.DstAlpha;case 773:return en.OneMinusDstAlpha;case 774:return en.Dst;case 775:return en.OneMinusDst;case 776:return en.SrcAlphaSaturated;case 32769:return en.Constant;case 32770:return en.OneMinusConstant;case 32771:return en.Constant;case 32772:return en.OneMinusConstant;default:return en.One}}static _GetCompareFunction(e){switch(e){case 0:return Mr.Never;case 1:return Mr.Less;case 2:return Mr.Equal;case 3:return Mr.LessEqual;case 4:return Mr.Greater;case 5:return Mr.NotEqual;case 6:return Mr.GreaterEqual;case 7:return Mr.Always}return Mr.Never}static _GetStencilOpFunction(e){switch(e){case 0:return go.Zero;case 1:return go.Keep;case 2:return go.Replace;case 3:return go.IncrementClamp;case 4:return go.DecrementClamp;case 5:return go.Invert;case 6:return go.IncrementWrap;case 7:return go.DecrementWrap}return go.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case P.BYTE:switch(s){case 1:case 2:return i?ps.Snorm8x2:ps.Sint8x2;case 3:case 4:return i?ps.Snorm8x4:ps.Sint8x4}break;case P.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?ps.Unorm8x2:ps.Uint8x2;case 3:case 4:return i?ps.Unorm8x4:ps.Uint8x4}break;case P.SHORT:switch(s){case 1:case 2:return i?ps.Snorm16x2:ps.Sint16x2;case 3:case 4:return i?ps.Snorm16x4:ps.Sint16x4}break;case P.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?ps.Unorm16x2:ps.Uint16x2;case 3:case 4:return i?ps.Unorm16x4:ps.Uint16x4}break;case P.INT:switch(s){case 1:return ps.Sint32;case 2:return ps.Sint32x2;case 3:return ps.Sint32x3;case 4:return ps.Sint32x4}break;case P.UNSIGNED_INT:switch(s){case 1:return ps.Uint32;case 2:return ps.Uint32x2;case 3:return ps.Uint32x3;case 4:return ps.Uint32x4}break;case P.FLOAT:switch(s){case 1:return ps.Float32;case 2:return ps.Float32x2;case 3:return ps.Float32x3;case 4:return ps.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:hs._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:hs._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[Ls.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,r=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,a=i-1+(s<<1)+(r<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==a&&(this._rasterizationState=a,this._states[Ls.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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:h_[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:h_[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:h_[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:h_[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[Ls.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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[Ls.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthStencilState))}_setVertexState(e){var t,i;const s=this._statesLength;let r=Ls.VertexState;const n=e._pipelineContext,a=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect;let h,c=0;for(let u=0;u0)for(let g=0;g=this._video.HAVE_CURRENT_DATA}dispose(){}}class Pm{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Pm._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?Uh.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){var i,s,r;let n=this.textures[e],a=-1;n?a=(s=(i=n.texture)===null||i===void 0?void 0:i.uniqueId)!==null&&s!==void 0?s:-1:this.textures[e]=n={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(n.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,n.isExternalTexture=gy.IsExternalTexture(t),n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatOrDepthTexture=!1,n.isExternalTexture=!1),n.texture=t;const l=a!==((r=t==null?void 0:t.uniqueId)!==null&&r!==void 0?r:-1);l&&this.updateId++,this.isDirty||(this.isDirty=l)}}Pm._Counter=0;class Mm{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,Hi.CopyDst|Hi.Indirect|Hi.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=Mm._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||i===void 0?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}}Mm._Counter=0;class E_{constructor(){this.values={}}}class Cs{static get Statistics(){return{totalCreated:Cs.NumBindGroupsCreatedTotal,lastFrameCreated:Cs.NumBindGroupsCreatedLastFrame,lookupLastFrame:Cs.NumBindGroupsLookupLastFrame,noLookupLastFrame:Cs.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Cs.NumBindGroupsCreatedLastFrame=Cs._NumBindGroupsCreatedCurrentFrame,Cs.NumBindGroupsLookupLastFrame=Cs._NumBindGroupsLookupCurrentFrame,Cs.NumBindGroupsNoLookupLastFrame=Cs._NumBindGroupsNoLookupCurrentFrame,Cs._NumBindGroupsCreatedCurrentFrame=0,Cs._NumBindGroupsLookupCurrentFrame=0,Cs._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var s,r,n,a,l,h,c,u,d,f;let p,_=Cs._Cache;const g=this.disabled||i.forceBindGroupCreation;if(!g){if(!t.isDirty(i.updateId)&&!i.isDirty)return Cs._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const E of e.shaderProcessingContext.bufferNames){const C=(r=(s=t.buffers[E])===null||s===void 0?void 0:s.uniqueId)!==null&&r!==void 0?r:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}for(const E of e.shaderProcessingContext.samplerNames){const C=(a=(n=i.samplers[E])===null||n===void 0?void 0:n.hashCode)!==null&&a!==void 0?a:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}for(const E of e.shaderProcessingContext.textureNames){const C=(c=(h=(l=i.textures[E])===null||l===void 0?void 0:l.texture)===null||h===void 0?void 0:h.uniqueId)!==null&&c!==void 0?c:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,Cs._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,g||(_.bindGroups=p),Cs.NumBindGroupsCreatedTotal++,Cs._NumBindGroupsCreatedCurrentFrame++;const v=e.bindGroupLayouts[i.textureState];for(let E=0;EV==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=this._cacheSampler.getSampler(B,!1,L.hashCode,B.label)}else G.Error(`Sampler "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.texture||I.storageTexture){const L=i.textures[O];if(L){if(this._engine.dbgSanityChecks&&L.texture===null){G.Error(`Trying to bind a null texture! entry=${JSON.stringify(I)}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const B=L.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!B||I.texture&&!B.view||I.storageTexture&&!B.viewForWriting)){G.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, isReady=${(d=L.texture)===null||d===void 0?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=I.storageTexture?B.viewForWriting:B.view}else G.Error(`Texture "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.externalTexture){const L=i.textures[O];if(L){if(this._engine.dbgSanityChecks&&L.texture===null){G.Error(`Trying to bind a null external texture! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const B=L.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!B){G.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, isReady=${(f=L.texture)===null||f===void 0?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=this._device.importExternalTexture({source:B})}else G.Error(`Texture "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.buffer){const L=t.buffers[O];if(L){const B=L.underlyingResource;S[R].resource.buffer=B,S[R].resource.size=L.capacity}else G.Error(`Can't find buffer "${O}". entry=${JSON.stringify(I)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const b=v[E];p[E]=this._device.createBindGroup({layout:b,entries:S})}return p}}Cs.NumBindGroupsCreatedTotal=0;Cs.NumBindGroupsCreatedLastFrame=0;Cs.NumBindGroupsLookupLastFrame=0;Cs.NumBindGroupsNoLookupLastFrame=0;Cs._Cache=new E_;Cs._NumBindGroupsCreatedCurrentFrame=0;Cs._NumBindGroupsLookupCurrentFrame=0;Cs._NumBindGroupsNoLookupCurrentFrame=0;const RV="clearQuadVertexShader",IV=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), +`));let a=this._compiledShaders[s];if(!a){let h=this._glslang.compileGLSL(n+L0[t].vertex,"vertex"),c=this._glslang.compileGLSL(n+L0[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});a=this._compiledShaders[s]=[u,d]}const l=this._device.createRenderPipeline({layout:Md.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:sa.TriangleStrip,stripIndexFormat:gh.Uint16}});r=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=wc.DontInvertY){const i=t===wc.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 a=this._device.createShaderModule({code:TV}),l=this._device.createShaderModule({code:i===0?EV:SV});r=this._videoCompiledShaders[i]=[a,l]}const n=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:Md.Auto,vertex:{module:r[0],entryPoint:"main"},fragment:{module:r[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:sa.TriangleStrip,stripIndexFormat:gh.Uint16}});s=this._videoPipelines[e][i]=[n,n.getBindGroupLayout(0)]}return s}static GetTextureTypeFromFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.RGB9E5UFloat:case U.RG11B10UFloat:case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC4RUnorm:case U.BC4RSnorm:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:case U.EACRG11Unorm:case U.EACRG11Snorm:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:case U.Stencil8:return 0;case U.R16Uint:case U.R16Sint:case U.RG16Uint:case U.RG16Sint:case U.RGBA16Uint:case U.RGBA16Sint:case U.Depth16Unorm:return 5;case U.R16Float:case U.RG16Float:case U.RGBA16Float:return 2;case U.R32Uint:case U.R32Sint:case U.RG32Uint:case U.RG32Sint:case U.RGBA32Uint:case U.RGBA32Sint:return 7;case U.R32Float:case U.RG32Float:case U.RGBA32Float:case U.Depth32Float:case U.Depth32FloatStencil8:case U.Depth24Plus:case U.Depth24PlusStencil8:return 1}return 0}static _GetBlockInformationFromFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:return{width:1,height:1,length:1};case U.R16Uint:case U.R16Sint:case U.R16Float:case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:return{width:1,height:1,length:2};case U.R32Uint:case U.R32Sint:case U.R32Float:case U.RG16Uint:case U.RG16Sint:case U.RG16Float:case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB9E5UFloat:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.RG11B10UFloat:return{width:1,height:1,length:4};case U.RG32Uint:case U.RG32Sint:case U.RG32Float:case U.RGBA16Uint:case U.RGBA16Sint:case U.RGBA16Float:return{width:1,height:1,length:8};case U.RGBA32Uint:case U.RGBA32Sint:case U.RGBA32Float:return{width:1,height:1,length:16};case U.Stencil8:throw"No fixed size for Stencil8 format!";case U.Depth16Unorm:return{width:1,height:1,length:2};case U.Depth24Plus:throw"No fixed size for Depth24Plus format!";case U.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case U.Depth32Float:return{width:1,height:1,length:4};case U.Depth32FloatStencil8:return{width:1,height:1,length:5};case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case U.BC4RUnorm:case U.BC4RSnorm:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:return{width:4,height:4,length:8};case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACRG11Unorm:case U.EACRG11Snorm:return{width:4,height:4,length:16};case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case U.ASTC12x12Unorm:case U.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}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case U.BC7RGBAUnormSRGB:case U.BC7RGBAUnorm:case U.BC6HRGBFloat:case U.BC6HRGBUFloat:case U.BC5RGSnorm:case U.BC5RGUnorm:case U.BC4RSnorm:case U.BC4RUnorm:case U.BC3RGBAUnormSRGB:case U.BC3RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.BC1RGBAUnorm:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.EACR11Unorm:case U.EACR11Snorm:case U.EACRG11Unorm:case U.EACRG11Snorm:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return U.Depth16Unorm;case 16:return U.Depth24Plus;case 13:return U.Depth24PlusStencil8;case 14:return U.Depth32Float;case 18:return U.Depth32FloatStencil8;case 19:return U.Stencil8;case 36492:return i?U.BC7RGBAUnormSRGB:U.BC7RGBAUnorm;case 36495:return U.BC6HRGBUFloat;case 36494:return U.BC6HRGBFloat;case 33779:return i?U.BC3RGBAUnormSRGB:U.BC3RGBAUnorm;case 33778:return i?U.BC2RGBAUnormSRGB:U.BC2RGBAUnorm;case 33777:case 33776:return i?U.BC1RGBAUnormSRGB:U.BC1RGBAUnorm;case 37808:return i?U.ASTC4x4UnormSRGB:U.ASTC4x4Unorm;case 36196:case 37492:return i?U.ETC2RGB8UnormSRGB:U.ETC2RGB8Unorm;case 37496:return i?U.ETC2RGBA8UnormSRGB:U.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return U.R8Snorm;case 7:return U.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return U.R8Sint;case 9:return U.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA8Sint;default:return U.RGBA8Snorm}case 0:switch(t){case 6:return U.R8Unorm;case 7:return U.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?U.RGBA8UnormSRGB:U.RGBA8Unorm;case 12:return i?U.BGRA8UnormSRGB:U.BGRA8Unorm;case 8:return U.R8Uint;case 9:return U.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return U.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 U.RGBA8Unorm}case 4:switch(t){case 8:return U.R16Sint;case 9:return U.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA16Sint;default:return U.RGBA16Sint}case 5:switch(t){case 8:return U.R16Uint;case 9:return U.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA16Uint;default:return U.RGBA16Uint}case 6:switch(t){case 8:return U.R32Sint;case 9:return U.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA32Sint;default:return U.RGBA32Sint}case 7:switch(t){case 8:return U.R32Uint;case 9:return U.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return U.RGBA32Uint;default:return U.RGBA32Uint}case 1:switch(t){case 6:return U.R32Float;case 7:return U.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return U.RGBA32Float;default:return U.RGBA32Float}case 2:switch(t){case 6:return U.R16Float;case 7:return U.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return U.RGBA16Float;default:return U.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return U.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return U.RG11B10UFloat}case 14:switch(t){case 5:return U.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 U.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 U.RGB10A2Unorm;case 11:return U.RGB10A2UINT;default:return U.RGB10A2Unorm}}return i?U.RGBA8UnormSRGB:U.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case U.R8Unorm:case U.R8Snorm:case U.R8Uint:case U.R8Sint:case U.BC4RUnorm:case U.BC4RSnorm:case U.R16Uint:case U.R16Sint:case U.Depth16Unorm:case U.R16Float:case U.R32Uint:case U.R32Sint:case U.R32Float:case U.Depth32Float:case U.Stencil8:case U.Depth24Plus:case U.EACR11Unorm:case U.EACR11Snorm:return 1;case U.RG8Unorm:case U.RG8Snorm:case U.RG8Uint:case U.RG8Sint:case U.Depth32FloatStencil8:case U.BC5RGUnorm:case U.BC5RGSnorm:case U.RG16Uint:case U.RG16Sint:case U.RG16Float:case U.RG32Uint:case U.RG32Sint:case U.RG32Float:case U.Depth24PlusStencil8:case U.EACRG11Unorm:case U.EACRG11Snorm:return 2;case U.RGB9E5UFloat:case U.RG11B10UFloat:case U.BC6HRGBUFloat:case U.BC6HRGBFloat:case U.ETC2RGB8Unorm:case U.ETC2RGB8UnormSRGB:return 3;case U.RGBA8Unorm:case U.RGBA8UnormSRGB:case U.RGBA8Snorm:case U.RGBA8Uint:case U.RGBA8Sint:case U.BGRA8Unorm:case U.BGRA8UnormSRGB:case U.RGB10A2UINT:case U.RGB10A2Unorm:case U.BC7RGBAUnorm:case U.BC7RGBAUnormSRGB:case U.BC3RGBAUnorm:case U.BC3RGBAUnormSRGB:case U.BC2RGBAUnorm:case U.BC2RGBAUnormSRGB:case U.BC1RGBAUnorm:case U.BC1RGBAUnormSRGB:case U.RGBA16Uint:case U.RGBA16Sint:case U.RGBA16Float:case U.RGBA32Uint:case U.RGBA32Sint:case U.RGBA32Float:case U.ETC2RGB8A1Unorm:case U.ETC2RGB8A1UnormSRGB:case U.ETC2RGBA8Unorm:case U.ETC2RGBA8UnormSRGB:case U.ASTC4x4Unorm:case U.ASTC4x4UnormSRGB:case U.ASTC5x4Unorm:case U.ASTC5x4UnormSRGB:case U.ASTC5x5Unorm:case U.ASTC5x5UnormSRGB:case U.ASTC6x5Unorm:case U.ASTC6x5UnormSRGB:case U.ASTC6x6Unorm:case U.ASTC6x6UnormSRGB:case U.ASTC8x5Unorm:case U.ASTC8x5UnormSRGB:case U.ASTC8x6Unorm:case U.ASTC8x6UnormSRGB:case U.ASTC8x8Unorm:case U.ASTC8x8UnormSRGB:case U.ASTC10x5Unorm:case U.ASTC10x5UnormSRGB:case U.ASTC10x6Unorm:case U.ASTC10x6UnormSRGB:case U.ASTC10x8Unorm:case U.ASTC10x8UnormSRGB:case U.ASTC10x10Unorm:case U.ASTC10x10UnormSRGB:case U.ASTC12x10Unorm:case U.ASTC12x10UnormSRGB:case U.ASTC12x12Unorm:case U.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case U.Stencil8:case U.Depth32FloatStencil8:case U.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case U.Depth32FloatStencil8:case U.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case U.Depth16Unorm:return U.Depth16Unorm;case U.Depth24Plus:return U.Depth24Plus;case U.Depth24PlusStencil8:return U.Depth24Plus;case U.Depth32Float:return U.Depth32Float;case U.Depth32FloatStencil8:return U.Depth32Float}return e}static GetSample(e){return e>1?4:1}copyVideoToTexture(e,t,i,s=!1,r){var n,a,l,h;const c=r===void 0,[u,d]=this._getVideoPipeline(i,s?wc.InvertY:wc.DontInvertY);c&&(r=this._device.createCommandEncoder({})),(a=(n=r).pushDebugGroup)===null||a===void 0||a.call(n,`copy video to texture - invertY=${s}`);const p={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:qi.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:Go.All}),loadOp:ir.Load,storeOp:ba.Store}]},_=r.beginRenderPass(p),g={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},v=this._device.createBindGroup(g);_.setPipeline(u),_.setBindGroup(0,v),_.draw(4,1,0,0),_.end(),(h=(l=r).popDebugGroup)===null||h===void 0||h.call(l),c&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,a=0,l=0,h=1,c=0,u=0,d=0,f=0,p,_){var g,v,E,C,S,b;const R=d!==0,I=p===void 0,[N,O]=this._getPipeline(s,R?Za.InvertYPremultiplyAlphaWithOfst:Za.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});a=Math.max(a,0),I&&(p=this._device.createCommandEncoder({})),(v=(g=p).pushDebugGroup)===null||v===void 0||v.call(g,`internal process texture - invertY=${r} premultiplyAlpha=${n}`);let L;if(Ri._IsHardwareTexture(e)?(L=e.underlyingResource,r&&!n&&h===1&&a===0||(e=void 0)):(L=e,e=void 0),!L)return;R&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,d,f]),0,4*4);const B=e,V=(E=B==null?void 0:B._copyInvertYTempTexture)!==null&&E!==void 0?E:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,p,ls.CopySrc|ls.RenderAttachment|ls.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),Z=(C=B==null?void 0:B._copyInvertYRenderPassDescr)!==null&&C!==void 0?C:{colorAttachments:[{view:V.createView({format:s,dimension:qi.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:ir.Load,storeOp:ba.Store}]},ue=p.beginRenderPass(Z);let oe=R?B==null?void 0:B._copyInvertYBindGroupWithOfst:B==null?void 0:B._copyInvertYBindGroup;if(!oe){const me={layout:O,entries:[{binding:0,resource:L.createView({format:s,dimension:qi.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:a})}]};R&&me.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),oe=this._device.createBindGroup(me)}ue.setPipeline(N),ue.setBindGroup(0,oe),ue.draw(4,1,0,0),ue.end(),p.copyTextureToTexture({texture:V},{texture:L,mipLevel:l,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),B?(B._copyInvertYTempTexture=V,B._copyInvertYRenderPassDescr=Z,R?B._copyInvertYBindGroupWithOfst=oe:B._copyInvertYBindGroup=oe):this._deferredReleaseTextures.push([V,null]),(b=(S=p).popDebugGroup)===null||b===void 0||b.call(S),I&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,s){var r,n,a,l;const h=s===void 0,[c,u]=this._getPipeline(t,Za.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});h&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,"internal copy texture with invertY");const d=s.beginRenderPass(i),f=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});d.setPipeline(c),d.setBindGroup(0,f),d.draw(4,1,0,0),d.end(),(l=(a=s).popDebugGroup)===null||l===void 0||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,a=U.RGBA8Unorm,l=1,h,c=-1,u=0,d){l=Ri.GetSample(l);const f=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:f},_=zo[a]?ls.RenderAttachment:0,g=Ri.IsCompressedFormat(a),v=t?Ri.ComputeNumMipmapLevels(e.width,e.height):1,E=c>=0?c:ls.CopySrc|ls.CopyDst|ls.TextureBinding;u|=t&&!g?ls.CopySrc|_:0,!g&&!n&&(u|=_|ls.CopyDst);const C=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${l}`,size:p,dimension:n?to.E3d:to.E2d,format:a,usage:E|u,sampleCount:l,mipLevelCount:v});return Ri.IsImageBitmap(e)&&(this.updateTexture(e,C,e.width,e.height,f,a,0,0,s,r,0,0),t&&i&&this.generateMipmaps(C,a,v,0,h)),C}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=U.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Ri.GetSample(a);const d=Ri.IsImageBitmapArray(e)?e[0].width:e.width,f=Ri.IsImageBitmapArray(e)?e[0].height:e.height,p=zo[n]?ls.RenderAttachment:0,_=Ri.IsCompressedFormat(n),g=t?Ri.ComputeNumMipmapLevels(d,f):1,v=h>=0?h:ls.CopySrc|ls.CopyDst|ls.TextureBinding;c|=t&&!_?ls.CopySrc|p:0,_||(c|=p|ls.CopyDst);const E=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:to.E2d,format:n,usage:v|c,sampleCount:a,mipLevelCount:g});return Ri.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,E,d,f,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(E,n,g,l)),E}generateCubeMipmaps(e,t,i,s){var r,n,a,l;const h=s===void 0;h&&(s=this._device.createCommandEncoder({})),(n=(r=s).pushDebugGroup)===null||n===void 0||n.call(r,`create cube mipmaps - ${i} levels`);for(let c=0;c<6;++c)this.generateMipmaps(e,t,i,c,s);(l=(a=s).popDebugGroup)===null||l===void 0||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r){var n,a,l,h,c,u,d,f;const p=r===void 0,[_,g]=this._getPipeline(t);s=Math.max(s,0),p&&(r=this._device.createCommandEncoder({})),(a=(n=r).pushDebugGroup)===null||a===void 0||a.call(n,`create mipmaps for face #${s} - ${i} levels`);let v;if(Ri._IsHardwareTexture(e)?(v=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(v=e,e=void 0),!v)return;const E=e;for(let C=1;Cc;)this._device.queue.writeBuffer(n,t+u,i.buffer,a+u,c),u+=c;this._device.queue.writeBuffer(n,t+u,i.buffer,a+u,r-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=wo(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,a=0,l=0,h=null,c=!0,u=!1){const d=a===1?2:a===2?1:0;return new Promise((f,p)=>{e.mapAsync(Yh.Read,l,t).then(()=>{const _=e.getMappedRange(l,t);let g=h;if(u)g===null?g=Fv(a,t,!0,_):g=Fv(a,g.buffer,void 0,_);else if(g===null)switch(d){case 0:g=new Uint8Array(t),g.set(new Uint8Array(_));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_);break;case 2:g=new Float32Array(t/4),g.set(new Float32Array(_));break}else switch(d){case 0:g=new Uint8Array(g.buffer),g.set(new Uint8Array(_));break;case 1:g=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_,h);break;case 2:g=new Float32Array(g.buffer),g.set(new Float32Array(_));break}if(r!==n){d===1&&!u&&(r*=2,n*=2);const v=new Uint8Array(g.buffer);let E=r,C=0;for(let S=1;S{this._engine.isDisposed?f(new Uint8Array):p(_)})})}releaseBuffer(e){return L_._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e1?4:1;return bV[e.samplingMode]+yV[(e._comparisonFunction||514)-512+1]+AV[e.samplingMode]+(((t=e._cachedWrapU)!==null&&t!==void 0?t:1)<<8)+(((i=e._cachedWrapV)!==null&&i!==void 0?i:1)<<10)+(((s=e._cachedWrapR)!==null&&s!==void 0?s:1)<<12)+((e.useMipMaps?1:0)<<14)+(r<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,a;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=ri.Linear,s=ri.Linear,r=ri.Nearest,l||(n=a=0);break;case 3:case 3:i=ri.Linear,s=ri.Linear,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 8:i=ri.Nearest,s=ri.Nearest,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 4:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,l||(n=a=0);break;case 5:i=ri.Nearest,s=ri.Linear,r=ri.Nearest,l||(n=a=0);break;case 6:i=ri.Nearest,s=ri.Linear,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 7:i=ri.Nearest,s=ri.Linear,r=ri.Nearest,n=a=0;break;case 1:case 1:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,n=a=0;break;case 9:i=ri.Linear,s=ri.Nearest,r=ri.Nearest,l||(n=a=0);break;case 10:i=ri.Linear,s=ri.Nearest,l?r=ri.Linear:(r=ri.Nearest,n=a=0);break;case 2:case 2:i=ri.Linear,s=ri.Linear,r=ri.Nearest,n=a=0;break;case 12:i=ri.Linear,s=ri.Nearest,r=ri.Nearest,n=a=0;break;default:i=ri.Nearest,s=ri.Nearest,r=ri.Nearest,n=a=0;break}return t>1&&(n!==0||a!==0)&&r!==ri.Nearest?{magFilter:ri.Linear,minFilter:ri.Linear,mipmapFilter:ri.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:return Nc.Repeat;case 0:return Nc.ClampToEdge;case 2:return Nc.MirrorRepeat}return Nc.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 Object.assign(Object.assign(Object.assign({label:t},s),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?kh.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1})}static GetCompareFunction(e){switch(e){case 519:return Mr.Always;case 514:return Mr.Equal;case 516:return Mr.Greater;case 518:return Mr.GreaterEqual;case 513:return Mr.Less;case 515:return Mr.LessEqual;case 512:return Mr.Never;case 517:return Mr.NotEqual;default:return Mr.Less}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(kh._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=kh.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(kh._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var Ls;(function(o){o[o.StencilReadMask=0]="StencilReadMask",o[o.StencilWriteMask=1]="StencilWriteMask",o[o.DepthBias=2]="DepthBias",o[o.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",o[o.DepthStencilState=4]="DepthStencilState",o[o.MRTAttachments1=5]="MRTAttachments1",o[o.MRTAttachments2=6]="MRTAttachments2",o[o.RasterizationState=7]="RasterizationState",o[o.ColorStates=8]="ColorStates",o[o.ShaderStage=9]="ShaderStage",o[o.TextureStage=10]="TextureStage",o[o.VertexState=11]="VertexState",o[o.NumStates=12]="NumStates"})(Ls||(Ls={}));const h_={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},Ac={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},RV={[P.PositionKind]:!0,[P.NormalKind]:!0,[P.TangentKind]:!0,[P.UVKind]:!0,[P.UV2Kind]:!0,[P.UV3Kind]:!0,[P.UV4Kind]:!0,[P.UV5Kind]:!0,[P.UV6Kind]:!0,[P.ColorKind]:!0,[P.ColorInstanceKind]:!0,[P.MatricesIndicesKind]:!0,[P.MatricesWeightsKind]:!0,[P.MatricesIndicesExtraKind]:!0,[P.MatricesWeightsExtraKind]:!0};class hs{static _IsSignedType(e){switch(e){case P.BYTE:case P.SHORT:case P.INT:case P.FLOAT:return!0;case P.UNSIGNED_BYTE:case P.UNSIGNED_SHORT:case P.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=[U.BGRA8Unorm],this.setColorFormat(U.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(U.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=Ri.GetSample(i),this.disabled){const n=hs._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,i),hs.NumCacheMiss++,hs._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,hs.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return hs.NumCacheHitWithHash++,this._parameter.pipeline;const r=hs._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),hs.NumCacheMiss++,hs._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){hs.NumPipelineCreationLastFrame=hs._NumPipelineCreationCurrentFrame,hs._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,a,l){this._depthWriteEnabled=a,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[Ls.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[Ls.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=zo[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const r=[0,0];let n=0,a=0,l=0;for(let h=0;h=32&&(a=0,n++)}this._mrtFormats.length=l,(this._mrtAttachments1!==r[0]||this._mrtAttachments2!==r[1])&&(this._mrtAttachments1=r[0],this._mrtAttachments2=r[1],this._states[Ls.MRTAttachments1]=r[0],this._states[Ls.MRTAttachments2]=r[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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:zo[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:Ac[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:Ac[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:Ac[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[Ls.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[Ls.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:Ac[i],this._stencilFrontPassOp=s===null?2:Ac[s],this._stencilFrontFailOp=r===null?1:Ac[r],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return sa.TriangleList;case 2:return sa.PointList;case 1:return sa.LineList;case 3:return sa.PointList;case 4:return sa.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return sa.LineStrip;case 7:return sa.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return sa.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return Ql.Add;case 32778:return Ql.Subtract;case 32779:return Ql.ReverseSubtract;case 32775:return Ql.Min;case 32776:return Ql.Max;default:return Ql.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return en.Zero;case 1:return en.One;case 768:return en.Src;case 769:return en.OneMinusSrc;case 770:return en.SrcAlpha;case 771:return en.OneMinusSrcAlpha;case 772:return en.DstAlpha;case 773:return en.OneMinusDstAlpha;case 774:return en.Dst;case 775:return en.OneMinusDst;case 776:return en.SrcAlphaSaturated;case 32769:return en.Constant;case 32770:return en.OneMinusConstant;case 32771:return en.Constant;case 32772:return en.OneMinusConstant;default:return en.One}}static _GetCompareFunction(e){switch(e){case 0:return Mr.Never;case 1:return Mr.Less;case 2:return Mr.Equal;case 3:return Mr.LessEqual;case 4:return Mr.Greater;case 5:return Mr.NotEqual;case 6:return Mr.GreaterEqual;case 7:return Mr.Always}return Mr.Never}static _GetStencilOpFunction(e){switch(e){case 0:return go.Zero;case 1:return go.Keep;case 2:return go.Replace;case 3:return go.IncrementClamp;case 4:return go.DecrementClamp;case 5:return go.Invert;case 6:return go.IncrementWrap;case 7:return go.DecrementWrap}return go.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case P.BYTE:switch(s){case 1:case 2:return i?ps.Snorm8x2:ps.Sint8x2;case 3:case 4:return i?ps.Snorm8x4:ps.Sint8x4}break;case P.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?ps.Unorm8x2:ps.Uint8x2;case 3:case 4:return i?ps.Unorm8x4:ps.Uint8x4}break;case P.SHORT:switch(s){case 1:case 2:return i?ps.Snorm16x2:ps.Sint16x2;case 3:case 4:return i?ps.Snorm16x4:ps.Sint16x4}break;case P.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?ps.Unorm16x2:ps.Uint16x2;case 3:case 4:return i?ps.Unorm16x4:ps.Uint16x4}break;case P.INT:switch(s){case 1:return ps.Sint32;case 2:return ps.Sint32x2;case 3:return ps.Sint32x3;case 4:return ps.Sint32x4}break;case P.UNSIGNED_INT:switch(s){case 1:return ps.Uint32;case 2:return ps.Uint32x2;case 3:return ps.Uint32x3;case 4:return ps.Uint32x4}break;case P.FLOAT:switch(s){case 1:return ps.Float32;case 2:return ps.Float32x2;case 3:return ps.Float32x3;case 4:return ps.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:hs._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:hs._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:hs._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[Ls.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,r=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,a=i-1+(s<<1)+(r<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==a&&(this._rasterizationState=a,this._states[Ls.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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:h_[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:h_[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:h_[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:h_[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[Ls.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.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[Ls.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,Ls.DepthStencilState))}_setVertexState(e){var t,i;const s=this._statesLength;let r=Ls.VertexState;const n=e._pipelineContext,a=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect;let h,c=0;for(let u=0;u0)for(let g=0;g=this._video.HAVE_CURRENT_DATA}dispose(){}}class Pm{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Pm._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?kh.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){var i,s,r;let n=this.textures[e],a=-1;n?a=(s=(i=n.texture)===null||i===void 0?void 0:i.uniqueId)!==null&&s!==void 0?s:-1:this.textures[e]=n={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(n.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,n.isExternalTexture=xy.IsExternalTexture(t),n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatOrDepthTexture=!1,n.isExternalTexture=!1),n.texture=t;const l=a!==((r=t==null?void 0:t.uniqueId)!==null&&r!==void 0?r:-1);l&&this.updateId++,this.isDirty||(this.isDirty=l)}}Pm._Counter=0;class Mm{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,Hi.CopyDst|Hi.Indirect|Hi.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=Mm._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||i===void 0?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}}Mm._Counter=0;class E_{constructor(){this.values={}}}class bs{static get Statistics(){return{totalCreated:bs.NumBindGroupsCreatedTotal,lastFrameCreated:bs.NumBindGroupsCreatedLastFrame,lookupLastFrame:bs.NumBindGroupsLookupLastFrame,noLookupLastFrame:bs.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){bs.NumBindGroupsCreatedLastFrame=bs._NumBindGroupsCreatedCurrentFrame,bs.NumBindGroupsLookupLastFrame=bs._NumBindGroupsLookupCurrentFrame,bs.NumBindGroupsNoLookupLastFrame=bs._NumBindGroupsNoLookupCurrentFrame,bs._NumBindGroupsCreatedCurrentFrame=0,bs._NumBindGroupsLookupCurrentFrame=0,bs._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var s,r,n,a,l,h,c,u,d,f;let p,_=bs._Cache;const g=this.disabled||i.forceBindGroupCreation;if(!g){if(!t.isDirty(i.updateId)&&!i.isDirty)return bs._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const E of e.shaderProcessingContext.bufferNames){const C=(r=(s=t.buffers[E])===null||s===void 0?void 0:s.uniqueId)!==null&&r!==void 0?r:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}for(const E of e.shaderProcessingContext.samplerNames){const C=(a=(n=i.samplers[E])===null||n===void 0?void 0:n.hashCode)!==null&&a!==void 0?a:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}for(const E of e.shaderProcessingContext.textureNames){const C=(c=(h=(l=i.textures[E])===null||l===void 0?void 0:l.texture)===null||h===void 0?void 0:h.uniqueId)!==null&&c!==void 0?c:0;let S=_.values[C];S||(S=new E_,_.values[C]=S),_=S}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,bs._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,g||(_.bindGroups=p),bs.NumBindGroupsCreatedTotal++,bs._NumBindGroupsCreatedCurrentFrame++;const v=e.bindGroupLayouts[i.textureState];for(let E=0;EV==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=this._cacheSampler.getSampler(B,!1,L.hashCode,B.label)}else G.Error(`Sampler "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.texture||I.storageTexture){const L=i.textures[O];if(L){if(this._engine.dbgSanityChecks&&L.texture===null){G.Error(`Trying to bind a null texture! entry=${JSON.stringify(I)}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const B=L.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!B||I.texture&&!B.view||I.storageTexture&&!B.viewForWriting)){G.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, isReady=${(d=L.texture)===null||d===void 0?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=I.storageTexture?B.viewForWriting:B.view}else G.Error(`Texture "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.externalTexture){const L=i.textures[O];if(L){if(this._engine.dbgSanityChecks&&L.texture===null){G.Error(`Trying to bind a null external texture! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const B=L.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!B){G.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(I)}, name=${O}, bindingInfo=${JSON.stringify(L,(V,Z)=>V==="texture"?"":Z)}, isReady=${(f=L.texture)===null||f===void 0?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}S[R].resource=this._device.importExternalTexture({source:B})}else G.Error(`Texture "${O}" could not be bound. entry=${JSON.stringify(I)}, materialContext=${JSON.stringify(i,(B,V)=>B==="texture"||B==="sampler"?"":V)}`,50)}else if(I.buffer){const L=t.buffers[O];if(L){const B=L.underlyingResource;S[R].resource.buffer=B,S[R].resource.size=L.capacity}else G.Error(`Can't find buffer "${O}". entry=${JSON.stringify(I)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const b=v[E];p[E]=this._device.createBindGroup({layout:b,entries:S})}return p}}bs.NumBindGroupsCreatedTotal=0;bs.NumBindGroupsCreatedLastFrame=0;bs.NumBindGroupsLookupLastFrame=0;bs.NumBindGroupsNoLookupLastFrame=0;bs._Cache=new E_;bs._NumBindGroupsCreatedCurrentFrame=0;bs._NumBindGroupsLookupCurrentFrame=0;bs._NumBindGroupsNoLookupCurrentFrame=0;const MV="clearQuadVertexShader",DV=`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)}; @@ -3274,9 +3274,9 @@ void main(void) { gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); #define CUSTOM_VERTEX_MAIN_END } -`;ne.ShadersStore[RV]=IV;const PV="clearQuadPixelShader",MV=`uniform vec4 color;void main() {gl_FragColor=color;} -`;ne.ShadersStore[PV]=MV;class DV{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 Sl(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){var n,a;let l,h=null,c;const u=!!this._engine._currentRenderTarget;if(e)l=e;else{let E=0;this._keyTemp.length=0;for(let S=0;S1?2**36:0)+C*2**37,c=this._keyTemp.join("_"),h=this._bundleCache[c],h)return h;l=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ri.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Ri.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 d=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),f=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),f.uniformBuffer.update();const p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=f.uniformBuffer.getBuffer(),g=_.uniqueId+"-"+p.uniqueId;let v=this._bindGroups[g];if(!v){const E=f.bindGroupLayouts[0];v=this._bindGroups[g]=[],v.push(this._device.createBindGroup({layout:E[0],entries:[]})),Ma._SimplifiedKnownBindings||v.push(this._device.createBindGroup({layout:E[1],entries:[]})),v.push(this._device.createBindGroup({layout:E[Ma._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}l.setPipeline(d);for(let E=0;E{const s=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,s},s=>{if(this._engine.isDisposed)return null;throw s})}async readValue(e=0){const t=this._getBuffer(e,1);return t===null?null:t.mapAsync(Xh.Read).then(()=>{const i=new BigUint64Array(t.getMappedRange()),s=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},i=>{if(this._engine.isDisposed)return 0;throw i})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);return t===null?null:t.mapAsync(Xh.Read).then(()=>{const i=new BigUint64Array(t.getMappedRange()),s=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},i=>{if(this._engine.isDisposed)return 0;throw i})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)===null||e===void 0||e.dispose()}}class NV{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new vy(e,s,w_.Timestamp,t,i,!0,r)}start(e){var t;(t=e.writeTimestamp)===null||t===void 0||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)===null||t===void 0||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 wV{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=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;(e=this._querySet)===null||e===void 0||e.dispose(),this._availableIndices.length=0}}class ra{async initTwgsl(e){if(!ra._twgsl)return e=e||{},e=Object.assign(Object.assign({},ra._TWgslDefaultOptions),e),e.twgsl?(ra._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await fe.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(ra._twgsl=await self.twgsl(fe.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=ra._twgsl.convertSpirV2WGSL(e,ra.DisableUniformityAnalysis||t);return ra.ShowWGSLShaderCode&&(G.Log(i),G.Log("***********************************************")),ra.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); -`+i:i}}ra._TWgslDefaultOptions={jsPath:`${fe._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${fe._DefaultCdnUrl}/twgsl/twgsl.wasm`};ra.ShowWGSLShaderCode=!1;ra.DisableUniformityAnalysis=!1;ra._twgsl=null;class FV{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 LV="postprocessVertexShader",BV=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); +`;ne.ShadersStore[MV]=DV;const OV="clearQuadPixelShader",NV=`uniform vec4 color;void main() {gl_FragColor=color;} +`;ne.ShadersStore[OV]=NV;class wV{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 Sl(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){var n,a;let l,h=null,c;const u=!!this._engine._currentRenderTarget;if(e)l=e;else{let E=0;this._keyTemp.length=0;for(let S=0;S1?2**36:0)+C*2**37,c=this._keyTemp.join("_"),h=this._bundleCache[c],h)return h;l=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ri.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Ri.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 d=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),f=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),f.uniformBuffer.update();const p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=f.uniformBuffer.getBuffer(),g=_.uniqueId+"-"+p.uniqueId;let v=this._bindGroups[g];if(!v){const E=f.bindGroupLayouts[0];v=this._bindGroups[g]=[],v.push(this._device.createBindGroup({layout:E[0],entries:[]})),Ma._SimplifiedKnownBindings||v.push(this._device.createBindGroup({layout:E[1],entries:[]})),v.push(this._device.createBindGroup({layout:E[Ma._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}l.setPipeline(d);for(let E=0;E{const s=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,s},s=>{if(this._engine.isDisposed)return null;throw s})}async readValue(e=0){const t=this._getBuffer(e,1);return t===null?null:t.mapAsync(Yh.Read).then(()=>{const i=new BigUint64Array(t.getMappedRange()),s=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},i=>{if(this._engine.isDisposed)return 0;throw i})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);return t===null?null:t.mapAsync(Yh.Read).then(()=>{const i=new BigUint64Array(t.getMappedRange()),s=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},i=>{if(this._engine.isDisposed)return 0;throw i})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)===null||e===void 0||e.dispose()}}class LV{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new Ty(e,s,w_.Timestamp,t,i,!0,r)}start(e){var t;(t=e.writeTimestamp)===null||t===void 0||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)===null||t===void 0||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 BV{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=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;(e=this._querySet)===null||e===void 0||e.dispose(),this._availableIndices.length=0}}class ra{async initTwgsl(e){if(!ra._twgsl)return e=e||{},e=Object.assign(Object.assign({},ra._TWgslDefaultOptions),e),e.twgsl?(ra._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await fe.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(ra._twgsl=await self.twgsl(fe.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=ra._twgsl.convertSpirV2WGSL(e,ra.DisableUniformityAnalysis||t);return ra.ShowWGSLShaderCode&&(G.Log(i),G.Log("***********************************************")),ra.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); +`+i:i}}ra._TWgslDefaultOptions={jsPath:`${fe._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${fe._DefaultCdnUrl}/twgsl/twgsl.wasm`};ra.ShowWGSLShaderCode=!1;ra.DisableUniformityAnalysis=!1;ra._twgsl=null;class VV{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 UV="postprocessVertexShader",kV=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { @@ -3284,19 +3284,19 @@ fn main(input : VertexInputs)->FragmentInputs { vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END } -`;ne.ShadersStoreWGSL[LV]=BV;const F0={label:"TextureView_SwapChain_ResolveTarget",dimension:to.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},L0={label:"TextureView_SwapChain",dimension:to.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},c_="/* disable_uniformity_analysis */",VV=new Ze;class Pt extends re{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 G.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 Ix:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Pt(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){var i,s;if(super(null,(i=t.antialias)!==null&&i!==void 0?i:!0,t),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=(s=t.enableGPUDebugMarkers)!==null&&s!==void 0?s:!1,G.Log(`Babylon.js v${re.Version} - ${this.description} engine`),!navigator.gpu){G.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(e),this._shaderProcessor=new R2,this._shaderProcessorWGSL=new hV}initAsync(e,t){var i;return this._initGlslang(e??((i=this._options)===null||i===void 0?void 0:i.glslangOptions)).then(s=>{var r;return this._glslang=s,this._tintWASM=Pt.UseTWGSL?new ra:null,this._tintWASM?this._tintWASM.initTwgsl(t??((r=this._options)===null||r===void 0?void 0:r.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options),n=>{throw G.Error("Can not initialize twgsl!"),G.Error(n),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},s=>{throw G.Error("Can not initialize glslang!"),G.Error(s),Error("WebGPU initializations stopped.")}).then(s=>{var r,n,a;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(r=this._adapter.features)===null||r===void 0||r.forEach(c=>this._adapterSupportedExtensions.push(c)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(c=>{this._adapterInfo=c});const l=(n=this._options.deviceDescriptor)!==null&&n!==void 0?n:{},h=(a=l==null?void 0:l.requiredFeatures)!==null&&a!==void 0?a:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(h){const c=h,u=[];for(const d of c)this._adapterSupportedExtensions.indexOf(d)!==-1&&u.push(d);l.requiredFeatures=u}if(this._options.setMaximumLimits&&!l.requiredLimits){l.requiredLimits={};for(const c in this._adapterSupportedLimits)l.requiredLimits[c]=this._adapterSupportedLimits[c]}return this._adapter.requestDevice(l)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var r,n;this._device=s,this._deviceEnabledExtensions=[],(r=this._device.features)===null||r===void 0||r.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let a=-1;this._device.addEventListener("uncapturederror",l=>{++a{this._isDisposed||(this._contextWasLost=!0,G.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},s=>{G.Error("Could not retrieve a WebGPU device."),G.Error(s)}).then(()=>{this._bufferManager=new L_(this,this._device),this._textureHelper=new Ri(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Uh(this._device),this._cacheBindGroups=new Cs(this._device,this._cacheSampler,this),this._timestampQuery=new OV(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new wV(this,this._device,this._bufferManager):void 0,this._bundleList=new Yx(this._device),this._snapshotRendering=new FV(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Hi.Uniform|Hi.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Hi.Uniform|Hi.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,G.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 P(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new Sl(this._device,this._emptyVertexBuffer),this._depthCullingState=new AV(this._cacheRenderPipeline),this._stencilStateComposer=new yV(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 DV(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=>{var r;G.Error("Can not create WebGPU Device and/or context."),G.Error(s),(r=console==null?void 0:console.trace)===null||r===void 0||r.call(console)})}_initGlslang(e){return e=e||{},e=Object.assign(Object.assign({},Pt._GLSLslangDefaultOptions),e),e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?fe.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(fe.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(Tl.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Tl.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(Tl.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._caps.parallelShaderCompile=null,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,forceVertexBufferStrideMultiple4Bytes:!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 T_],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:to.E2d,format:this._options.swapChainFormat,usage:ls.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(r),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:to.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ze(0,0,0,1),loadOp:ir.Clear,storeOp:ba.Store}]}else t=[{view:void 0,clearValue:new Ze(0,0,0,1),loadOp:ir.Clear,storeOp:ba.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?U.Depth24PlusStencil8:U.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:to.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ls.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:to.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:ir.Clear,depthStoreOp:ba.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?ir.Clear:void 0,stencilStoreOp:this.isStencilEnable?ba.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ls.RenderAttachment|ls.CopySrc,alphaMode:this.premultipliedAlpha?F_.Premultiplied:F_.Opaque})}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return G.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 Mx:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Pt(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){var i,s;if(super(null,(i=t.antialias)!==null&&i!==void 0?i:!0,t),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=(s=t.enableGPUDebugMarkers)!==null&&s!==void 0?s:!1,G.Log(`Babylon.js v${re.Version} - ${this.description} engine`),!navigator.gpu){G.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(e),this._shaderProcessor=new M2,this._shaderProcessorWGSL=new dV}initAsync(e,t){var i;return this._initGlslang(e??((i=this._options)===null||i===void 0?void 0:i.glslangOptions)).then(s=>{var r;return this._glslang=s,this._tintWASM=Pt.UseTWGSL?new ra:null,this._tintWASM?this._tintWASM.initTwgsl(t??((r=this._options)===null||r===void 0?void 0:r.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options),n=>{throw G.Error("Can not initialize twgsl!"),G.Error(n),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},s=>{throw G.Error("Can not initialize glslang!"),G.Error(s),Error("WebGPU initializations stopped.")}).then(s=>{var r,n,a;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(r=this._adapter.features)===null||r===void 0||r.forEach(c=>this._adapterSupportedExtensions.push(c)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(c=>{this._adapterInfo=c});const l=(n=this._options.deviceDescriptor)!==null&&n!==void 0?n:{},h=(a=l==null?void 0:l.requiredFeatures)!==null&&a!==void 0?a:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(h){const c=h,u=[];for(const d of c)this._adapterSupportedExtensions.indexOf(d)!==-1&&u.push(d);l.requiredFeatures=u}if(this._options.setMaximumLimits&&!l.requiredLimits){l.requiredLimits={};for(const c in this._adapterSupportedLimits)l.requiredLimits[c]=this._adapterSupportedLimits[c]}return this._adapter.requestDevice(l)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var r,n;this._device=s,this._deviceEnabledExtensions=[],(r=this._device.features)===null||r===void 0||r.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let a=-1;this._device.addEventListener("uncapturederror",l=>{++a{this._isDisposed||(this._contextWasLost=!0,G.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},s=>{G.Error("Could not retrieve a WebGPU device."),G.Error(s)}).then(()=>{this._bufferManager=new L_(this,this._device),this._textureHelper=new Ri(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new kh(this._device),this._cacheBindGroups=new bs(this._device,this._cacheSampler,this),this._timestampQuery=new FV(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new BV(this,this._device,this._bufferManager):void 0,this._bundleList=new Kx(this._device),this._snapshotRendering=new VV(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Hi.Uniform|Hi.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Hi.Uniform|Hi.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,G.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 P(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new Sl(this._device,this._emptyVertexBuffer),this._depthCullingState=new PV(this._cacheRenderPipeline),this._stencilStateComposer=new IV(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 wV(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=>{var r;G.Error("Can not create WebGPU Device and/or context."),G.Error(s),(r=console==null?void 0:console.trace)===null||r===void 0||r.call(console)})}_initGlslang(e){return e=e||{},e=Object.assign(Object.assign({},Pt._GLSLslangDefaultOptions),e),e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?fe.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(fe.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(Tl.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(Tl.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Tl.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(Tl.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._caps.parallelShaderCompile=null,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,forceVertexBufferStrideMultiple4Bytes:!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 T_],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:to.E2d,format:this._options.swapChainFormat,usage:ls.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(r),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:to.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ze(0,0,0,1),loadOp:ir.Clear,storeOp:ba.Store}]}else t=[{view:void 0,clearValue:new Ze(0,0,0,1),loadOp:ir.Clear,storeOp:ba.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?U.Depth24PlusStencil8:U.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:to.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ls.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:to.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:ir.Clear,depthStoreOp:ba.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?ir.Clear:void 0,stencilStoreOp:this.isStencilEnable?ba.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ls.RenderAttachment|ls.CopySrc,alphaMode:this.premultipliedAlpha?F_.Premultiplied:F_.Opaque})}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count=0,r=t.indexOf(c_)>=0,n=i===is.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===is.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(c_)>=0,n=t.indexOf(c_)>=0,a=`#version 450 -`,l=s===is.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),h=s===is.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):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 Hh(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new b2(e,this)}createMaterialContext(){return new Pm}createDrawContext(){return new Mm(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,a,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(G.Log(["defines",l]),G.Log(t),G.Log(i),G.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;r0,h._cachedWrapU=0,h._cachedWrapV=0,h._useSRGBBuffer=l.useSRGBBuffer,h.label=l.label,this._internalTexturesCache.push(h),i||this._textureHelper.createGPUTextureForInternalTexture(h,c,u,d||1,l.creationFlags),h}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,s,r,n,a,(g,v,E,C,S,b,R,I)=>{var N;const O=C;if(g.baseWidth=O.width,g.baseHeight=O.height,g.width=O.width,g.height=O.height,g.format=g.format!==-1?g.format:c??5,g.type=g.type!==-1?g.type:0,I(g.width,g.height,O,v,g,()=>{}),!((N=g._hardwareTexture)===null||N===void 0)&&N.underlyingResource)!b&&!R&&this._generateMipmaps(g,this._uploadEncoder);else{const L=this._textureHelper.createGPUTextureForInternalTexture(g,O.width,O.height,void 0,p);Ri.IsImageBitmap(O)&&(this._textureHelper.updateTexture(O,g,O.width,O.height,g.depth,L.format,0,0,S,!1,0,0),!b&&!R&&this._generateMipmaps(g,this._uploadEncoder))}E&&E.removePendingData(g),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>!1,l,h,c,u,d,f,_)}wrapWebGPUTexture(e){const t=new T_(e),i=new Ti(this,Vt.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===void 0)&&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+us.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;r0;for(const r in e){const n=e[r],a=i[r],l=a.group,h=a.binding,c=n.type,u=n.object;let d=n.indexInGroupEntries,f=this._bindGroupEntries[l];switch(f||(f=this._bindGroupEntries[l]=[]),c){case ns.Sampler:{const p=u;d!==void 0&&s?f[d].resource=this._cacheSampler.getSampler(p):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._cacheSampler.getSampler(p)}));break}case ns.Texture:case ns.TextureWithoutSampler:{const p=u,_=p._texture._hardwareTexture;d!==void 0&&s?(c===ns.Texture&&(f[d++].resource=this._cacheSampler.getSampler(p._texture)),f[d].resource=_.view):(n.indexInGroupEntries=f.length,c===ns.Texture&&f.push({binding:h-1,resource:this._cacheSampler.getSampler(p._texture)}),f.push({binding:h,resource:_.view}));break}case ns.StorageTexture:{const p=u,_=p._texture._hardwareTexture;_.textureAdditionalUsages&ls.StorageBinding||G.Error(`computeDispatch: The texture (name=${p.name}, uniqueId=${p.uniqueId}) is not a storage texture!`,50),d!==void 0&&s?f[d].resource=_.viewForWriting:(n.indexInGroupEntries=f.length,f.push({binding:h,resource:_.viewForWriting}));break}case ns.ExternalTexture:{const _=u.underlyingResource;d!==void 0&&s?f[d].resource=this._device.importExternalTexture({source:_}):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._device.importExternalTexture({source:_})}));break}case ns.UniformBuffer:case ns.StorageBuffer:{const _=(c===ns.UniformBuffer,u).getBuffer(),g=_.underlyingResource;d!==void 0&&s?(f[d].resource.buffer=g,f[d].resource.size=_.capacity):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:{buffer:g,offset:0,size:_.capacity}}));break}}}for(let r=0;r0&&c.dispatchWorkgroups(i,s,r),c.end(),a&&(this._timestampQuery.endPass(this._timestampIndex,a),this._timestampIndex+=2)};Pt.prototype.releaseComputeEffects=function(){for(const o in this._compiledComputeEffects){const e=this._compiledComputeEffects[o].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Pt.prototype._prepareComputePipelineContext=function(o,e,t,i,s){const r=o;this.dbgShowShaderCode&&(G.Log(i),G.Log(e)),r.sources={compute:e,rawCompute:t},r.stage=this._createComputePipelineStageDescriptor(e,i,s)};Pt.prototype._releaseComputeEffect=function(o){this._compiledComputeEffects[o._key]&&(delete this._compiledComputeEffects[o._key],this._deleteComputePipelineContext(o.getPipelineContext()))};Pt.prototype._rebuildComputeEffects=function(){for(const o in this._compiledComputeEffects){const e=this._compiledComputeEffects[o];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Pt.prototype._deleteComputePipelineContext=function(o){o&&o.dispose()};Pt.prototype._createComputePipelineStageDescriptor=function(o,e,t){return e?e="//"+e.split(` +`,l=s===is.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),h=s===is.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):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 Xh(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new R2(e,this)}createMaterialContext(){return new Pm}createDrawContext(){return new Mm(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,a,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(G.Log(["defines",l]),G.Log(t),G.Log(i),G.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;r0,h._cachedWrapU=0,h._cachedWrapV=0,h._useSRGBBuffer=l.useSRGBBuffer,h.label=l.label,this._internalTexturesCache.push(h),i||this._textureHelper.createGPUTextureForInternalTexture(h,c,u,d||1,l.creationFlags),h}createTexture(e,t,i,s,r=3,n=null,a=null,l=null,h=null,c=null,u=null,d,f,p,_){return this._createTextureBase(e,t,i,s,r,n,a,(g,v,E,C,S,b,R,I)=>{var N;const O=C;if(g.baseWidth=O.width,g.baseHeight=O.height,g.width=O.width,g.height=O.height,g.format=g.format!==-1?g.format:c??5,g.type=g.type!==-1?g.type:0,I(g.width,g.height,O,v,g,()=>{}),!((N=g._hardwareTexture)===null||N===void 0)&&N.underlyingResource)!b&&!R&&this._generateMipmaps(g,this._uploadEncoder);else{const L=this._textureHelper.createGPUTextureForInternalTexture(g,O.width,O.height,void 0,p);Ri.IsImageBitmap(O)&&(this._textureHelper.updateTexture(O,g,O.width,O.height,g.depth,L.format,0,0,S,!1,0,0),!b&&!R&&this._generateMipmaps(g,this._uploadEncoder))}E&&E.removePendingData(g),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>!1,l,h,c,u,d,f,_)}wrapWebGPUTexture(e){const t=new T_(e),i=new Ti(this,Ut.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===void 0)&&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+us.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;r0;for(const r in e){const n=e[r],a=i[r],l=a.group,h=a.binding,c=n.type,u=n.object;let d=n.indexInGroupEntries,f=this._bindGroupEntries[l];switch(f||(f=this._bindGroupEntries[l]=[]),c){case ns.Sampler:{const p=u;d!==void 0&&s?f[d].resource=this._cacheSampler.getSampler(p):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._cacheSampler.getSampler(p)}));break}case ns.Texture:case ns.TextureWithoutSampler:{const p=u,_=p._texture._hardwareTexture;d!==void 0&&s?(c===ns.Texture&&(f[d++].resource=this._cacheSampler.getSampler(p._texture)),f[d].resource=_.view):(n.indexInGroupEntries=f.length,c===ns.Texture&&f.push({binding:h-1,resource:this._cacheSampler.getSampler(p._texture)}),f.push({binding:h,resource:_.view}));break}case ns.StorageTexture:{const p=u,_=p._texture._hardwareTexture;_.textureAdditionalUsages&ls.StorageBinding||G.Error(`computeDispatch: The texture (name=${p.name}, uniqueId=${p.uniqueId}) is not a storage texture!`,50),d!==void 0&&s?f[d].resource=_.viewForWriting:(n.indexInGroupEntries=f.length,f.push({binding:h,resource:_.viewForWriting}));break}case ns.ExternalTexture:{const _=u.underlyingResource;d!==void 0&&s?f[d].resource=this._device.importExternalTexture({source:_}):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._device.importExternalTexture({source:_})}));break}case ns.UniformBuffer:case ns.StorageBuffer:{const _=(c===ns.UniformBuffer,u).getBuffer(),g=_.underlyingResource;d!==void 0&&s?(f[d].resource.buffer=g,f[d].resource.size=_.capacity):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:{buffer:g,offset:0,size:_.capacity}}));break}}}for(let r=0;r0&&c.dispatchWorkgroups(i,s,r),c.end(),a&&(this._timestampQuery.endPass(this._timestampIndex,a),this._timestampIndex+=2)};Pt.prototype.releaseComputeEffects=function(){for(const o in this._compiledComputeEffects){const e=this._compiledComputeEffects[o].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Pt.prototype._prepareComputePipelineContext=function(o,e,t,i,s){const r=o;this.dbgShowShaderCode&&(G.Log(i),G.Log(e)),r.sources={compute:e,rawCompute:t},r.stage=this._createComputePipelineStageDescriptor(e,i,s)};Pt.prototype._releaseComputeEffect=function(o){this._compiledComputeEffects[o._key]&&(delete this._compiledComputeEffects[o._key],this._deleteComputePipelineContext(o.getPipelineContext()))};Pt.prototype._rebuildComputeEffects=function(){for(const o in this._compiledComputeEffects){const e=this._compiledComputeEffects[o];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Pt.prototype._deleteComputePipelineContext=function(o){o&&o.dispose()};Pt.prototype._createComputePipelineStageDescriptor=function(o,e,t){return e?e="//"+e.split(` `).join(` //`)+` -`:e="",{module:this._device.createShaderModule({code:e+o}),entryPoint:t}};Pt.prototype._createDepthStencilCubeTexture=function(o,e){const t=new Ti(this,Vt.DepthStencil);t.isCube=!0;const i=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},e);return t.format=i.generateStencil?13:14,this._setupDepthStencilTexture(t,o,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t),this._internalTexturesCache.push(t),t};Pt.prototype.createCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(o,e,t,!!i,s,r,n,a,l,h,c,u,null,(f,p)=>{const _=p,g=_[0].width,v=g;this._setCubeMapTextureParams(f,!i),f.format=n??-1;const E=this._textureHelper.createGPUTextureForInternalTexture(f,g,v);this._textureHelper.updateCubeTextures(_,E.underlyingResource,g,v,E.format,!1,!1,0,0),i||this._generateMipmaps(f,this._uploadEncoder),f.isReady=!0,f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),s&&s()},!!d)};Pt.prototype._setCubeMapTextureParams=function(o,e,t){o.samplingMode=e?3:2,o._cachedWrapU=0,o._cachedWrapV=0,t&&(o._maxLodLevel=t)};Pt.prototype._debugPushGroup=function(o,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(o):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(o):this._pendingDebugCommands.push(["push",o]))};Pt.prototype._debugPopGroup=function(o){this._options.enableGPUDebugMarkers&&(o===0||o===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Pt.prototype._debugInsertMarker=function(o,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(o):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(o):this._pendingDebugCommands.push(["insert",o]))};Pt.prototype._debugFlushPendingCommands=function(){for(let o=0;o{e==null||e.removePendingData(d),h&&_&&h(_.status+" "+_.statusText,g)},p=_=>{const g=d.width,v=n(_);if(!v)return;const E=[0,2,4,1,3,5];if(a){const C=i===4,S=a(v),b=d._hardwareTexture,R=[0,1,2,3,4,5];for(let I=0;I>I,O=[];for(let L=0;L<6;L++){let B=S[I][R[L]];C&&(B=ap(B,N,N,s)),O.push(new Uint8Array(B.buffer,B.byteOffset,B.byteLength))}this._textureHelper.updateCubeTextures(O,b.underlyingResource,N,N,b.format,u,!1,0,0)}}else{const C=[];for(let S=0;S<6;S++)C.push(v[E[S]]);this.updateRawCubeTexture(d,C,i,s,u)}d.isReady=!0,e==null||e.removePendingData(d),l&&l()};return this._loadFile(o,_=>{p(_)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};Pt.prototype.createRawTexture3D=function(o,e,t,i,s,r,n,a,l=null,h=0,c=0){const u=Vt.Raw3D,d=new Ti(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=a,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=o),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,c),this.updateRawTexture3D(d,o,s,n,l,h),this._internalTexturesCache.push(d),d};Pt.prototype.updateRawTexture3D=function(o,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.invertY=i,o._compression=s),e){const n=o._hardwareTexture;t===4&&(e=ap(e,o.width,o.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,o,o.width,o.height,o.depth,n.format,0,0,i,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o,this._uploadEncoder)}o.isReady=!0};Pt.prototype.createRawTexture2DArray=function(o,e,t,i,s,r,n,a,l=null,h=0,c=0){const u=Vt.Raw2DArray,d=new Ti(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=a,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=o),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,c),this.updateRawTexture2DArray(d,o,s,n,l,h),this._internalTexturesCache.push(d),d};Pt.prototype.updateRawTexture2DArray=function(o,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.invertY=i,o._compression=s),e){const n=o._hardwareTexture;t===4&&(e=ap(e,o.width,o.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,o,o.width,o.height,o.depth,n.format,0,0,i,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o,this._uploadEncoder)}o.isReady=!0};function ap(o,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;n0,o.depth=l,o.isReady=!0,o.samples=r,o.generateMipMaps=!1,o.samplingMode=i?2:1,o.type=1,o._comparisonFunction=s,o._cachedWrapU=0,o._cachedWrapV=0};Pt.prototype.updateRenderTargetTextureSampleCount=function(o,e){return!o||!o.texture||o.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(o.texture,e),o._depthStencilTexture&&(this._textureHelper.createMSAATexture(o._depthStencilTexture,e),o._depthStencilTexture.samples=e),o._samples=e,o.texture.samples=e),e};Pt.prototype.createRenderTargetCubeTexture=function(o,e){var t;const i=this._createHardwareRenderTargetWrapper(!1,!0,o),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},e);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=(t=s.label)!==null&&t!==void 0?t:"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new Ti(this,Vt.RenderTarget);return r.width=o,r.height=o,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,s.samplingMode===void 0||s.samplingMode===2||s.samplingMode===2||s.samplingMode===3||s.samplingMode===3||s.samplingMode===5||s.samplingMode===6||s.samplingMode===7||s.samplingMode===11,i._generateStencilBuffer,i.samples),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i};ji.prototype.setTextureSampler=function(o,e){this._engine.setTextureSampler(o,e)};Pt.prototype.setTextureSampler=function(o,e){var t;(t=this._currentMaterialContext)===null||t===void 0||t.setSampler(o,e)};ji.prototype.setStorageBuffer=function(o,e){this._engine.setStorageBuffer(o,e)};Pt.prototype.createStorageBuffer=function(o,e,t){return this._createBuffer(o,e|32,t)};Pt.prototype.updateStorageBuffer=function(o,e,t,i){const s=o;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)};Pt.prototype.readFromStorageBuffer=function(o,e,t,i,s){t=t||o.capacity;const r=this._bufferManager.createRawBuffer(t,Hi.MapRead|Hi.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(o.underlyingResource,e??0,r,0,t),new Promise((n,a)=>{const l=()=>{r.mapAsync(Xh.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):a(h)})};s?(this.flushFramebuffer(),l()):this.onEndFrameObservable.addOnce(()=>{l()})})};Pt.prototype.setStorageBuffer=function(o,e){var t,i;(t=this._currentDrawContext)===null||t===void 0||t.setBuffer(o,(i=e==null?void 0:e.getBuffer())!==null&&i!==void 0?i:null)};Pt.prototype.createUniformBuffer=function(o,e){let t;return o instanceof Array?t=new Float32Array(o):t=o,this._bufferManager.createBuffer(t,Hi.Uniform|Hi.CopyDst,e)};Pt.prototype.createDynamicUniformBuffer=function(o,e){return this.createUniformBuffer(o,e)};Pt.prototype.updateUniformBuffer=function(o,e,t,i){t===void 0&&(t=0);const s=o;let r;i===void 0?(e instanceof Float32Array?r=e:r=new Float32Array(e),i=r.byteLength):e instanceof Float32Array?r=e:r=new Float32Array(e),this._bufferManager.setSubData(s,t,r,0,i)};Pt.prototype.bindUniformBufferBase=function(o,e,t){this._currentDrawContext.setBuffer(t,o)};Pt.prototype.bindUniformBlock=function(){};function zV(o){return!!(o&&o.underlyingResource!==void 0)}Pt.prototype.updateVideoTexture=function(o,e,t){var i;if(!o||o._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let s=o._hardwareTexture;!((i=o._hardwareTexture)===null||i===void 0)&&i.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(o)),zV(e)?(this._textureHelper.copyVideoToTexture(e,o,s.format,!t),o.generateMipMaps&&this._generateMipmaps(o),o.isReady=!0):e&&this.createImageBitmap(e).then(r=>{this._textureHelper.updateTexture(r,o,o.width,o.height,o.depth,s.format,0,0,!t,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o),o.isReady=!0}).catch(()=>{o.isReady=!0})};class tc extends Yt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=k.Identity(),this._projectionMatrix=k.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=T.Zero()),T.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=T.Zero()),T.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=T.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=T.Cross(this.direction,an.Y),t=T.Cross(e,this.direction);return T.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=T.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=k.Identity()),k.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=K.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),T.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(T.Dot(t,T.Up()))===1&&(t.z=1e-13);const s=K.Vector3[1];return i.addToRef(t,s),k.LookAtLHToRef(i,s,T.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}A([kr()],tc.prototype,"position",null);A([kr()],tc.prototype,"direction",null);A([D()],tc.prototype,"shadowMinZ",null);A([D()],tc.prototype,"shadowMaxZ",null);Mi.AddNodeConstructor("Light_Type_1",(o,e)=>()=>new ro(o,T.Zero(),e));class ro extends tc{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 Yt.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&&k.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=T.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;fthis._orthoRight&&(this._orthoRight=c.x),c.y>this._orthoTop&&(this._orthoTop=c.y),this.autoCalcShadowZBounds&&(c.zd&&(d=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=d)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;k.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?l:a,h?a: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}}A([D()],ro.prototype,"shadowFrustumSize",null);A([D()],ro.prototype,"shadowOrthoScale",null);A([D()],ro.prototype,"autoUpdateExtends",void 0);A([D()],ro.prototype,"autoCalcShadowZBounds",void 0);A([D("orthoLeft")],ro.prototype,"_orthoLeft",void 0);A([D("orthoRight")],ro.prototype,"_orthoRight",void 0);A([D("orthoTop")],ro.prototype,"_orthoTop",void 0);A([D("orthoBottom")],ro.prototype,"_orthoBottom",void 0);function WV(o,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=Qo("",{slice:.5,diameter:e.diameter,segments:e.segments},t),s=wx("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);s.rotation.x=-Math.PI/2,s.parent=i;const r=se.MergeMeshes([s,i],!0);return r.name=o,r}se.CreateHemisphere=(o,e,t,i)=>WV(o,{segments:e,diameter:t},i);Mi.AddNodeConstructor("Light_Type_2",(o,e)=>()=>new io(o,T.Zero(),T.Zero(),0,0,e));class io extends tc{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()&&(io._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):io._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=k.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=T.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=T.Zero(),this._projectionTextureViewLightMatrix=k.Zero(),this._projectionTextureProjectionLightMatrix=k.Zero(),this._projectionTextureScalingMatrix=k.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 Yt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(r,1,l?a:n,l?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),k.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;k.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 ee){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;k.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=T.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=T.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=T.Normalize(this.transformedDirection):i=T.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())}}A([D()],io.prototype,"angle",null);A([D()],io.prototype,"innerAngle",null);A([D()],io.prototype,"shadowAngleScale",null);A([D()],io.prototype,"exponent",void 0);A([D()],io.prototype,"projectionTextureLightNear",null);A([D()],io.prototype,"projectionTextureLightFar",null);A([D()],io.prototype,"projectionTextureUpDirection",null);A([Jt("projectedLightTexture")],io.prototype,"_projectionTexture",void 0);const HV="kernelBlurVaryingDeclaration",XV="varying vec2 sampleCoord{X};";ne.IncludesShadersStore[HV]=XV;const YV="packingFunctions",$V=`vec4 pack(float depth) +`:e="",{module:this._device.createShaderModule({code:e+o}),entryPoint:t}};Pt.prototype._createDepthStencilCubeTexture=function(o,e){const t=new Ti(this,Ut.DepthStencil);t.isCube=!0;const i=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},e);return t.format=i.generateStencil?13:14,this._setupDepthStencilTexture(t,o,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t),this._internalTexturesCache.push(t),t};Pt.prototype.createCubeTexture=function(o,e,t,i,s=null,r=null,n,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(o,e,t,!!i,s,r,n,a,l,h,c,u,null,(f,p)=>{const _=p,g=_[0].width,v=g;this._setCubeMapTextureParams(f,!i),f.format=n??-1;const E=this._textureHelper.createGPUTextureForInternalTexture(f,g,v);this._textureHelper.updateCubeTextures(_,E.underlyingResource,g,v,E.format,!1,!1,0,0),i||this._generateMipmaps(f,this._uploadEncoder),f.isReady=!0,f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),s&&s()},!!d)};Pt.prototype._setCubeMapTextureParams=function(o,e,t){o.samplingMode=e?3:2,o._cachedWrapU=0,o._cachedWrapV=0,t&&(o._maxLodLevel=t)};Pt.prototype._debugPushGroup=function(o,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(o):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(o):this._pendingDebugCommands.push(["push",o]))};Pt.prototype._debugPopGroup=function(o){this._options.enableGPUDebugMarkers&&(o===0||o===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Pt.prototype._debugInsertMarker=function(o,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(o):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(o):this._pendingDebugCommands.push(["insert",o]))};Pt.prototype._debugFlushPendingCommands=function(){for(let o=0;o{e==null||e.removePendingData(d),h&&_&&h(_.status+" "+_.statusText,g)},p=_=>{const g=d.width,v=n(_);if(!v)return;const E=[0,2,4,1,3,5];if(a){const C=i===4,S=a(v),b=d._hardwareTexture,R=[0,1,2,3,4,5];for(let I=0;I>I,O=[];for(let L=0;L<6;L++){let B=S[I][R[L]];C&&(B=ap(B,N,N,s)),O.push(new Uint8Array(B.buffer,B.byteOffset,B.byteLength))}this._textureHelper.updateCubeTextures(O,b.underlyingResource,N,N,b.format,u,!1,0,0)}}else{const C=[];for(let S=0;S<6;S++)C.push(v[E[S]]);this.updateRawCubeTexture(d,C,i,s,u)}d.isReady=!0,e==null||e.removePendingData(d),l&&l()};return this._loadFile(o,_=>{p(_)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};Pt.prototype.createRawTexture3D=function(o,e,t,i,s,r,n,a,l=null,h=0,c=0){const u=Ut.Raw3D,d=new Ti(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=a,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=o),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,c),this.updateRawTexture3D(d,o,s,n,l,h),this._internalTexturesCache.push(d),d};Pt.prototype.updateRawTexture3D=function(o,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.invertY=i,o._compression=s),e){const n=o._hardwareTexture;t===4&&(e=ap(e,o.width,o.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,o,o.width,o.height,o.depth,n.format,0,0,i,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o,this._uploadEncoder)}o.isReady=!0};Pt.prototype.createRawTexture2DArray=function(o,e,t,i,s,r,n,a,l=null,h=0,c=0){const u=Ut.Raw2DArray,d=new Ti(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=a,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=o),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,c),this.updateRawTexture2DArray(d,o,s,n,l,h),this._internalTexturesCache.push(d),d};Pt.prototype.updateRawTexture2DArray=function(o,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(o._bufferView=e,o.format=t,o.invertY=i,o._compression=s),e){const n=o._hardwareTexture;t===4&&(e=ap(e,o.width,o.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,o,o.width,o.height,o.depth,n.format,0,0,i,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o,this._uploadEncoder)}o.isReady=!0};function ap(o,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;n0,o.depth=l,o.isReady=!0,o.samples=r,o.generateMipMaps=!1,o.samplingMode=i?2:1,o.type=1,o._comparisonFunction=s,o._cachedWrapU=0,o._cachedWrapV=0};Pt.prototype.updateRenderTargetTextureSampleCount=function(o,e){return!o||!o.texture||o.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(o.texture,e),o._depthStencilTexture&&(this._textureHelper.createMSAATexture(o._depthStencilTexture,e),o._depthStencilTexture.samples=e),o._samples=e,o.texture.samples=e),e};Pt.prototype.createRenderTargetCubeTexture=function(o,e){var t;const i=this._createHardwareRenderTargetWrapper(!1,!0,o),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},e);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=(t=s.label)!==null&&t!==void 0?t:"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new Ti(this,Ut.RenderTarget);return r.width=o,r.height=o,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,s.samplingMode===void 0||s.samplingMode===2||s.samplingMode===2||s.samplingMode===3||s.samplingMode===3||s.samplingMode===5||s.samplingMode===6||s.samplingMode===7||s.samplingMode===11,i._generateStencilBuffer,i.samples),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),e&&e.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i};ji.prototype.setTextureSampler=function(o,e){this._engine.setTextureSampler(o,e)};Pt.prototype.setTextureSampler=function(o,e){var t;(t=this._currentMaterialContext)===null||t===void 0||t.setSampler(o,e)};ji.prototype.setStorageBuffer=function(o,e){this._engine.setStorageBuffer(o,e)};Pt.prototype.createStorageBuffer=function(o,e,t){return this._createBuffer(o,e|32,t)};Pt.prototype.updateStorageBuffer=function(o,e,t,i){const s=o;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)};Pt.prototype.readFromStorageBuffer=function(o,e,t,i,s){t=t||o.capacity;const r=this._bufferManager.createRawBuffer(t,Hi.MapRead|Hi.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(o.underlyingResource,e??0,r,0,t),new Promise((n,a)=>{const l=()=>{r.mapAsync(Yh.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):a(h)})};s?(this.flushFramebuffer(),l()):this.onEndFrameObservable.addOnce(()=>{l()})})};Pt.prototype.setStorageBuffer=function(o,e){var t,i;(t=this._currentDrawContext)===null||t===void 0||t.setBuffer(o,(i=e==null?void 0:e.getBuffer())!==null&&i!==void 0?i:null)};Pt.prototype.createUniformBuffer=function(o,e){let t;return o instanceof Array?t=new Float32Array(o):t=o,this._bufferManager.createBuffer(t,Hi.Uniform|Hi.CopyDst,e)};Pt.prototype.createDynamicUniformBuffer=function(o,e){return this.createUniformBuffer(o,e)};Pt.prototype.updateUniformBuffer=function(o,e,t,i){t===void 0&&(t=0);const s=o;let r;i===void 0?(e instanceof Float32Array?r=e:r=new Float32Array(e),i=r.byteLength):e instanceof Float32Array?r=e:r=new Float32Array(e),this._bufferManager.setSubData(s,t,r,0,i)};Pt.prototype.bindUniformBufferBase=function(o,e,t){this._currentDrawContext.setBuffer(t,o)};Pt.prototype.bindUniformBlock=function(){};function XV(o){return!!(o&&o.underlyingResource!==void 0)}Pt.prototype.updateVideoTexture=function(o,e,t){var i;if(!o||o._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let s=o._hardwareTexture;!((i=o._hardwareTexture)===null||i===void 0)&&i.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(o)),XV(e)?(this._textureHelper.copyVideoToTexture(e,o,s.format,!t),o.generateMipMaps&&this._generateMipmaps(o),o.isReady=!0):e&&this.createImageBitmap(e).then(r=>{this._textureHelper.updateTexture(r,o,o.width,o.height,o.depth,s.format,0,0,!t,!1,0,0),o.generateMipMaps&&this._generateMipmaps(o),o.isReady=!0}).catch(()=>{o.isReady=!0})};class ic extends Yt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=k.Identity(),this._projectionMatrix=k.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=T.Zero()),T.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=T.Zero()),T.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=T.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=T.Cross(this.direction,an.Y),t=T.Cross(e,this.direction);return T.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=T.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=k.Identity()),k.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=K.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),T.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(T.Dot(t,T.Up()))===1&&(t.z=1e-13);const s=K.Vector3[1];return i.addToRef(t,s),k.LookAtLHToRef(i,s,T.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}A([kr()],ic.prototype,"position",null);A([kr()],ic.prototype,"direction",null);A([D()],ic.prototype,"shadowMinZ",null);A([D()],ic.prototype,"shadowMaxZ",null);Mi.AddNodeConstructor("Light_Type_1",(o,e)=>()=>new ro(o,T.Zero(),e));class ro extends ic{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 Yt.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&&k.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=T.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;fthis._orthoRight&&(this._orthoRight=c.x),c.y>this._orthoTop&&(this._orthoTop=c.y),this.autoCalcShadowZBounds&&(c.zd&&(d=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=d)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;k.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?l:a,h?a: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}}A([D()],ro.prototype,"shadowFrustumSize",null);A([D()],ro.prototype,"shadowOrthoScale",null);A([D()],ro.prototype,"autoUpdateExtends",void 0);A([D()],ro.prototype,"autoCalcShadowZBounds",void 0);A([D("orthoLeft")],ro.prototype,"_orthoLeft",void 0);A([D("orthoRight")],ro.prototype,"_orthoRight",void 0);A([D("orthoTop")],ro.prototype,"_orthoTop",void 0);A([D("orthoBottom")],ro.prototype,"_orthoBottom",void 0);function YV(o,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=Qo("",{slice:.5,diameter:e.diameter,segments:e.segments},t),s=Lx("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);s.rotation.x=-Math.PI/2,s.parent=i;const r=se.MergeMeshes([s,i],!0);return r.name=o,r}se.CreateHemisphere=(o,e,t,i)=>YV(o,{segments:e,diameter:t},i);Mi.AddNodeConstructor("Light_Type_2",(o,e)=>()=>new io(o,T.Zero(),T.Zero(),0,0,e));class io extends ic{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()&&(io._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):io._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=k.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=T.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=T.Zero(),this._projectionTextureViewLightMatrix=k.Zero(),this._projectionTextureProjectionLightMatrix=k.Zero(),this._projectionTextureScalingMatrix=k.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 Yt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(r,1,l?a:n,l?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),k.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;k.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 ee){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;k.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=T.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=T.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=T.Normalize(this.transformedDirection):i=T.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())}}A([D()],io.prototype,"angle",null);A([D()],io.prototype,"innerAngle",null);A([D()],io.prototype,"shadowAngleScale",null);A([D()],io.prototype,"exponent",void 0);A([D()],io.prototype,"projectionTextureLightNear",null);A([D()],io.prototype,"projectionTextureLightFar",null);A([D()],io.prototype,"projectionTextureUpDirection",null);A([Jt("projectedLightTexture")],io.prototype,"_projectionTexture",void 0);const $V="kernelBlurVaryingDeclaration",KV="varying vec2 sampleCoord{X};";ne.IncludesShadersStore[$V]=KV;const qV="packingFunctions",jV=`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);}`;ne.IncludesShadersStore[YV]=$V;const KV="kernelBlurFragment",qV=`#ifdef DOF +{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);}`;ne.IncludesShadersStore[qV]=jV;const QV="kernelBlurFragment",ZV=`#ifdef DOF factor=sampleCoC(sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else @@ -3307,7 +3307,7 @@ blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; #endif -`;ne.IncludesShadersStore[KV]=qV;const jV="kernelBlurFragment2",QV=`#ifdef DOF +`;ne.IncludesShadersStore[QV]=ZV;const JV="kernelBlurFragment2",eU=`#ifdef DOF factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; @@ -3317,7 +3317,7 @@ blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})) #else blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif -`;ne.IncludesShadersStore[jV]=QV;const ZV="kernelBlurPixelShader",JV=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +`;ne.IncludesShadersStore[JV]=eU;const tU="kernelBlurPixelShader",iU=`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 @@ -3352,7 +3352,7 @@ gl_FragColor=blend; #ifdef DOF gl_FragColor/=sumOfWeights; #endif -}`;ne.ShadersStore[ZV]=JV;const eU="kernelBlurVertex",tU="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";ne.IncludesShadersStore[eU]=tU;const iU="kernelBlurVertexShader",sU=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +}`;ne.ShadersStore[tU]=iU;const sU="kernelBlurVertex",rU="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";ne.IncludesShadersStore[sU]=rU;const nU="kernelBlurVertexShader",aU=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; #include[0..varyingCount] const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @@ -3362,12 +3362,12 @@ sampleCenter=(position*madd+madd); #include[0..varyingCount] gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[iU]=sU;class or extends lt{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=ee.BILINEAR_SAMPLINGMODE,a,l,h=0,c="",u=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,a,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=[],a=0;for(let g=0;g{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=[],a=0;for(let g=0;g0)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 Xe.Parse(()=>new or(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}A([D("kernel")],or.prototype,"_kernel",void 0);A([D("packedFloat")],or.prototype,"_packedFloat",void 0);A([ix()],or.prototype,"direction",void 0);j("BABYLON.BlurPostProcess",or);class Om extends ms{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=ee.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,s,!0,r,!1,n,a),this.mirrorPlane=new An(0,1,0,1),this._transformMatrix=k.Zero(),this._mirrorMatrix=k.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===void 0||c.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var c;(c=l._debugPopGroup)===null||c===void 0||c.call(l,1)});let h;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),k.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=T.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 or("horizontal blur",new Re(1,0),this._blurKernelX,this._blurRatio,null,ee.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 or("vertical blur",new Re(0,1),this._blurKernelY,this._blurRatio,null,ee.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 Om(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(e=this._sceneUBO)===null||e===void 0||e.dispose()}}ee._CreateMirror=(o,e,t,i)=>new Om(o,e,t,i);class lr extends Ei{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(k.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 lr(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new lr(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,a=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 he,this.boundingBoxPosition=T.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new k,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=k.Identity(),this._createPolynomials=u,this.coordinatesMode=ee.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=c,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=d,this._lodOffset=f,!(!e&&!r)&&this.updateURL(e,c,n,h,a,i,(g=this.getScene())===null||g===void 0?void 0:g.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,a=!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 p=0;pa.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!(!((i=this.getScene())===null||i===void 0)&&i.useRightHandedSystem)))return;const s=K.Vector3[0],r=K.Quaternion[0],n=K.Vector3[1];this._textureMatrix.decompose(s,r,n),r.z*=-1,r.w*=-1,k.ComposeToRef(s,r,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return!((e=this.getScene())===null||e===void 0)&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const s=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const n=()=>{var l;this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),(l=this.getScene())===null||l===void 0||l.markAllMaterialsAsDirty(1)),e&&e()},a=(l,h)=>{this._loadingError=!0,this._errorObject={message:l,exception:h},t&&t(l,h),ee.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?fe.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,s,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,s,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(i=this._texture)===null||i===void 0||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=Xe.Parse(()=>{var r;let n=!1;return e.prefiltered&&(n=e.prefiltered),new lr(i+((r=e.url)!==null&&r!==void 0?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r{const i=new lr(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}A([D()],lr.prototype,"url",void 0);A([kr()],lr.prototype,"boundingBoxPosition",void 0);A([kr()],lr.prototype,"boundingBoxSize",null);A([D("rotationY")],lr.prototype,"rotationY",null);A([D("files")],lr.prototype,"_files",void 0);A([D("forcedExtension")],lr.prototype,"_forcedExtension",void 0);A([D("extensions")],lr.prototype,"_extensions",void 0);A([rx("textureMatrix")],lr.prototype,"_textureMatrix",void 0);A([rx("textureMatrixRefraction")],lr.prototype,"_textureMatrixRefraction",void 0);ee._CubeTextureParser=lr.Parse;j("BABYLON.CubeTexture",lr);const rU="backgroundFragmentDeclaration",nU=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +`,_++;this.packedFloat&&(p+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(p,null,null,{varyingCount:f,depCount:_},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 Xe.Parse(()=>new or(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}A([D("kernel")],or.prototype,"_kernel",void 0);A([D("packedFloat")],or.prototype,"_packedFloat",void 0);A([rx()],or.prototype,"direction",void 0);j("BABYLON.BlurPostProcess",or);class Om extends ms{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=ee.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,s,!0,r,!1,n,a),this.mirrorPlane=new Rn(0,1,0,1),this._transformMatrix=k.Zero(),this._mirrorMatrix=k.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===void 0||c.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var c;(c=l._debugPopGroup)===null||c===void 0||c.call(l,1)});let h;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),k.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=T.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 or("horizontal blur",new Re(1,0),this._blurKernelX,this._blurRatio,null,ee.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 or("vertical blur",new Re(0,1),this._blurKernelY,this._blurRatio,null,ee.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 Om(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),(e=this._sceneUBO)===null||e===void 0||e.dispose()}}ee._CreateMirror=(o,e,t,i)=>new Om(o,e,t,i);class lr extends Ei{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(k.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 lr(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new lr(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,a=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 he,this.boundingBoxPosition=T.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new k,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=k.Identity(),this._createPolynomials=u,this.coordinatesMode=ee.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=c,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=d,this._lodOffset=f,!(!e&&!r)&&this.updateURL(e,c,n,h,a,i,(g=this.getScene())===null||g===void 0?void 0:g.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,a=!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 p=0;pa.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!(!((i=this.getScene())===null||i===void 0)&&i.useRightHandedSystem)))return;const s=K.Vector3[0],r=K.Quaternion[0],n=K.Vector3[1];this._textureMatrix.decompose(s,r,n),r.z*=-1,r.w*=-1,k.ComposeToRef(s,r,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return!((e=this.getScene())===null||e===void 0)&&e.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const s=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const n=()=>{var l;this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),(l=this.getScene())===null||l===void 0||l.markAllMaterialsAsDirty(1)),e&&e()},a=(l,h)=>{this._loadingError=!0,this._errorObject={message:l,exception:h},t&&t(l,h),ee.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?fe.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,s,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,s,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(i=this._texture)===null||i===void 0||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=Xe.Parse(()=>{var r;let n=!1;return e.prefiltered&&(n=e.prefiltered),new lr(i+((r=e.url)!==null&&r!==void 0?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r{const i=new lr(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}A([D()],lr.prototype,"url",void 0);A([kr()],lr.prototype,"boundingBoxPosition",void 0);A([kr()],lr.prototype,"boundingBoxSize",null);A([D("rotationY")],lr.prototype,"rotationY",null);A([D("files")],lr.prototype,"_files",void 0);A([D("forcedExtension")],lr.prototype,"_forcedExtension",void 0);A([D("extensions")],lr.prototype,"_extensions",void 0);A([ax("textureMatrix")],lr.prototype,"_textureMatrix",void 0);A([ax("textureMatrixRefraction")],lr.prototype,"_textureMatrixRefraction",void 0);ee._CubeTextureParser=lr.Parse;j("BABYLON.CubeTexture",lr);const oU="backgroundFragmentDeclaration",lU=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; #ifdef USEHIGHLIGHTANDSHADOWCOLORS uniform vec4 vPrimaryColorShadow; #endif @@ -3390,10 +3390,10 @@ uniform mat4 view; #ifdef PROJECTED_GROUND uniform vec2 projectedGroundInfos; #endif -`;ne.IncludesShadersStore[rU]=nU;const aU="backgroundUboDeclaration",oU=`layout(std140,column_major) uniform;uniform Material +`;ne.IncludesShadersStore[oU]=lU;const hU="backgroundUboDeclaration",cU=`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 -`;ne.IncludesShadersStore[aU]=oU;const lU="backgroundPixelShader",hU=`#ifdef TEXTURELODSUPPORT +`;ne.IncludesShadersStore[hU]=cU;const uU="backgroundPixelShader",dU=`#ifdef TEXTURELODSUPPORT #extension GL_EXT_shader_texture_lod : enable #endif precision highp float; @@ -3604,7 +3604,7 @@ color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END } -`;ne.ShadersStore[lU]=hU;const cU="backgroundVertexDeclaration",uU=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; +`;ne.ShadersStore[uU]=dU;const fU="backgroundVertexDeclaration",pU=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif @@ -3614,7 +3614,7 @@ uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflec #ifdef POINTSIZE uniform float pointSize; #endif -`;ne.IncludesShadersStore[cU]=uU;const dU="backgroundVertexShader",fU=`precision highp float; +`;ne.IncludesShadersStore[fU]=pU;const _U="backgroundVertexShader",mU=`precision highp float; #include<__decl__backgroundVertex> #include attribute vec3 position; @@ -3711,7 +3711,7 @@ gl_PointSize=pointSize; #include #define CUSTOM_VERTEX_MAIN_END } -`;ne.ShadersStore[dU]=fU;class pU extends Wn{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 qt extends ep{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=qt.StandardReflectance0*t,this.reflectionReflectance90=qt.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=qt.StandardReflectance0+(1-qt.StandardReflectance0)*t,this.reflectionReflectance90=qt.StandardReflectance90+(1-qt.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=Te.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=T.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 qs(16),this._reflectionControls=Dt.Zero(),this._white=Te.White(),this._primaryShadowColor=Te.Black(),this._primaryHighlightColor=Te.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){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new pU);const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(Me.PrepareDefinesForLights(s,e,r,!1,this._maxSimultaneousLights),r._needNormals=!0,Me.PrepareDefinesForMultiview(s,r),r._areTexturesDirty){if(r._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(r.TEXTURELODSUPPORT=!0),this._diffuseTexture&&we.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Me.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE"),r.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,r.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,r.OPACITYFRESNEL=this._opacityFresnel}else r.DIFFUSE=!1,r.DIFFUSEDIRECTUV=0,r.DIFFUSEHASALPHA=!1,r.GAMMADIFFUSE=!1,r.OPACITYFRESNEL=!1;const a=this._reflectionTexture;if(a&&we.ReflectionTextureEnabled){if(!a.isReadyOrNotBlocking())return!1;switch(r.REFLECTION=!0,r.GAMMAREFLECTION=a.gammaSpace,r.RGBDREFLECTION=a.isRGBD,r.REFLECTIONBLUR=this._reflectionBlur>0,r.LODINREFLECTIONALPHA=a.lodLevelInAlpha,r.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,r.REFLECTIONBGR=this.switchToBGR,a.coordinatesMode===ee.INVCUBIC_MODE&&(r.INVERTCUBICMAP=!0),r.REFLECTIONMAP_3D=a.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,a.coordinatesMode){case ee.EXPLICIT_MODE:r.REFLECTIONMAP_EXPLICIT=!0;break;case ee.PLANAR_MODE:r.REFLECTIONMAP_PLANAR=!0;break;case ee.PROJECTION_MODE:r.REFLECTIONMAP_PROJECTION=!0;break;case ee.SKYBOX_MODE:r.REFLECTIONMAP_SKYBOX=!0;break;case ee.SPHERICAL_MODE:r.REFLECTIONMAP_SPHERICAL=!0;break;case ee.EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ee.FIXED_EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:r.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(r.REFLECTIONFRESNEL=!0,r.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1)}else r.REFLECTION=!1,r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1,r.REFLECTIONBLUR=!1,r.REFLECTIONMAP_3D=!1,r.REFLECTIONMAP_SPHERICAL=!1,r.REFLECTIONMAP_PLANAR=!1,r.REFLECTIONMAP_CUBIC=!1,r.REFLECTIONMAP_PROJECTION=!1,r.REFLECTIONMAP_SKYBOX=!1,r.REFLECTIONMAP_EXPLICIT=!1,r.REFLECTIONMAP_EQUIRECTANGULAR=!1,r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,r.INVERTCUBICMAP=!1,r.REFLECTIONMAP_OPPOSITEZ=!1,r.LODINREFLECTIONALPHA=!1,r.GAMMAREFLECTION=!1,r.RGBDREFLECTION=!1}r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.USERGBCOLOR=this._useRGBColor,r.NOISE=this._enableNoise}if(r._areLightsDirty&&(r.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),r.BACKMAT_SHADOWONLY=this._shadowOnly),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r)}if(r._areMiscDirty&&(r.REFLECTIONMAP_3D&&this._enableGroundProjection?(r.PROJECTED_GROUND=!0,r.REFLECTIONMAP_SKYBOX=!0):r.PROJECTED_GROUND=!1),Me.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),Me.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),Me.PrepareDefinesForAttributes(e,r,!1,!0,!1)&&e&&!s.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),G.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const a=new Jh;r.FOG&&a.addFallback(0,"FOG"),r.POINTSIZE&&a.addFallback(1,"POINTSIZE"),r.MULTIVIEW&&a.addFallback(0,"MULTIVIEW"),Me.HandleFallbacksForShadows(r,a,this._maxSimultaneousLights);const l=[P.PositionKind];r.NORMAL&&l.push(P.NormalKind),r.UV1&&l.push(P.UVKind),r.UV2&&l.push(P.UV2Kind),Me.PrepareAttributesForBones(l,e,r,a),Me.PrepareAttributesForInstances(l,r);const h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Ao(h);const c=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],u=["Material","Scene"];jt&&(jt.PrepareUniforms(h,r),jt.PrepareSamplers(c,r)),Me.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this._maxSimultaneousLights});const d=r.toString(),f=s.getEngine().createEffect("background",{attributes:l,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:d,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(f,r,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._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),Me.BindBonesParameters(t,this._activeEffect);const a=this._mustRebind(s,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync)&&(s.texturesEnabled&&(this._diffuseTexture&&we.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Me.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&we.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&&we.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&we.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)),so(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(s.lightsEnabled&&Me.BindLights(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Me.BindFogParameters(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&Me.BindLogDepth(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!(super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Xe.Clone(()=>new qt(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Xe.Parse(()=>new qt(e.name,t),e,t,i)}}qt.StandardReflectance0=.05;qt.StandardReflectance90=.5;A([ds()],qt.prototype,"_primaryColor",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"primaryColor",void 0);A([ds()],qt.prototype,"__perceptualColor",void 0);A([D()],qt.prototype,"_primaryColorShadowLevel",void 0);A([D()],qt.prototype,"_primaryColorHighlightLevel",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"primaryColorHighlightLevel",null);A([Jt()],qt.prototype,"_reflectionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionTexture",void 0);A([D()],qt.prototype,"_reflectionBlur",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionBlur",void 0);A([Jt()],qt.prototype,"_diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"shadowLights",void 0);A([D()],qt.prototype,"_shadowLevel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"shadowLevel",void 0);A([kr()],qt.prototype,"_sceneCenter",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"sceneCenter",void 0);A([D()],qt.prototype,"_opacityFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"opacityFresnel",void 0);A([D()],qt.prototype,"_reflectionFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionFresnel",void 0);A([D()],qt.prototype,"_reflectionFalloffDistance",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionFalloffDistance",void 0);A([D()],qt.prototype,"_reflectionAmount",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionAmount",void 0);A([D()],qt.prototype,"_reflectionReflectance0",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionReflectance0",void 0);A([D()],qt.prototype,"_reflectionReflectance90",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionReflectance90",void 0);A([D()],qt.prototype,"_useRGBColor",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"useRGBColor",void 0);A([D()],qt.prototype,"_enableNoise",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"enableNoise",void 0);A([D()],qt.prototype,"_maxSimultaneousLights",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"maxSimultaneousLights",void 0);A([D()],qt.prototype,"_shadowOnly",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"shadowOnly",void 0);A([QC()],qt.prototype,"_imageProcessingConfiguration",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],qt.prototype,"enableGroundProjection",void 0);A([D()],qt.prototype,"projectedGroundRadius",void 0);A([D()],qt.prototype,"projectedGroundHeight",void 0);j("BABYLON.BackgroundMaterial",qt);class jh{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Te(.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 Te(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:T.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=Object.assign(Object.assign({},jh._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new he,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t=Object.assign(Object.assign({},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 Ze(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 Ei){this._scene.environmentTexture=this._options.environmentTexture;return}const e=lr.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new se("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 Ji&&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=J_("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 qt("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 Ei){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new ee(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=ee.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Om("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,ee.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new An(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._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new qt("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 Ei){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new lr(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=ee.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)}}jh._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";jh._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";jh._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class In extends It{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=ee.CLAMP_ADDRESSMODE,this._texture.wrapV=ee.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=ee.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=In.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new he,this.onLoadObservable=new he,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=Qo(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:se.BACKSIDE},s);const n=this._material=new qt(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const a=this._initTexture(t,s,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Qo("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:se.BACKSIDE},s),this._halfDomeMask.rotate(an.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=T.Forward(),c=T.TransformNormal(h,l.getViewMatrix());c.normalize(),this.rotation.y=Math.acos(T.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 In.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case In.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 In.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)}}In.MODE_MONOSCOPIC=0;In.MODE_TOPBOTTOM=1;In.MODE_SIDEBYSIDE=2;class $x extends In{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 ee(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)})}}$x.MODE_MONOSCOPIC=In.MODE_MONOSCOPIC;$x.MODE_TOPBOTTOM=In.MODE_TOPBOTTOM;$x.MODE_SIDEBYSIDE=In.MODE_SIDEBYSIDE;const _U="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 mU=0;const Kx=o=>{if(!o.environmentBRDFTexture){const e=o.useDelayedTextureLoading;o.useDelayedTextureLoading=!1;const t=o._blockEntityCollection;o._blockEntityCollection=!1;const i=ee.CreateFromBase64String(_U,"EnvironmentBRDFTexture"+mU++,o,!0,!1,ee.BILINEAR_SAMPLINGMODE);o._blockEntityCollection=t;const s=o.getEngine().getLoadedTexturesCache(),r=s.indexOf(i.getInternalTexture());r!==-1&&s.splice(r,1),i.isRGBD=!0,i.wrapU=ee.CLAMP_ADDRESSMODE,i.wrapV=ee.CLAMP_ADDRESSMODE,o.environmentBRDFTexture=i,o.useDelayedTextureLoading=e,_0.ExpandRGBDTexture(i);const n=o.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const a=()=>{i.isReady()?_0.ExpandRGBDTexture(i):fe.SetImmediate(a)};a()});o.onDisposeObservable.add(()=>{o.getEngine().onContextRestoredObservable.remove(n)})}return o.environmentBRDFTexture};class gU extends Wn{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 rn extends ca{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new gU,t),this._useEnergyConservation=rn.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=rn.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=rn.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=rn.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=rn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=rn.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"}}rn.DEFAULT_USE_ENERGY_CONSERVATION=!0;rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;rn.DEFAULT_USE_SPHERICAL_HARMONICS=!0;rn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useEnergyConservation",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSmithVisibilityHeightCorrelated",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSphericalHarmonics",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const vU="pbrFragmentDeclaration",xU=`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; +`;ne.ShadersStore[_U]=mU;class gU extends Wn{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 qt extends ep{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=qt.StandardReflectance0*t,this.reflectionReflectance90=qt.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=qt.StandardReflectance0+(1-qt.StandardReflectance0)*t,this.reflectionReflectance90=qt.StandardReflectance90+(1-qt.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=Te.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=T.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 qs(16),this._reflectionControls=Dt.Zero(),this._white=Te.White(),this._primaryShadowColor=Te.Black(),this._primaryHighlightColor=Te.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){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new gU);const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if(Me.PrepareDefinesForLights(s,e,r,!1,this._maxSimultaneousLights),r._needNormals=!0,Me.PrepareDefinesForMultiview(s,r),r._areTexturesDirty){if(r._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(r.TEXTURELODSUPPORT=!0),this._diffuseTexture&&we.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Me.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE"),r.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,r.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,r.OPACITYFRESNEL=this._opacityFresnel}else r.DIFFUSE=!1,r.DIFFUSEDIRECTUV=0,r.DIFFUSEHASALPHA=!1,r.GAMMADIFFUSE=!1,r.OPACITYFRESNEL=!1;const a=this._reflectionTexture;if(a&&we.ReflectionTextureEnabled){if(!a.isReadyOrNotBlocking())return!1;switch(r.REFLECTION=!0,r.GAMMAREFLECTION=a.gammaSpace,r.RGBDREFLECTION=a.isRGBD,r.REFLECTIONBLUR=this._reflectionBlur>0,r.LODINREFLECTIONALPHA=a.lodLevelInAlpha,r.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,r.REFLECTIONBGR=this.switchToBGR,a.coordinatesMode===ee.INVCUBIC_MODE&&(r.INVERTCUBICMAP=!0),r.REFLECTIONMAP_3D=a.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,a.coordinatesMode){case ee.EXPLICIT_MODE:r.REFLECTIONMAP_EXPLICIT=!0;break;case ee.PLANAR_MODE:r.REFLECTIONMAP_PLANAR=!0;break;case ee.PROJECTION_MODE:r.REFLECTIONMAP_PROJECTION=!0;break;case ee.SKYBOX_MODE:r.REFLECTIONMAP_SKYBOX=!0;break;case ee.SPHERICAL_MODE:r.REFLECTIONMAP_SPHERICAL=!0;break;case ee.EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ee.FIXED_EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:r.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(r.REFLECTIONFRESNEL=!0,r.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1)}else r.REFLECTION=!1,r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1,r.REFLECTIONBLUR=!1,r.REFLECTIONMAP_3D=!1,r.REFLECTIONMAP_SPHERICAL=!1,r.REFLECTIONMAP_PLANAR=!1,r.REFLECTIONMAP_CUBIC=!1,r.REFLECTIONMAP_PROJECTION=!1,r.REFLECTIONMAP_SKYBOX=!1,r.REFLECTIONMAP_EXPLICIT=!1,r.REFLECTIONMAP_EQUIRECTANGULAR=!1,r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,r.INVERTCUBICMAP=!1,r.REFLECTIONMAP_OPPOSITEZ=!1,r.LODINREFLECTIONALPHA=!1,r.GAMMAREFLECTION=!1,r.RGBDREFLECTION=!1}r.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,r.USERGBCOLOR=this._useRGBColor,r.NOISE=this._enableNoise}if(r._areLightsDirty&&(r.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),r.BACKMAT_SHADOWONLY=this._shadowOnly),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r)}if(r._areMiscDirty&&(r.REFLECTIONMAP_3D&&this._enableGroundProjection?(r.PROJECTED_GROUND=!0,r.REFLECTIONMAP_SKYBOX=!0):r.PROJECTED_GROUND=!1),Me.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),Me.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),Me.PrepareDefinesForAttributes(e,r,!1,!0,!1)&&e&&!s.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),G.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const a=new ec;r.FOG&&a.addFallback(0,"FOG"),r.POINTSIZE&&a.addFallback(1,"POINTSIZE"),r.MULTIVIEW&&a.addFallback(0,"MULTIVIEW"),Me.HandleFallbacksForShadows(r,a,this._maxSimultaneousLights);const l=[P.PositionKind];r.NORMAL&&l.push(P.NormalKind),r.UV1&&l.push(P.UVKind),r.UV2&&l.push(P.UV2Kind),Me.PrepareAttributesForBones(l,e,r,a),Me.PrepareAttributesForInstances(l,r);const h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Ao(h);const c=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],u=["Material","Scene"];jt&&(jt.PrepareUniforms(h,r),jt.PrepareSamplers(c,r)),Me.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this._maxSimultaneousLights});const d=r.toString(),f=s.getEngine().createEffect("background",{attributes:l,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:d,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(f,r,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._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),Me.BindBonesParameters(t,this._activeEffect);const a=this._mustRebind(s,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync)&&(s.texturesEnabled&&(this._diffuseTexture&&we.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Me.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&we.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&&we.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&we.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)),so(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(s.lightsEnabled&&Me.BindLights(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Me.BindFogParameters(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&Me.BindLogDepth(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!(super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Xe.Clone(()=>new qt(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Xe.Parse(()=>new qt(e.name,t),e,t,i)}}qt.StandardReflectance0=.05;qt.StandardReflectance90=.5;A([ds()],qt.prototype,"_primaryColor",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"primaryColor",void 0);A([ds()],qt.prototype,"__perceptualColor",void 0);A([D()],qt.prototype,"_primaryColorShadowLevel",void 0);A([D()],qt.prototype,"_primaryColorHighlightLevel",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"primaryColorHighlightLevel",null);A([Jt()],qt.prototype,"_reflectionTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionTexture",void 0);A([D()],qt.prototype,"_reflectionBlur",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionBlur",void 0);A([Jt()],qt.prototype,"_diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"diffuseTexture",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"shadowLights",void 0);A([D()],qt.prototype,"_shadowLevel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"shadowLevel",void 0);A([kr()],qt.prototype,"_sceneCenter",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"sceneCenter",void 0);A([D()],qt.prototype,"_opacityFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"opacityFresnel",void 0);A([D()],qt.prototype,"_reflectionFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionFresnel",void 0);A([D()],qt.prototype,"_reflectionFalloffDistance",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionFalloffDistance",void 0);A([D()],qt.prototype,"_reflectionAmount",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionAmount",void 0);A([D()],qt.prototype,"_reflectionReflectance0",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionReflectance0",void 0);A([D()],qt.prototype,"_reflectionReflectance90",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"reflectionReflectance90",void 0);A([D()],qt.prototype,"_useRGBColor",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"useRGBColor",void 0);A([D()],qt.prototype,"_enableNoise",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"enableNoise",void 0);A([D()],qt.prototype,"_maxSimultaneousLights",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],qt.prototype,"maxSimultaneousLights",void 0);A([D()],qt.prototype,"_shadowOnly",void 0);A([Ce("_markAllSubMeshesAsLightsDirty")],qt.prototype,"shadowOnly",void 0);A([JC()],qt.prototype,"_imageProcessingConfiguration",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],qt.prototype,"enableGroundProjection",void 0);A([D()],qt.prototype,"projectedGroundRadius",void 0);A([D()],qt.prototype,"projectedGroundHeight",void 0);j("BABYLON.BackgroundMaterial",qt);class Qh{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Te(.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 Te(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:T.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=Object.assign(Object.assign({},Qh._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new he,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t=Object.assign(Object.assign({},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 Ze(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 Ei){this._scene.environmentTexture=this._options.environmentTexture;return}const e=lr.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new se("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 Ji&&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=J_("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 qt("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 Ei){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new ee(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=ee.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Om("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,ee.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Rn(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._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new qt("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 Ei){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new lr(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=ee.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)}}Qh._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";Qh._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";Qh._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class In extends It{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=ee.CLAMP_ADDRESSMODE,this._texture.wrapV=ee.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=ee.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=In.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new he,this.onLoadObservable=new he,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=Qo(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:se.BACKSIDE},s);const n=this._material=new qt(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const a=this._initTexture(t,s,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Qo("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:se.BACKSIDE},s),this._halfDomeMask.rotate(an.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=T.Forward(),c=T.TransformNormal(h,l.getViewMatrix());c.normalize(),this.rotation.y=Math.acos(T.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 In.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case In.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 In.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)}}In.MODE_MONOSCOPIC=0;In.MODE_TOPBOTTOM=1;In.MODE_SIDEBYSIDE=2;class qx extends In{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 ee(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)})}}qx.MODE_MONOSCOPIC=In.MODE_MONOSCOPIC;qx.MODE_TOPBOTTOM=In.MODE_TOPBOTTOM;qx.MODE_SIDEBYSIDE=In.MODE_SIDEBYSIDE;const vU="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 xU=0;const jx=o=>{if(!o.environmentBRDFTexture){const e=o.useDelayedTextureLoading;o.useDelayedTextureLoading=!1;const t=o._blockEntityCollection;o._blockEntityCollection=!1;const i=ee.CreateFromBase64String(vU,"EnvironmentBRDFTexture"+xU++,o,!0,!1,ee.BILINEAR_SAMPLINGMODE);o._blockEntityCollection=t;const s=o.getEngine().getLoadedTexturesCache(),r=s.indexOf(i.getInternalTexture());r!==-1&&s.splice(r,1),i.isRGBD=!0,i.wrapU=ee.CLAMP_ADDRESSMODE,i.wrapV=ee.CLAMP_ADDRESSMODE,o.environmentBRDFTexture=i,o.useDelayedTextureLoading=e,g0.ExpandRGBDTexture(i);const n=o.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const a=()=>{i.isReady()?g0.ExpandRGBDTexture(i):fe.SetImmediate(a)};a()});o.onDisposeObservable.add(()=>{o.getEngine().onContextRestoredObservable.remove(n)})}return o.environmentBRDFTexture};class TU extends Wn{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 rn extends ca{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new TU,t),this._useEnergyConservation=rn.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=rn.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=rn.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=rn.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=rn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=rn.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"}}rn.DEFAULT_USE_ENERGY_CONSERVATION=!0;rn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;rn.DEFAULT_USE_SPHERICAL_HARMONICS=!0;rn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useEnergyConservation",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSmithVisibilityHeightCorrelated",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSphericalHarmonics",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],rn.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const EU="pbrFragmentDeclaration",SU=`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 @@ -3847,12 +3847,12 @@ uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;unifo #endif #endif #define ADDITIONAL_FRAGMENT_DECLARATION -`;ne.IncludesShadersStore[vU]=xU;const TU="pbrUboDeclaration",EU=`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; +`;ne.IncludesShadersStore[EU]=SU;const CU="pbrUboDeclaration",bU=`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 #include -`;ne.IncludesShadersStore[TU]=EU;const SU="pbrFragmentExtraDeclaration",CU=`varying vec3 vPositionW; +`;ne.IncludesShadersStore[CU]=bU;const yU="pbrFragmentExtraDeclaration",AU=`varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif @@ -3866,7 +3866,7 @@ varying vec3 vEnvironmentIrradiance; #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif -`;ne.IncludesShadersStore[SU]=CU;const bU="samplerFragmentAlternateDeclaration",yU=`#ifdef _DEFINENAME_ +`;ne.IncludesShadersStore[yU]=AU;const RU="samplerFragmentAlternateDeclaration",IU=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -3883,7 +3883,7 @@ varying vec4 vColor; varying vec2 v_VARYINGNAME_UV; #endif #endif -`;ne.IncludesShadersStore[bU]=yU;const AU="pbrFragmentSamplersDeclaration",RU=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +`;ne.IncludesShadersStore[RU]=IU;const PU="pbrFragmentSamplersDeclaration",MU=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) @@ -3975,11 +3975,11 @@ uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; #include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) #include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) #endif -`;ne.IncludesShadersStore[AU]=RU;const IU="subSurfaceScatteringFunctions",PU=`bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`;ne.IncludesShadersStore[IU]=PU;const MU="importanceSampling",DU=`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);} +`;ne.IncludesShadersStore[PU]=MU;const DU="subSurfaceScatteringFunctions",OU=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;ne.IncludesShadersStore[DU]=OU;const NU="importanceSampling",wU=`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);}`;ne.IncludesShadersStore[MU]=DU;const OU="pbrHelperFunctions",NU=`#define MINIMUMVARIANCE 0.0005 +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);}`;ne.IncludesShadersStore[NU]=wU;const FU="pbrHelperFunctions",LU=`#define MINIMUMVARIANCE 0.0005 float convertRoughnessToAverageSlope(float roughness) {return square(roughness)+MINIMUMVARIANCE;} float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} @@ -4011,7 +4011,7 @@ clearCoatIntensity);return clearCoatAbsorption;} 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 -`;ne.IncludesShadersStore[OU]=NU;const wU="harmonicsFunctions",FU=`#ifdef USESPHERICALFROMREFLECTIONMAP +`;ne.IncludesShadersStore[FU]=LU;const BU="harmonicsFunctions",VU=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 + vSphericalL1_1*(normal.y) @@ -4026,7 +4026,7 @@ vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 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 -`;ne.IncludesShadersStore[wU]=FU;const LU="pbrDirectLightingSetupFunctions",BU=`struct preLightingInfo +`;ne.IncludesShadersStore[BU]=VU;const UU="pbrDirectLightingSetupFunctions",kU=`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; @@ -4037,7 +4037,7 @@ preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) #ifdef SPECULARTERM result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); #endif -return result;}`;ne.IncludesShadersStore[LU]=BU;const VU="pbrDirectLightingFalloffFunctions",UU=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +return result;}`;ne.IncludesShadersStore[UU]=kU;const GU="pbrDirectLightingFalloffFunctions",zU=`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);} @@ -4071,7 +4071,7 @@ return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenter #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif -}`;ne.IncludesShadersStore[VU]=UU;const kU="pbrBRDFFunctions",GU=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +}`;ne.IncludesShadersStore[GU]=zU;const WU="pbrBRDFFunctions",HU=`#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 @@ -4201,7 +4201,7 @@ float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {f 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 -`;ne.IncludesShadersStore[kU]=GU;const zU="hdrFilteringFunctions",WU=`#ifdef NUM_SAMPLES +`;ne.IncludesShadersStore[WU]=HU;const XU="hdrFilteringFunctions",YU=`#ifdef NUM_SAMPLES #if NUM_SAMPLES>0 #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) float radicalInverse_VdC(uint bits) @@ -4254,7 +4254,7 @@ result+=c*NoL;}} result=result/weight;return result;}} #endif #endif -`;ne.IncludesShadersStore[zU]=WU;const HU="pbrDirectLightingFunctions",XU=`#define CLEARCOATREFLECTANCE90 1.0 +`;ne.IncludesShadersStore[XU]=YU;const $U="pbrDirectLightingFunctions",KU=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM @@ -4314,7 +4314,7 @@ float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} #endif -`;ne.IncludesShadersStore[HU]=XU;const YU="pbrIBLFunctions",$U=`#if defined(REFLECTION) || defined(SS_REFRACTION) +`;ne.IncludesShadersStore[$U]=KU;const qU="pbrIBLFunctions",jU=`#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 @@ -4328,7 +4328,7 @@ float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {v #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 -`;ne.IncludesShadersStore[YU]=$U;const KU="pbrBlockAlbedoOpacity",qU=`struct albedoOpacityOutParams +`;ne.IncludesShadersStore[qU]=jU;const QU="pbrBlockAlbedoOpacity",ZU=`struct albedoOpacityOutParams {vec3 surfaceAlbedo;float alpha;}; #define pbr_inline void albedoOpacityBlock( @@ -4399,7 +4399,7 @@ alpha=1.0; #endif #endif outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;} -`;ne.IncludesShadersStore[KU]=qU;const jU="pbrBlockReflectivity",QU=`struct reflectivityOutParams +`;ne.IncludesShadersStore[QU]=ZU;const JU="pbrBlockReflectivity",e3=`struct reflectivityOutParams {float microSurface;float roughness;vec3 surfaceReflectivityColor; #ifdef METALLICWORKFLOW vec3 surfaceAlbedo; @@ -4509,7 +4509,7 @@ microSurface*=microSurfaceTexel.r; #endif #endif microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} -`;ne.IncludesShadersStore[jU]=QU;const ZU="pbrBlockAmbientOcclusion",JU=`struct ambientOcclusionOutParams +`;ne.IncludesShadersStore[JU]=e3;const t3="pbrBlockAmbientOcclusion",i3=`struct ambientOcclusionOutParams {vec3 ambientOcclusionColor; #if DEBUGMODE>0 && defined(AMBIENT) vec3 ambientOcclusionColorMap; @@ -4535,7 +4535,7 @@ outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;} -`;ne.IncludesShadersStore[ZU]=JU;const e3="pbrBlockAlphaFresnel",t3=`#ifdef ALPHAFRESNEL +`;ne.IncludesShadersStore[t3]=i3;const s3="pbrBlockAlphaFresnel",r3=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {float alpha;}; @@ -4564,7 +4564,7 @@ outParams.alpha=1.0; } #endif #endif -`;ne.IncludesShadersStore[e3]=t3;const i3="pbrBlockAnisotropic",s3=`#ifdef ANISOTROPIC +`;ne.IncludesShadersStore[s3]=r3;const n3="pbrBlockAnisotropic",a3=`#ifdef ANISOTROPIC struct anisotropicOutParams {float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; #if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) @@ -4598,7 +4598,7 @@ anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotr #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 -`;ne.IncludesShadersStore[i3]=s3;const r3="pbrBlockReflection",n3=`#ifdef REFLECTION +`;ne.IncludesShadersStore[n3]=a3;const o3="pbrBlockReflection",l3=`#ifdef REFLECTION struct reflectionOutParams {vec4 environmentRadiance;vec3 environmentIrradiance; #ifdef REFLECTIONMAP_3D @@ -4845,7 +4845,7 @@ environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); #endif environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} #endif -`;ne.IncludesShadersStore[r3]=n3;const a3="pbrBlockSheen",o3=`#ifdef SHEEN +`;ne.IncludesShadersStore[o3]=l3;const h3="pbrBlockSheen",c3=`#ifdef SHEEN struct sheenOutParams {float sheenIntensity;vec3 sheenColor;float sheenRoughness; #ifdef SHEEN_LINKWITHALBEDO @@ -5027,7 +5027,7 @@ outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor. #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} #endif -`;ne.IncludesShadersStore[a3]=o3;const l3="pbrBlockClearcoat",h3=`struct clearcoatOutParams +`;ne.IncludesShadersStore[h3]=c3;const u3="pbrBlockClearcoat",d3=`struct clearcoatOutParams {vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; #ifdef REFLECTION vec3 finalClearCoatRadianceScaled; @@ -5274,7 +5274,7 @@ outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParam #endif } #endif -`;ne.IncludesShadersStore[l3]=h3;const c3="pbrBlockIridescence",u3=`struct iridescenceOutParams +`;ne.IncludesShadersStore[u3]=d3;const f3="pbrBlockIridescence",p3=`struct iridescenceOutParams {float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; #ifdef IRIDESCENCE #define pbr_inline @@ -5317,7 +5317,7 @@ topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqr #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 -`;ne.IncludesShadersStore[c3]=u3;const d3="pbrBlockSubSurface",f3=`struct subSurfaceOutParams +`;ne.IncludesShadersStore[f3]=p3;const _3="pbrBlockSubSurface",m3=`struct subSurfaceOutParams {vec3 specularEnvironmentReflectance; #ifdef SS_REFRACTION vec3 finalRefraction;vec3 surfaceAlbedo; @@ -5697,7 +5697,7 @@ outParams.refractionIrradiance=refractionIrradiance.rgb; #endif } #endif -`;ne.IncludesShadersStore[d3]=f3;const p3="pbrBlockNormalGeometric",_3=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +`;ne.IncludesShadersStore[_3]=m3;const g3="pbrBlockNormalGeometric",v3=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else @@ -5707,7 +5707,7 @@ vec3 geometricNormalW=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; #endif -`;ne.IncludesShadersStore[p3]=_3;const m3="pbrBlockNormalFinal",g3=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +`;ne.IncludesShadersStore[g3]=v3;const x3="pbrBlockNormalFinal",T3=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; @@ -5717,7 +5717,7 @@ normalW*=sign(dot(normalW,faceNormal)); #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) normalW=gl_FrontFacing ? normalW : -normalW; #endif -`;ne.IncludesShadersStore[m3]=g3;const v3="pbrBlockLightmapInit",x3=`#ifdef LIGHTMAP +`;ne.IncludesShadersStore[x3]=T3;const E3="pbrBlockLightmapInit",S3=`#ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); @@ -5727,7 +5727,7 @@ lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif -`;ne.IncludesShadersStore[v3]=x3;const T3="pbrBlockGeometryInfo",E3=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +`;ne.IncludesShadersStore[E3]=S3;const C3="pbrBlockGeometryInfo",b3=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif @@ -5751,7 +5751,7 @@ float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); #endif #endif #endif -`;ne.IncludesShadersStore[T3]=E3;const S3="pbrBlockReflectance0",C3=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +`;ne.IncludesShadersStore[C3]=b3;const y3="pbrBlockReflectance0",A3=`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 @@ -5760,7 +5760,7 @@ vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); #ifdef ALPHAFRESNEL float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif -`;ne.IncludesShadersStore[S3]=C3;const b3="pbrBlockReflectance",y3=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +`;ne.IncludesShadersStore[y3]=A3;const R3="pbrBlockReflectance",I3=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); #ifdef RADIANCEOCCLUSION specularEnvironmentReflectance*=seo; @@ -5781,7 +5781,7 @@ specularEnvironmentReflectance*=clearcoatOut.conservationFactor; specularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif -`;ne.IncludesShadersStore[b3]=y3;const A3="pbrBlockDirectLighting",R3=`vec3 diffuseBase=vec3(0.,0.,0.); +`;ne.IncludesShadersStore[R3]=I3;const P3="pbrBlockDirectLighting",M3=`vec3 diffuseBase=vec3(0.,0.,0.); #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif @@ -5796,7 +5796,7 @@ float aggShadow=0.;float numLights=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) vec3 absorption=vec3(0.); #endif -`;ne.IncludesShadersStore[A3]=R3;const I3="pbrBlockFinalLitComponents",P3=`aggShadow=aggShadow/numLights; +`;ne.IncludesShadersStore[P3]=M3;const D3="pbrBlockFinalLitComponents",O3=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); @@ -5883,7 +5883,7 @@ luminanceOverAlpha+=getLuminance(finalClearCoatScaled); alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif -`;ne.IncludesShadersStore[I3]=P3;const M3="pbrBlockFinalUnlitComponents",D3=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +`;ne.IncludesShadersStore[D3]=O3;const N3="pbrBlockFinalUnlitComponents",w3=`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 @@ -5900,7 +5900,7 @@ vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,v vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;ne.IncludesShadersStore[M3]=D3;const O3="pbrBlockFinalColorComposition",N3=`vec4 finalColor=vec4( +`;ne.IncludesShadersStore[N3]=w3;const F3="pbrBlockFinalColorComposition",L3=`vec4 finalColor=vec4( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + @@ -5942,7 +5942,7 @@ finalColor.rgb+=lightmapColor.rgb; finalColor.rgb+=finalEmissive; #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,0.0); -`;ne.IncludesShadersStore[O3]=N3;const w3="pbrBlockImageProcessing",F3=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +`;ne.IncludesShadersStore[F3]=L3;const B3="pbrBlockImageProcessing",V3=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor.rgb=clamp(finalColor.rgb,0.,30.0); #endif @@ -5953,7 +5953,7 @@ finalColor.a*=visibility; #ifdef PREMULTIPLYALPHA finalColor.rgb*=finalColor.a; #endif -`;ne.IncludesShadersStore[w3]=F3;const L3="pbrDebug",B3=`#if DEBUGMODE>0 +`;ne.IncludesShadersStore[B3]=V3;const U3="pbrDebug",k3=`#if DEBUGMODE>0 if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { #if DEBUGMODE==1 gl_FragColor.rgb=vPositionW.rgb; @@ -6135,7 +6135,7 @@ return; #endif } #endif -`;ne.IncludesShadersStore[L3]=B3;const V3="pbrPixelShader",U3=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;ne.IncludesShadersStore[U3]=k3;const G3="pbrPixelShader",z3=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #extension GL_OES_standard_derivatives : enable #endif #ifdef LODBASEDMICROSFURACE @@ -6711,7 +6711,7 @@ if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaM #include #define CUSTOM_FRAGMENT_MAIN_END } -`;ne.ShadersStore[V3]=U3;const k3="pbrVertexDeclaration",G3=`uniform mat4 view;uniform mat4 viewProjection; +`;ne.ShadersStore[G3]=z3;const W3="pbrVertexDeclaration",H3=`uniform mat4 view;uniform mat4 viewProjection; #ifdef ALBEDO uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; #endif @@ -6822,7 +6822,7 @@ uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION -`;ne.IncludesShadersStore[k3]=G3;const z3="pbrVertexShader",W3=`precision highp float; +`;ne.IncludesShadersStore[W3]=H3;const X3="pbrVertexShader",Y3=`precision highp float; #include<__decl__pbrVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; @@ -7015,7 +7015,7 @@ gl_PointSize=pointSize; #endif #include #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[z3]=W3;class H3 extends Wn{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 Tr extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new H3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Tr._DefaultIndexOfRefraction,this.indexOfRefraction=Tr._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=Te.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&&we.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&we.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&we.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.ClearCoatTextureEnabled?Me.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&we.ClearCoatTextureEnabled?Me.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&we.ClearCoatBumpTextureEnabled?Me.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Tr._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&we.ClearCoatTintTextureEnabled?(Me.PrepareDefinesForMergedUV(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 r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,g=this._material._invertNormalMapX,v=this._material._invertNormalMapY,E=f.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){E&&we.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&we.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._textureRoughness)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"clearCoat"),this._textureRoughness&&!E&&!f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&we.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Me.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",g?1:-1,v?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",g?-1:1,v?-1:1)),this._tintTexture&&we.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Me.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const C=1-this._indexOfRefraction,S=1+this._indexOfRefraction,b=Math.pow(-C/S,2),R=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",b,R,C,S),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&&we.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!E&&!f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&we.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&we.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&we.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===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||i.dispose(),(s=this._bumpTexture)===null||s===void 0||s.dispose(),(r=this._tintTexture)===null||r===void 0||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"}]}}}Tr._DefaultIndexOfRefraction=1.5;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"isEnabled",void 0);A([D()],Tr.prototype,"intensity",void 0);A([D()],Tr.prototype,"roughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"indexOfRefraction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"useRoughnessFromMainTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"textureRoughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"remapF0OnInterfaceChange",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"bumpTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"isTintEnabled",void 0);A([ds()],Tr.prototype,"tintColor",void 0);A([D()],Tr.prototype,"tintColorAtDistance",void 0);A([D()],Tr.prototype,"tintThickness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"tintTexture",void 0);class X3 extends Wn{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 mn extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new X3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=mn._DefaultMinimumThickness,this.maximumThickness=mn._DefaultMaximumThickness,this.indexOfRefraction=mn._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&&we.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.IridescenceTextureEnabled?Me.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&we.IridescenceTextureEnabled?Me.PrepareDefinesForMergedUV(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,s){var r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;(!e.useUbo||!p||!e.isSync)&&(_&&we.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&we.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._thicknessTexture)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._thicknessTexture)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"iridescence"),this._thicknessTexture&&!_&&!f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&we.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&we.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===void 0||t.dispose(),(i=this._thicknessTexture)===null||i===void 0||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"}]}}}mn._DefaultMinimumThickness=100;mn._DefaultMaximumThickness=400;mn._DefaultIndexOfRefraction=1.3;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],mn.prototype,"isEnabled",void 0);A([D()],mn.prototype,"intensity",void 0);A([D()],mn.prototype,"minimumThickness",void 0);A([D()],mn.prototype,"maximumThickness",void 0);A([D()],mn.prototype,"indexOfRefraction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],mn.prototype,"texture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],mn.prototype,"thicknessTexture",void 0);class Y3 extends Wn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class xu extends ca{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 Y3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Re(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&&we.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(P.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.AnisotropicTextureEnabled?Me.PrepareDefinesForMergedUV(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&&we.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Me.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&we.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)}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],xu.prototype,"isEnabled",void 0);A([D()],xu.prototype,"intensity",void 0);A([ix()],xu.prototype,"direction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],xu.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],xu.prototype,"legacy",void 0);class $3 extends Wn{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 tl extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new $3,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Te.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&&we.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.SheenTextureEnabled?(Me.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&we.SheenTextureEnabled?Me.PrepareDefinesForMergedUV(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){var r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=f.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!e.useUbo||!p||!e.isSync)&&(_&&we.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&we.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._textureRoughness)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"sheen"),this._textureRoughness&&!_&&!f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(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&&we.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&we.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===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||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"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"isEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"linkSheenWithAlbedo",void 0);A([D()],tl.prototype,"intensity",void 0);A([ds()],tl.prototype,"color",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"useRoughnessFromMainTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"roughness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"textureRoughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"albedoScaling",void 0);class K3 extends Wn{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 As extends ca{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 K3,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=Te.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Te.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&&we.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&we.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&&we.ThicknessTextureEnabled&&Me.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&!r&&Me.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&!r&&Me.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&r,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&r,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&r,this._isRefractionEnabled&&t.texturesEnabled){const n=this._getRefractionTexture(t);n&&we.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(K.Vector3[0]);const r=Math.max(Math.abs(K.Vector3[0].x),Math.abs(K.Vector3[0].y),Math.abs(K.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,a=this._material.realTimeFiltering,l=r.LODBASEDMICROSFURACE,h=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&we.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Me.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Me.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Me.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),h&&we.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),a&&e.updateFloat2("vRefractionFilteringInfo",u,ye.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&&we.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),h&&we.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){we.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(we.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"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isRefractionEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isTranslucencyEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isDispersionEnabled",void 0);A([D(),Ce("_markScenePrePassDirty")],As.prototype,"isScatteringEnabled",void 0);A([D()],As.prototype,"_scatteringDiffusionProfileIndex",void 0);A([D()],As.prototype,"refractionIntensity",void 0);A([D()],As.prototype,"translucencyIntensity",void 0);A([D()],As.prototype,"useAlbedoToTintRefraction",void 0);A([D()],As.prototype,"useAlbedoToTintTranslucency",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"thicknessTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"refractionTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"indexOfRefraction",void 0);A([D()],As.prototype,"_volumeIndexOfRefraction",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"volumeIndexOfRefraction",null);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"invertRefractionY",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"linkRefractionWithTransparency",void 0);A([D()],As.prototype,"minimumThickness",void 0);A([D()],As.prototype,"maximumThickness",void 0);A([D()],As.prototype,"useThicknessAsDepth",void 0);A([ds()],As.prototype,"tintColor",void 0);A([D()],As.prototype,"tintColorAtDistance",void 0);A([D()],As.prototype,"dispersion",void 0);A([ds()],As.prototype,"diffusionDistance",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"useMaskFromThicknessTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"refractionIntensityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"translucencyIntensityTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"useGltfStyleTextures",void 0);const Rc={effect:null,subMesh:null};class V0 extends Wn{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 Ni extends ep{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 Dt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Ni.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=Te.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Te(0,0,0),this._albedoColor=new Te(1,1,1),this._reflectivityColor=new Te(1,1,1),this._reflectionColor=new Te(1,1,1),this._emissiveColor=new Te(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=Ni.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 qs(16),this._globalAmbientColor=new Te(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 rn(this),this.clearCoat=new Tr(this),this.iridescence=new mn(this),this.anisotropy=new xu(this),this.sheen=new tl(this),this.subSurface=new As(this),this.detailMap=new Th(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),we.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Kx(this.getScene()),this.prePassConfiguration=new P_}get hasRenderTargetTextures(){return we.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===Ni.PBRMATERIAL_OPAQUE||this._transparencyMode===Ni.PBRMATERIAL_ALPHATEST||((e=this.subSurface)===null||e===void 0?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===void 0)&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ni.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Ni.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var s;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo),t.materialDefines=new V0(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),a=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&we.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&we.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&we.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const d=this._getReflectionTexture();if(d&&we.ReflectionTextureEnabled){if(!d.isReadyOrNotBlocking())return!1;if(d.irradianceTexture){if(!d.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!d.sphericalPolynomial&&(!((s=d.getInternalTexture())===null||s===void 0)&&s._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&we.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&we.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(we.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(a.getCaps().standardDerivatives&&this._bumpTexture&&we.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&we.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;!a.getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),G.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&&(Rc.effect=c,Rc.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Rc)),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(),t.effect._wasPreviouslyReady=!u,t.effect._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,a){if(this._prepareDefines(e,t,r,n,a),!t.isDirty)return null;t.markAsProcessed();const h=this.getScene().getEngine(),c=new Jh;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=Me.HandleFallbacksForShadows(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=[P.PositionKind];t.NORMAL&&d.push(P.NormalKind),t.TANGENT&&d.push(P.TangentKind);for(let b=1;b<=6;++b)t["UV"+b]&&d.push(`uv${b===1?"":b}`);t.VERTEXCOLOR&&d.push(P.ColorKind),Me.PrepareAttributesForBones(d,e,t,c),Me.PrepareAttributesForInstances(d,t),Me.PrepareAttributesForMorphTargets(d,e,t),Me.PrepareAttributesForBakedVertexAnimation(d,e,t);let f="pbr";const p=["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"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],v={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=v,this._callbackPluginEventGeneric(Lr.PrepareEffect,this._eventInfo),P_.AddUniforms(p),Ao(p),jt&&(jt.PrepareUniforms(p,t),jt.PrepareSamplers(_,t)),Me.PrepareUniformsAndSamplersList({uniformsNames:p,uniformBuffersNames:g,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const E={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,g,_,t,d,E));const C=t.toString(),S=h.createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:g,samplers:_,defines:C,fallbacks:c,onCompiled:i,onError:s,indexParameters:v,processFinalCode:E.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},h);return this._eventInfo.customCode=void 0,S}_prepareDefines(e,t,i=null,s=null,r=!1){var n;const a=this.getScene(),l=a.getEngine();Me.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Me.PrepareDefinesForMultiview(a,t);const h=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Me.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!h),Me.PrepareDefinesForOIT(a,t,h),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let c=1;c<=6;++c)t["MAINUV"+c]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,l.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&we.DiffuseTextureEnabled?(Me.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&we.AmbientTextureEnabled?(Me.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&we.OpacityTextureEnabled?(Me.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const c=this._getReflectionTexture();if(c&&we.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,l._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=c.coordinatesMode===ee.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 ee.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case ee.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case ee.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case ee.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case ee.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case ee.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ee.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!c.boundingBoxSize;break}c.coordinatesMode!==ee.SKYBOX_MODE&&(c.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):c.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.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&&we.LightmapTextureEnabled?(Me.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&we.EmissiveTextureEnabled?(Me.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,we.SpecularTextureEnabled){if(this._metallicTexture?(Me.PrepareDefinesForMergedUV(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Me.PrepareDefinesForMergedUV(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){const u=this._metallicReflectanceTexture!==null&&this._metallicReflectanceTexture._texture===((n=this._reflectanceTexture)===null||n===void 0?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!u,this._metallicReflectanceTexture?(Me.PrepareDefinesForMergedUV(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)?(Me.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?Me.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;l.getCaps().standardDerivatives&&this._bumpTexture&&we.BumpTextureEnabled&&!this._disableBumpMap?(Me.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&we.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.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&&we.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===Ni.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Ni.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=l.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&&(Me.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(P.NormalKind),t.DEBUGMODE=this._debugMode),Me.PrepareDefinesForFrameBoundValues(a,l,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Me.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==Ni.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo);const r=new V0(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Rc.effect=n,Rc.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Rc)),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 s,r,n,a;const l=this.getScene(),h=i.materialDefines;if(!h)return;const c=i.effect;if(!c)return;this._activeEffect=c,t.getMeshUniformBuffer().bindToEffect(c,"Mesh"),t.transferToEffect(e);const u=l.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,l,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),h.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const d=c._forceRebindOnNextCall||this._mustRebind(l,c,t.visibility);Me.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let f=null;const p=this._uniformBuffer;if(d){if(this.bindViewProjection(c),f=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||c._forceRebindOnNextCall){if(l.texturesEnabled){if(this._albedoTexture&&we.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Me.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&we.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Me.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&we.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Me.BindTextureMatrix(this._opacityTexture,p,"opacity")),f&&we.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",f.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",f.level,0),f.boundingBoxSize){const _=f;p.updateVector3("vReflectionPosition",_.boundingBoxPosition),p.updateVector3("vReflectionSize",_.boundingBoxSize)}if(this.realTimeFiltering){const _=f.getSize().width;p.updateFloat2("vReflectionFilteringInfo",_,ye.Log2(_))}if(!h.USEIRRADIANCEMAP){const _=f.sphericalPolynomial;if(h.USESPHERICALFROMREFLECTIONMAP&&_)if(h.SPHERICAL_HARMONICS){const g=_.preScaledHarmonics;p.updateVector3("vSphericalL00",g.l00),p.updateVector3("vSphericalL1_1",g.l1_1),p.updateVector3("vSphericalL10",g.l10),p.updateVector3("vSphericalL11",g.l11),p.updateVector3("vSphericalL2_2",g.l2_2),p.updateVector3("vSphericalL2_1",g.l2_1),p.updateVector3("vSphericalL20",g.l20),p.updateVector3("vSphericalL21",g.l21),p.updateVector3("vSphericalL22",g.l22)}else p.updateFloat3("vSphericalX",_.x.x,_.x.y,_.x.z),p.updateFloat3("vSphericalY",_.y.x,_.y.y,_.y.z),p.updateFloat3("vSphericalZ",_.z.x,_.z.y,_.z.z),p.updateFloat3("vSphericalXX_ZZ",_.xx.x-_.zz.x,_.xx.y-_.zz.y,_.xx.z-_.zz.z),p.updateFloat3("vSphericalYY_ZZ",_.yy.x-_.zz.x,_.yy.y-_.zz.y,_.yy.z-_.zz.z),p.updateFloat3("vSphericalZZ",_.zz.x,_.zz.y,_.zz.z),p.updateFloat3("vSphericalXY",_.xy.x,_.xy.y,_.xy.z),p.updateFloat3("vSphericalYZ",_.yz.x,_.yz.y,_.yz.z),p.updateFloat3("vSphericalZX",_.zx.x,_.zx.y,_.zx.z)}p.updateFloat3("vReflectionMicrosurfaceInfos",f.getSize().width,f.lodGenerationScale,f.lodGenerationOffset)}this._emissiveTexture&&we.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Me.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&we.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Me.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),we.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Me.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Me.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Me.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&h.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Me.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Me.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&we.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Me.BindTextureMatrix(this._bumpTexture,p,"bump"),l._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),h.METALLICWORKFLOW){gi.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,gi.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,p.updateColor4("vReflectivityColor",gi.Color3[0],1);const _=(r=(s=this.subSurface)===null||s===void 0?void 0:s._indexOfRefraction)!==null&&r!==void 0?r:1.5,g=1,v=Math.pow((_-g)/(_+g),2);this._metallicReflectanceColor.scaleToRef(v*this._metallicF0Factor,gi.Color3[0]);const E=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",gi.Color3[0],E)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",we.EmissiveTextureEnabled?this._emissiveColor:Te.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!h.SS_REFRACTION&&(!((n=this.subSurface)===null||n===void 0)&&n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*l.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),l.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}l.texturesEnabled&&(this._albedoTexture&&we.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&we.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&we.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),f&&we.ReflectionTextureEnabled&&(h.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",f):(p.setTexture("reflectionSampler",f._lodTextureMid||f),p.setTexture("reflectionSamplerLow",f._lodTextureLow||f),p.setTexture("reflectionSamplerHigh",f._lodTextureHigh||f)),h.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",f.irradianceTexture)),h.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&we.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&we.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),we.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&h.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&we.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),so(this._activeEffect,this,l),this.bindEyePosition(c)}else l.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(d||!this.isFrozen)&&(l.lightsEnabled&&!this._disableLighting&&Me.BindLights(l,t,this._activeEffect,h,this._maxSimultaneousLights),(l.fogEnabled&&t.applyFog&&l.fogMode!==Qe.FOGMODE_NONE||f||this.subSurface.refractionTexture||t.receiveShadows||h.PREPASS)&&this.bindView(c),Me.BindFogParameters(l,t,this._activeEffect,!0),h.NUM_MORPH_INFLUENCERS&&Me.BindMorphTargetParameters(t,this._activeEffect),h.BAKED_VERTEX_ANIMATION_TEXTURE&&((a=t.bakedVertexAnimationManager)===null||a===void 0||a.bind(c,h.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Me.BindLogDepth(h,this._activeEffect,l)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var e;if(!(!((e=this.subSurface)===null||e===void 0)&&e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,s,r,n,a,l,h,c,u,d,f,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(a=this._emissiveTexture)===null||a===void 0||a.dispose(),(l=this._metallicTexture)===null||l===void 0||l.dispose(),(h=this._reflectivityTexture)===null||h===void 0||h.dispose(),(c=this._bumpTexture)===null||c===void 0||c.dispose(),(u=this._lightmapTexture)===null||u===void 0||u.dispose(),(d=this._metallicReflectanceTexture)===null||d===void 0||d.dispose(),(f=this._reflectanceTexture)===null||f===void 0||f.dispose(),(p=this._microSurfaceTexture)===null||p===void 0||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Ni.PBRMATERIAL_OPAQUE=Ie.MATERIAL_OPAQUE;Ni.PBRMATERIAL_ALPHATEST=Ie.MATERIAL_ALPHATEST;Ni.PBRMATERIAL_ALPHABLEND=Ie.MATERIAL_ALPHABLEND;Ni.PBRMATERIAL_ALPHATESTANDBLEND=Ie.MATERIAL_ALPHATESTANDBLEND;Ni.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Ni.LIGHTFALLOFF_PHYSICAL=0;Ni.LIGHTFALLOFF_GLTF=1;Ni.LIGHTFALLOFF_STANDARD=2;A([QC()],Ni.prototype,"_imageProcessingConfiguration",void 0);A([Ce("_markAllSubMeshesAsMiscDirty")],Ni.prototype,"debugMode",void 0);class Rt extends Ni{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===Ni.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ni.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Ni.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Ni.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ni.LIGHTFALLOFF_GLTF:this._lightFalloff=Ni.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=Rt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Te.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Te(0,0,0),this.albedoColor=new Te(1,1,1),this.reflectivityColor=new Te(1,1,1),this.reflectionColor=new Te(1,1,1),this.emissiveColor=new Te(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=Kx(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Xe.Clone(()=>new Rt(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=Xe.Parse(()=>new Rt(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ie._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}}Rt.PBRMATERIAL_OPAQUE=Ni.PBRMATERIAL_OPAQUE;Rt.PBRMATERIAL_ALPHATEST=Ni.PBRMATERIAL_ALPHATEST;Rt.PBRMATERIAL_ALPHABLEND=Ni.PBRMATERIAL_ALPHABLEND;Rt.PBRMATERIAL_ALPHATESTANDBLEND=Ni.PBRMATERIAL_ALPHATESTANDBLEND;Rt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Ni.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"directIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"environmentIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"specularIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"disableBumpMap",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"albedoTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTextureStrength",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"opacityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectionTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectivityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallic",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"roughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicF0Factor",void 0);A([ds(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicReflectanceColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicReflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"microSurfaceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"bumpTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty",null)],Rt.prototype,"lightmapTexture",void 0);A([ds("ambient"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientColor",void 0);A([ds("albedo"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"albedoColor",void 0);A([ds("reflectivity"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectivityColor",void 0);A([ds("reflection"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectionColor",void 0);A([ds("emissive"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"microSurface",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useLightmapAsShadowmap",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"useAlphaFromAlbedoTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"forceAlphaTest",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"alphaCutOff",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useSpecularOverAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRoughnessFromMetallicTextureGreen",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useMetallnessFromMetallicTextureBlue",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAmbientInGrayScale",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);A([D()],Rt.prototype,"usePhysicalLightFalloff",null);A([D()],Rt.prototype,"useGLTFLightFalloff",null);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRadianceOverAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useObjectSpaceNormalMap",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useParallax",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useParallaxOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"parallaxScaleBias",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Rt.prototype,"disableLighting",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"forceIrradianceInFragment",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Rt.prototype,"maxSimultaneousLights",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"invertNormalMapX",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"invertNormalMapY",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"twoSidedLighting",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAlphaFresnel",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useLinearAlphaFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"environmentBRDFTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"forceNormalForward",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"enableSpecularAntiAliasing",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useHorizonOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRadianceOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],Rt.prototype,"unlit",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],Rt.prototype,"applyDecalMapAfterDetailMap",void 0);j("BABYLON.PBRMaterial",Rt);const q3=542327876,U0=131072,k0=512,G0=4,z0=64,W0=131072;function Nm(o){return o.charCodeAt(0)+(o.charCodeAt(1)<<8)+(o.charCodeAt(2)<<16)+(o.charCodeAt(3)<<24)}function j3(o){return String.fromCharCode(o&255,o>>8&255,o>>16&255,o>>24&255)}const H0=Nm("DXT1"),X0=Nm("DXT3"),Y0=Nm("DXT5"),vv=Nm("DX10"),$0=113,K0=116,q0=2,j0=10,Q3=88,xv=31,Z3=0,J3=1,Q0=2,Z0=3,Tv=4,J0=7,Ev=20,eC=21,ek=22,tk=23,ik=24,sk=25,rk=26,nk=28,ak=32;class ki{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,xv),i=new Int32Array(e.buffer,e.byteOffset,xv+4);let s=1;t[Q0]&U0&&(s=Math.max(1,t[J0]));const r=t[eC],n=r===vv?i[ak]:0;let a=0;switch(r){case $0:a=2;break;case K0:a=1;break;case vv:if(n===j0){a=2;break}if(n===q0){a=1;break}}return{width:t[Tv],height:t[Z0],mipmapCount:s,isFourCC:(t[Ev]&G0)===G0,isRGB:(t[Ev]&z0)===z0,isLuminance:(t[Ev]&W0)===W0,isCube:(t[nk]&k0)===k0,isCompressed:r===H0||r===X0||r===Y0,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const a=new Float32Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,a,l){const h=new Uint8Array(s),c=new Uint8Array(r,i);let u=0;for(let d=0;d0?s.sphericalPolynomial=vu.ConvertCubeMapToSphericalPolynomial({size:d[Tv],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}}ki.StoreLODInAlphaChannel=!1;We.prototype.createPrefilteredCubeTexture=function(o,e,t,i,s=null,r=null,n,a=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 ph,u._source=Vt.CubePrefiltered,this.getCaps().textureLOD){s&&s(u);return}const d=3,f=this._gl,p=c.width;if(!p)return;const _=[];for(let g=0;g1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),ki.UploadDDSLevels(r,t,c,n,a,6,-1,h),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t):l=n.mipmapCount-1}else{const h=e;n=ki.GetDDSInfo(h),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new ph),a=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),ki.UploadDDSLevels(r,t,h,n,a,6),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t,!1):l=n.mipmapCount-1}r._setCubeMapTextureParams(t,a,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=ki.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,()=>{ki.UploadDDSLevels(t.getEngine(),t,e,s,r,1)})}}re._TextureLoaders.push(new ok);class lk{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=uy(e);if(n){t.width=n.width,t.height=n.width;try{fy(t,n),l2(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},a=>{r==null||r("Can not upload environment levels",a)})}catch(a){r==null||r("Can not upload environment file",a)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}re._TextureLoaders.push(new lk);class Da{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Da.IsValid(e)){this.isInvalid=!0,G.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){G.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){G.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){G.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){G.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=Da.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case Da.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break}}_upload2DCompressedLevels(e,t){let i=Da.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let a=0;a=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}}Da.HEADER_LEN=12+13*4;Da.COMPRESSED_2D=0;Da.COMPRESSED_3D=1;Da.TEX_2D=2;Da.TEX_3D=3;class hk{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 wm extends hk{constructor(e,t,i=wm.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{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))})})}}wm.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var tC;(function(o){o[o.ETC1S=0]="ETC1S",o[o.UASTC4x4=1]="UASTC4x4"})(tC||(tC={}));var rd;(function(o){o[o.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",o[o.BC7_RGBA=1]="BC7_RGBA",o[o.BC3_RGBA=2]="BC3_RGBA",o[o.BC1_RGB=3]="BC1_RGB",o[o.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",o[o.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",o[o.ETC2_RGBA=6]="ETC2_RGBA",o[o.ETC1_RGB=7]="ETC1_RGB",o[o.RGBA32=8]="RGBA32",o[o.R8=9]="R8",o[o.RG8=10]="RG8"})(rd||(rd={}));var zv;(function(o){o[o.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",o[o.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",o[o.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",o[o.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",o[o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",o[o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",o[o.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",o[o.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",o[o.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",o[o.RGBA8Format=32856]="RGBA8Format",o[o.R8Format=33321]="R8Format",o[o.RG8Format=33323]="RG8Format"})(zv||(zv={}));function Wv(o){o.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=o.wasmUASTCToASTC),o.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=o.wasmUASTCToBC7),o.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=o.wasmUASTCToRGBA_UNORM),o.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=o.wasmUASTCToRGBA_SRGB),o.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=o.wasmUASTCToR8_UNORM),o.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=o.wasmUASTCToRG8_UNORM),o.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=o.jsMSCTranscoder),o.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=o.wasmMSCTranscoder),o.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=o.wasmZSTDDecoder)}class ck{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:[rd.BC1_RGB,rd.BC3_RGBA],yes:{transcodeFormat:rd.RGBA32,engineFormat:zv.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Ir{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Ir._WorkerPoolPromise||Ir._DecoderModulePromise)return;const t={jsDecoderModule:fe.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:fe.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:fe.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:fe.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?Ir._WorkerPoolPromise=new Promise(i=>{const s=`${Wv}(${uk})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new wm(e,()=>new Promise((n,a)=>{const l=new Worker(r),h=u=>{l.removeEventListener("error",h),l.removeEventListener("message",c),a(u)},c=u=>{u.data.action==="init"&&(l.removeEventListener("error",h),l.removeEventListener("message",c),n(l))};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({action:"init",urls:t})})))}):typeof KTX2DECODER>"u"?Ir._DecoderModulePromise=fe.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Wv(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Ir._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=Ir.DefaultNumWorkers){this._engine=e,Ir._Initialize(t)}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(Ir._WorkerPoolPromise)return Ir._WorkerPoolPromise.then(n=>new Promise((a,l)=>{n.push((h,c)=>{const u=p=>{h.removeEventListener("error",u),h.removeEventListener("message",d),l(p),c()},d=p=>{if(p.data.action==="decoded"){if(h.removeEventListener("error",u),h.removeEventListener("message",d),!p.data.success)l({message:p.data.msg});else try{this._createTexture(p.data.decodedData,t,i),a()}catch(_){l({message:_})}c()}};h.addEventListener("error",u),h.addEventListener("message",d),h.postMessage({action:"setDefaultDecoderOptions",options:Ir.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(Ir._DecoderModulePromise)return Ir._DecoderModulePromise.then(n=>(Ir.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=Ir.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((a,l)=>{n.decode(e,s).then(h=>{this._createTexture(h,t),a()}).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=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}}Ir.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};Ir.DefaultNumWorkers=Ir.GetDefaultNumWorkers();Ir.DefaultDecoderOptions=new ck;function uk(){let o;onmessage=e=>{if(e.data)switch(e.data.action){case"init":{const t=e.data.urls;importScripts(t.jsDecoderModule),Wv(t),o=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=e.data.options;break}case"decode":o.decode(e.data.data,e.data.caps,e.data.options).then(t=>{const i=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:t})});break}}}function dk(o){switch(o){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 fk{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 Da(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Da.IsValid(e)){t._invertVScale=!t.invertY;const r=new Da(e,1),n=dk(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 Ir.IsValid(e)?new Ir(t.getEngine()).uploadAsync(e,t,s).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},n=>{G.Warn(`Failed to load KTX2 texture data: ${n.message}`),i(0,0,!1,!1,()=>{},!0)}):(G.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}re._TextureLoaders.unshift(new fk);class Md extends zn{constructor(e,t,i){super(e,T.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=Se.Identity(),this._referencedPosition=new T,this._trackingState=Oc.NOT_TRACKING,this.onXRCameraInitializedObservable=new he,this.onBeforeCameraTeleport=new he,this.onAfterCameraTeleport=new he,this.onTrackingStateChanged=new he,this.compensateOnFirstFrame=!0,this._rotate180=new Se(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new Se,this.cameraRigMode=et.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.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:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Na(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Na(.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,Se.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=K.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),Se.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(Oc.NOT_TRACKING);return}const t=e.emulatedPosition?Oc.TRACKING_LOST:Oc.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const i={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(i),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(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),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 r;const n=this.rigCameras[s];!n.isLeftCamera&&!n.isRightCamera&&(i.eye==="right"?n._isRightCamera=!0:i.eye==="left"&&(n._isLeftCamera=!0));const a=i.transform.position,l=i.transform.orientation;n.parent=this.parent,n.position.set(a.x,a.y,a.z),n.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),k.FromFloat32ArrayToRefScaled(i.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),s===0&&this._projectionMatrix.copyFrom(n._projectionMatrix);const h=this._xrSessionManager.getRenderTargetTextureForView(i);this._renderingMultiview=((r=h==null?void 0:h._texture)===null||r===void 0?void 0:r.isMultiview)||!1,this._renderingMultiview?s==0&&(this._xrSessionManager.trySetViewportForView(this.viewport,i),this.outputRenderTarget=h):(this._xrSessionManager.trySetViewportForView(n.viewport,i),n.outputRenderTarget=h||this._xrSessionManager.getRenderTargetTextureForView(i)),n.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=K.Matrix[0],t=K.Matrix[1],i=K.Matrix[2];k.ComposeToRef(Md._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),k.ComposeToRef(Md._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,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}Md._ScaleReadOnly=T.One();class qx{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 he,this.onStateChangedObservable=new he,this.state=rr.NOT_IN_XR,this.sessionManager=new xm(e),this.camera=new Md("webxr",e,this.sessionManager),this.featuresManager=new _s(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new qx(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(rr.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===void 0||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){var r,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(rr.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"&&G.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=await i.initializeXRLayerAsync(this.sessionManager.session),h={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(oi.LAYERS)||(h.baseLayer=l),this.sessionManager.updateRenderState(h),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(!((n=(r=this._nonVRCamera)===null||r===void 0?void 0:r.inputs)===null||n===void 0)&&n.attachedToElement),(a=this._nonVRCamera)===null||a===void 0||a.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!==rr.EXITING_XR&&this._setState(rr.EXITING_XR),this.camera.rigCameras.forEach(c=>{c.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(rr.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(rr.IN_XR)}),this.sessionManager}catch(l){throw G.Log(l),G.Log(l.message),this._setState(rr.NOT_IN_XR),l}}exitXRAsync(){return this.state!==rr.IN_XR?Promise.resolve():(this._setState(rr.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===rr.IN_XR?(this._spectatorCamera=new _u("webxr-spectator",T.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new Se,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(a=>{a===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===rr.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 la{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 he,this.onButtonStateChangedObservable=new he}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))}}la.BUTTON_TYPE="button";la.SQUEEZE_TYPE="squeeze";la.THUMBSTICK_TYPE="thumbstick";la.TOUCHPAD_TYPE="touchpad";la.TRIGGER_TYPE="trigger";class Tu{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=a=>{if(!a)return;const l=this.layout.components[a],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[a]=new la(a,h,c,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new he,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?G.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(a=>a.filename===t.filename&&a.path===t.path);if(n[0]){n[0].meshes.forEach(a=>a.setEnabled(!0)),r(n[0].meshes);return}}Ft.ImportMesh("",t.path,t.filename,this.scene,n=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:n})),r(n)},null,(n,a)=>{G.Log(a),G.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(a)})})}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;Se.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),T.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 se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=Se.FromEulerAngles(0,Math.PI,0)}}class Dd extends Tu{constructor(e,t,i){super(e,pk[i],t,i),this.profileId=Dd.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=Se.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Dd.ProfileId="generic-trigger";const pk={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 _k extends Tu{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=Ft.IsPluginForExtensionAvailable(".glb");return e||G.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===la.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,n)},i.type===la.TOUCHPAD_TYPE&&!this._touchDots[s]){const a=Qo(s+"dot",{diameter:.0015,segments:8},this.scene);a.material=new Oe(s+"mat",this.scene),a.material.diffuseColor=Te.Red(),a.parent=this._buttonMeshMapping[t].states[s].valueMesh||null,a.isVisible=!1,this._touchDots[s]=a}}})})}_setRootMesh(e){this.rootMesh=new se(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i{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 a=r.visualResponses[n];let l=i.value;if(a.componentProperty==="xAxis"?l=i.axes.x:a.componentProperty==="yAxis"&&(l=i.axes.y),a.valueNodeProperty==="transform")this._lerpTransform(s.states[n],l,a.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 Sv=[];class vr{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,a=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return n.call(this,s,e,t).catch(()=>a.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=fe.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){Sv.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),Sv.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(s=>{for(let r=0;r(this._ProfileLoadingPromises[s]||(this._ProfileLoadingPromises[s]=fe.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${s}/profile.json`,!1).then(r=>JSON.parse(r))),this._ProfileLoadingPromises[s])).then(s=>new _k(i,t,s,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Sv))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew Dd(e,o.gamepad,o.handedness));vr.DefaultFallbacks();let mk=0;class gk{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new T,this._disposed=!1,this.onDisposeObservable=new he,this.onMeshLoadedObservable=new he,this.onMotionControllerInitObservable=new he,this._uniqueId=`controller-${mk++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new hi(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new Se,this.inputSource.gripSpace&&(this.grip=new hi(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new Se),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&vr.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(a=>a.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===void 0||n.dispose())})},()=>{fe.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;T.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const r=s.transform.position;this.pointer.position.set(r.x,r.y,r.z);const n=s.transform.orientation;this.pointer.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const n=r.transform.position,a=r.transform.orientation;this.grip.position.set(n.x,n.y,n.z),this.grip.rotationQuaternion.set(a.x,a.y,a.z,a.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class vk{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new he,this.onControllerRemovedObservable=new he,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._options.customControllersRepositoryURL&&(vr.BaseRepositoryUrl=this._options.customControllersRepositoryURL),vr.UseOnlineRepository=!this._options.disableOnlineControllerRepository,vr.UseOnlineRepository)try{vr.UpdateProfilesList().catch(()=>{vr.UseOnlineRepository=!1})}catch{vr.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(n=>n.inputSource);for(const n of e)if(i.indexOf(n)===-1){const a=new gk(this.xrSessionManager.scene,n,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(a),this.onControllerAddedObservable.notifyObservers(a)}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(),vr.ClearControllerCache()}}class qo extends Cr{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:s,selectionMesh:r}=this._generateNewMeshPair(i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:s,selectionMesh:r,meshUnderPointer:null,pick:null,tmpRay:new Kt(new T,new T),disabledByNearInteraction:!1,id:qo._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":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new T,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Te(.9,.9,.9),this.laserPointerDefaultColor=new Te(.7,.7,.7),this.selectionMeshDefaultColor=new Te(.8,.8,.8),this.selectionMeshPickedColor=new Te(.3,.3,1),this._identityMatrix=k.Identity(),this._screenCoordinatesRef=T.Zero(),this._viewportRef=new Na(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Kt(new T,new T),disabledByNearInteraction:!1,id:qo._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{const i=this._controllers[t];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=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);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 l=this._xrSessionManager.scene,h=this._options.xrInput.xrCamera;h&&(h.viewport.toGlobalToRef(l.getEngine().getRenderWidth(),l.getEngine().getRenderHeight(),this._viewportRef),T.ProjectToRef(s,this._identityMatrix,l.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&(l.pointerX=this._screenCoordinatesRef.x,l.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{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,a=0;else if(a>i/10&&(n.isVisible=!0),a+=this._scene.getEngine().getDeltaTime(),a>=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-a/i;n.scaling.set(c,c,c)}else l=!1,a=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 a=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),a?(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)):a&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)}})};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=n=>{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._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(T.Dot(e,t.direction)){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 Vr,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{fe.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Cm("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new Oe("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():$h("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new Oe("targetMat",t);return n.specularColor=Te.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 i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(i=e.pickedPoint)===null||i===void 0||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const s=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>s}_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}}qo._IdCounter=200;qo.Name=oi.POINTER_SELECTION;qo.Version=1;_s.AddWebXRFeature(qo.Name,(o,e)=>()=>new qo(o,e),qo.Version,!0);on.prototype._projectOnTrianglesToRef=function(o,e,t,i,s,r){const n=K.Vector3[0],a=K.Vector3[1];let l=1/0;for(let h=this.indexStart;h{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),a=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n,currentAnimationState:ea.DEHYDRATED,grabRay:new Kt(new T,new T),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:jo._IdCounter++,pickedPointVisualCue:a},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 Te(.8,.8,.8),this.selectionMeshPickedColor=new Te(.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=Fh.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;ie.currentAnimationState)switch(e.currentAnimationState){case ea.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===ea.HOVER)break;case ea.HOVER:if(e.touchCollisionMeshFunction(!0),t===ea.TOUCH)break}else switch(e.currentAnimationState){case ea.TOUCH:if(e.touchCollisionMeshFunction(!1),t===ea.HOVER)break;case ea.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===ea.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var s;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(K.Vector3[0]),r.grabRay.direction.copyFrom(K.Vector3[0]),this._options.nearInteractionControllerMode===Fh.CENTERED_IN_FRONT&&!(!((s=r.xrController)===null||s===void 0)&&s.inputSource.hand)&&(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;const s=this._controllers[t],r=(i=s.xrController)===null||i===void 0?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!s.xrController||!r&&(!this._options.nearInteractionControllerMode||!s.xrController.inputSource.gamepad)){s.pick=null;return}if(s.hoverInteraction=!1,s.nearInteraction=!1,s.xrController){if(r){const h=r.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;K.Vector3[0].set(c.transform.position.x,c.transform.position.y,c.transform.position.z*u),K.Quaternion[0].set(c.transform.orientation.x,c.transform.orientation.y,c.transform.orientation.z*u,c.transform.orientation.w*u),this._processTouchPoint(t,K.Vector3[0],K.Quaternion[0])}}}else if(s.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==Fh.DISABLED){let h=s.xrController.pointer;s.xrController.grip&&this._options.nearInteractionControllerMode===Fh.CENTERED_ON_CONTROLLER&&(h=s.xrController.grip),this._processTouchPoint(t,h.position,h.rotationQuaternion)}}else return;const n=(h,c)=>{let u=null;return!c||!c.hit?u=h:!h||!h.hit||c.distance{let c=new Vr,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(!s.grabInteraction){let h=null,c=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(c=this._pickWithSphere(s,this._hoverRadius,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const u=this._pickWithSphere(s,this._hoverRadius,this._scene,f=>this._nearInteractionPredicate(f)),d=n(u,c);if(d&&d.hit&&(h=a(d),h.hit&&(s.hoverInteraction=!0)),s.hoverInteraction){let f=null;const p=r?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(s,p,this._utilityLayerScene,E=>this._nearPickPredicate(E)));const _=this._pickWithSphere(s,p,this._scene,E=>this._nearPickPredicate(E)),g=n(_,f),v=a(g);v.hit&&(h=v,s.nearInteraction=!0)}s.stalePick=s.pick,s.pick=h,s.pick&&s.pick.pickedPoint&&s.pick.hit?(s.meshUnderPointer=s.pick.pickedMesh,s.pickedPointVisualCue.position.copyFrom(s.pick.pickedPoint),s.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!0)):(s.meshUnderPointer=null,s.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!1))}let l=ea.DEHYDRATED;s.grabInteraction||s.nearInteraction?l=ea.TOUCH:s.hoverInteraction&&(l=ea.HOVER),this._handleTransitionAnimation(s,l)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("nearInteraction",{diameter:.0035*3},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=Se.Identity();const i=new Oe("targetMat",e);return i.specularColor=Te.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.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),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)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),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(a=>{if(a.changes.pressed){const l=a.changes.pressed.current;s(l)}}):(t.selectionComponent=n.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(a=>{if(a.changes.pressed){const l=a.changes.pressed.current;s(l)}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=a=>{t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=a=>{t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart: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(()=>{const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Vr,i)}),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._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:ys.ParseFromSnippetAsync("8RUNKL#3",e).then(I=>{t.material=I});const i=new Vw;i.setEasingMode(ln.EASINGMODE_EASEINOUT);const s=new T(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),r=this._controllerPickRadius*(4/3),n=new T(r,r,r),a=this._controllerPickRadius*(7/6),l=new T(a,a,a),h=this._controllerPickRadius*(4/5),c=new T(h,h,h),u=this._controllerPickRadius*(3/2),d=new T(u,u,u),f=[{frame:0,value:s},{frame:10,value:d},{frame:18,value:n}],p=[{frame:0,value:n},{frame:10,value:c},{frame:18,value:s}],_=[{frame:0,value:T.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],g=[{frame:0,value:s},{frame:10,value:T.ZeroReadOnly},{frame:15,value:T.ZeroReadOnly}],v=new Ee("touch","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),E=new Ee("release","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),C=new Ee("hydrate","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),S=new Ee("dehydrate","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT);return v.setEasingFunction(i),E.setEasingFunction(i),C.setEasingFunction(i),S.setEasingFunction(i),v.setKeys(f),E.setKeys(p),C.setKeys(_),S.setKeys(g),{touchCollisionMesh:t,touchCollisionMeshFunction:I=>{const N=I?v:E;e.beginDirectAnimation(t,[N],0,18,!1,1)},hydrateCollisionMeshFunction:I=>{const N=I?C:S;I&&(t.isVisible=!0),e.beginDirectAnimation(t,[N],0,15,!1,1,()=>{I||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,s){const r=new Vr;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,a=Rl.CreateFromCenterAndRadius(n,t);for(let l=0;lu&&(c=0,l.copyFrom(t.center)),c!==-1&&c()=>new jo(o,e),jo.Version,!0);class xk{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class jx{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new he,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 fe.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 a=".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) }";a+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l);const h=document.createElement("button");h.className="babylonVRicon",h.title=`${s} - ${r}`,this._buttons.push(new xk(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==rr.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)):fe.Warn(`Session mode "${this._buttons[n].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const s=new jx(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==rr.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==rr.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 Lh;(function(o){o[o.INIT=0]="INIT",o[o.STARTED=1]="STARTED",o[o.ENDED=2]="ENDED"})(Lh||(Lh={}));function iC(o){var e;let t=0;const i=Date.now();o.observableParameters=(e=o.observableParameters)!==null&&e!==void 0?e:{};const s=o.contextObservable.add(r=>{const n=Date.now();t=n-i;const a={startTime:i,currentTime:n,deltaTime:t,completeRate:t/o.timeout,payload:r};o.onTick&&o.onTick(a),o.breakCondition&&o.breakCondition()&&(o.contextObservable.remove(s),o.onAborted&&o.onAborted(a)),t>=o.timeout&&(o.contextObservable.remove(s),o.onEnded&&o.onEnded(a))},o.observableParameters.mask,o.observableParameters.insertFirst,o.observableParameters.scope);return s}class Tk{constructor(e){var t,i;this.onEachCountObservable=new he,this.onTimerAbortedObservable=new he,this.onTimerEndedObservable=new he,this.onStateChangedObservable=new he,this._observer=null,this._breakOnNextTick=!1,this._tick=s=>{const r=Date.now();this._timer=r-this._startTime;const n={startTime:this._startTime,currentTime:r,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:s},a=this._breakOnNextTick||this._breakCondition(n);a||this._timer>=this._timeToEnd?this._stop(n,a):this.onEachCountObservable.notifyObservers(n)},this._setState(Lh.INIT),this._contextObservable=e.contextObservable,this._observableParameters=(t=e.observableParameters)!==null&&t!==void 0?t:{},this._breakCondition=(i=e.breakCondition)!==null&&i!==void 0?i:()=>!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===Lh.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(Lh.STARTED)}stop(){this._state===Lh.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(Lh.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Wc extends Cr{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 Ze(1,1,1,1),this._tmpRay=new Kt(new T,new T),this._tmpVector=new T,this._tmpQuaternion=new Se,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 he,this.teleportationEnabled=!0,this._rotationEnabled=!0,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}};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(la.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(la.TOUCHPAD_TYPE);if(!n||this._options.useMainComponentOnly){const a=i.motionController.getMainComponent();if(!a)return;s.teleportationComponent=a,s.onButtonChangedObserver=a.onButtonStateChangedObservable.add(()=>{if(this.teleportationEnabled&&a.changes.pressed)if(a.changes.pressed.current){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const l=this._options.timeToTeleport||3e3;iC({timeout:l,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!a.pressed,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else s.teleportationState.forward=!1,this._currentTeleportationControllerId=""})}else s.teleportationComponent=n,s.onAxisChangedObserver=n.onAxisValueChangedObservable.add(a=>{if(a.y<=.7&&s.teleportationState.backwards&&(s.teleportationState.backwards=!1),a.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,Se.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(a.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),a.x){if(s.teleportationState.forward)this._currentTeleportationControllerId===s.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{s.teleportationState.currentRotation=Math.atan2(a.x,a.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):s.teleportationState.currentRotation=0);else if(!s.teleportationState.rotating&&Math.abs(a.x)>.7){s.teleportationState.rotating=!0;const l=this.rotationAngle*(a.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);Se.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else s.teleportationState.rotating=!1;a.x===0&&a.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 this._xrSessionManager.scene.onPointerObservable.add(r=>{if(r.type===rt.POINTERDOWN){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const n=this._options.timeToTeleport||3e3;iC({timeout:n,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else r.type===rt.POINTERUP&&(s.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ze(1,0,0,.75),this._setTargetMeshVisibility(!1)}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)}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{if(this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(l)!==-1)return!0;const h=this._floorMeshes.indexOf(l);return h===-1?!1:this._floorMeshes[h].absolutePosition.ythis._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(u)!==-1?!0:this._floorMeshes.indexOf(u)!==-1);if(c&&c.pickedMesh&&this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(c.pickedMesh)!==-1){r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(c);return}else c&&c.pickedPoint&&(r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(c),this._setTargetMeshVisibility(!0),this._showParabolicPath(c))}this._setTargetMeshVisibility(n)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Tm("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 Id("teleportationPlaneDynamicTexture",512,e,!0);n.hasAlpha=!0;const a=n.getContext(),l=512/2,h=512/2,c=200;a.beginPath(),a.arc(l,h,c,0,2*Math.PI,!1),a.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",a.fill(),a.lineWidth=10,a.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",a.stroke(),a.closePath(),n.update();const u=new Oe("teleportationPlaneMaterial",e);u.diffuseTexture=n,t.material=u}const i=$h("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const r=new Ee("animationInnerCircle","position.y",30,Ee.ANIMATIONTYPE_FLOAT,Ee.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 a=new mb;a.setEasingMode(ln.EASINGMODE_EASEINOUT),r.setEasingFunction(a),i.animations=[],i.animations.push(r),e.beginAnimation(i,0,60,!0)}const s=Cm("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(an.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 Oe("torusConsMat",e);r.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,r.disableLighting?r.emissiveColor=new Te(.3,.3,1):r.diffuseColor=new Te(.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._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 a=T.DistanceSquared(n,e);a<=r&&a{i.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&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||zs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=Lo.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=new Array(26).fill(r||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=ym("teleportation path line",{points:s.getPoints(),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._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,Se.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}Wc.Name=oi.TELEPORTATION;Wc.Version=1;_s.AddWebXRFeature(Wc.Name,(o,e)=>()=>new Wc(o,e),Wc.Version,!0);class Qx{constructor(){}static CreateAsync(e,t={}){const i=new Qx;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const s=Object.assign({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 jx(e,s)}return qx.CreateAsync(e).then(s=>{if(i.baseExperience=s,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new vk(s.sessionManager,s.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){const r=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(qo.Name,t.useStablePlugins?"stable":"latest",r),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Wc.Name,t.useStablePlugins?"stable":"latest",Object.assign({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(jo.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(s=>(G.Error("Error initializing XR"),G.Error(s),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}Qe.prototype.createDefaultLight=function(o=!1){if(o&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),s=i.max.subtract(i.min),r=i.min.add(s.scale(.5));let n,a=s.length()*1.5;if(isFinite(a)||(a=1,r.copyFromFloats(0,0,0)),o){const l=new Ji("default camera",-(Math.PI/2),Math.PI/2,a,r,this);l.lowerRadiusLimit=a*.01,l.wheelPrecision=100/a,n=l}else{const l=new zn("default camera",new T(r.x,r.y,-a),this);l.setTarget(r),n=l}n.minZ=a*.01,n.maxZ=a*1e3,n.speed=a*.2,this.activeCamera=n,t&&n.attachControl()}};Qe.prototype.createDefaultCameraOrLight=function(o=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(o,e,t)};Qe.prototype.createDefaultSkybox=function(o,e=!1,t=1e3,i=0,s=!0){if(!o)return G.Warn("Can not create default skybox without environment texture."),null;s&&o&&(this.environmentTexture=o);const r=bm("hdrSkyBox",{size:t},this);if(e){const n=new Rt("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=o.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=ee.SKYBOX_MODE),n.microSurface=1-i,n.disableLighting=!0,n.twoSidedLighting=!0,r.material=n}else{const n=new Oe("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=o.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=ee.SKYBOX_MODE),n.disableLighting=!0,r.material=n}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r};Qe.prototype.createDefaultEnvironment=function(o){return jh?new jh(o,this):null};Qe.prototype.createDefaultVRExperience=function(o={}){return new Jc(this,o)};Qe.prototype.createDefaultXRExperienceAsync=function(o={}){return Qx.CreateAsync(this,o).then(e=>e)};function sC(o){for(;o.firstChild;)o.removeChild(o.firstChild);o.srcObject=null,o.src="",o.removeAttribute("src")}class Ml extends ee{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new he),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):G.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){G.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=ee.TRILINEAR_SAMPLINGMODE,a={},l,h=5){var c;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=()=>{var d;this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||fe.IsExponentOfTwo(this.video.videoWidth)&&fe.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=ee.WRAP_ADDRESSMODE,this.wrapV=ee.WRAP_ADDRESSMODE):(this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=(d=this._format)!==null&&d!==void 0?d: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._settings.poster&&(!this._settings.autoPlay||!u)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):u&&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 fe.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(fe.SetCorsBehavior(e,t),t.src=e):(fe.SetCorsBehavior(e[0],t),e.forEach(i=>{const s=document.createElement("source");s.src=i,t.appendChild(s)})),this.onDisposeObservable.addOnce(()=>{sC(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 Ml(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)===null||e===void 0||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 a=()=>{const l=new Ml("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{r.remove()}),l.onDisposeObservable.addOnce(()=>{sC(r)}),n(l),r.removeEventListener("playing",a)};r.addEventListener("playing",a),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(a=>{a.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){G.Error(n.name)})}}A([D("settings")],Ml.prototype,"_settings",void 0);A([D("src")],Ml.prototype,"_currentSrc",void 0);A([D()],Ml.prototype,"isVideo",void 0);ee._CreateVideoTexture=(o,e,t,i=!1,s=!1,r=ee.TRILINEAR_SAMPLINGMODE,n={},a,l=5)=>new Ml(o,e,t,i,s,r,n,a,l);j("BABYLON.VideoTexture",Ml);class Zx extends In{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 Ml((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,ee.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(n=>{var a;((a=n.pickInfo)===null||a===void 0?void 0:a.pickedMesh)===this.mesh&&this._texture.video.play()},rt.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)}}Zx.MODE_MONOSCOPIC=In.MODE_MONOSCOPIC;Zx.MODE_TOPBOTTOM=In.MODE_TOPBOTTOM;Zx.MODE_SIDEBYSIDE=In.MODE_SIDEBYSIDE;const Ek="glowMapGenerationPixelShader",Sk=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +}`;ne.ShadersStore[X3]=Y3;class $3 extends Wn{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 Tr extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new $3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Tr._DefaultIndexOfRefraction,this.indexOfRefraction=Tr._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=Te.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&&we.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&we.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&we.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.ClearCoatTextureEnabled?Me.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&we.ClearCoatTextureEnabled?Me.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&we.ClearCoatBumpTextureEnabled?Me.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Tr._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&we.ClearCoatTintTextureEnabled?(Me.PrepareDefinesForMergedUV(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 r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,g=this._material._invertNormalMapX,v=this._material._invertNormalMapY,E=f.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){E&&we.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&we.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._textureRoughness)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"clearCoat"),this._textureRoughness&&!E&&!f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&we.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Me.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",g?1:-1,v?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",g?-1:1,v?-1:1)),this._tintTexture&&we.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Me.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const C=1-this._indexOfRefraction,S=1+this._indexOfRefraction,b=Math.pow(-C/S,2),R=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",b,R,C,S),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&&we.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!E&&!f.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&we.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&we.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&we.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===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||i.dispose(),(s=this._bumpTexture)===null||s===void 0||s.dispose(),(r=this._tintTexture)===null||r===void 0||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"}]}}}Tr._DefaultIndexOfRefraction=1.5;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"isEnabled",void 0);A([D()],Tr.prototype,"intensity",void 0);A([D()],Tr.prototype,"roughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"indexOfRefraction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"useRoughnessFromMainTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"textureRoughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"remapF0OnInterfaceChange",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"bumpTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"isTintEnabled",void 0);A([ds()],Tr.prototype,"tintColor",void 0);A([D()],Tr.prototype,"tintColorAtDistance",void 0);A([D()],Tr.prototype,"tintThickness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Tr.prototype,"tintTexture",void 0);class K3 extends Wn{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 gn extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new K3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=gn._DefaultMinimumThickness,this.maximumThickness=gn._DefaultMaximumThickness,this.indexOfRefraction=gn._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&&we.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.IridescenceTextureEnabled?Me.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&we.IridescenceTextureEnabled?Me.PrepareDefinesForMergedUV(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,s){var r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;(!e.useUbo||!p||!e.isSync)&&(_&&we.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&we.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._thicknessTexture)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._thicknessTexture)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"iridescence"),this._thicknessTexture&&!_&&!f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&we.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!f.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&we.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===void 0||t.dispose(),(i=this._thicknessTexture)===null||i===void 0||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"}]}}}gn._DefaultMinimumThickness=100;gn._DefaultMaximumThickness=400;gn._DefaultIndexOfRefraction=1.3;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],gn.prototype,"isEnabled",void 0);A([D()],gn.prototype,"intensity",void 0);A([D()],gn.prototype,"minimumThickness",void 0);A([D()],gn.prototype,"maximumThickness",void 0);A([D()],gn.prototype,"indexOfRefraction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],gn.prototype,"texture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],gn.prototype,"thicknessTexture",void 0);class q3 extends Wn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class xu extends ca{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 q3,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Re(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&&we.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(P.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.AnisotropicTextureEnabled?Me.PrepareDefinesForMergedUV(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&&we.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Me.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&we.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)}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],xu.prototype,"isEnabled",void 0);A([D()],xu.prototype,"intensity",void 0);A([rx()],xu.prototype,"direction",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],xu.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],xu.prototype,"legacy",void 0);class j3 extends Wn{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 tl extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new j3,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Te.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&&we.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&we.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||i===void 0?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&we.SheenTextureEnabled?(Me.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&we.SheenTextureEnabled?Me.PrepareDefinesForMergedUV(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){var r,n,a,l,h,c,u,d;if(!this._isEnabled)return;const f=s.materialDefines,p=this._material.isFrozen,_=f.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;(!e.useUbo||!p||!e.isSync)&&(_&&we.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),Me.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&we.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(n=(r=this._texture)===null||r===void 0?void 0:r.coordinatesIndex)!==null&&n!==void 0?n:0,(l=(a=this._texture)===null||a===void 0?void 0:a.level)!==null&&l!==void 0?l:0,(c=(h=this._textureRoughness)===null||h===void 0?void 0:h.coordinatesIndex)!==null&&c!==void 0?c:0,(d=(u=this._textureRoughness)===null||u===void 0?void 0:u.level)!==null&&d!==void 0?d:0),this._texture&&Me.BindTextureMatrix(this._texture,e,"sheen"),this._textureRoughness&&!_&&!f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Me.BindTextureMatrix(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&&we.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!f.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&we.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===void 0||t.dispose(),(i=this._textureRoughness)===null||i===void 0||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"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"isEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"linkSheenWithAlbedo",void 0);A([D()],tl.prototype,"intensity",void 0);A([ds()],tl.prototype,"color",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"texture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"useRoughnessFromMainTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"roughness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"textureRoughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],tl.prototype,"albedoScaling",void 0);class Q3 extends Wn{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 As extends ca{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 Q3,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=Te.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Te.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&&we.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&we.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&&we.ThicknessTextureEnabled&&Me.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&!r&&Me.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&!r&&Me.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&r,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&r,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&r,this._isRefractionEnabled&&t.texturesEnabled){const n=this._getRefractionTexture(t);n&&we.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(K.Vector3[0]);const r=Math.max(Math.abs(K.Vector3[0].x),Math.abs(K.Vector3[0].y),Math.abs(K.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,a=this._material.realTimeFiltering,l=r.LODBASEDMICROSFURACE,h=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&we.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Me.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Me.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Me.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),h&&we.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),a&&e.updateFloat2("vRefractionFilteringInfo",u,ye.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&&we.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&we.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&we.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),h&&we.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){we.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(we.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"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isRefractionEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isTranslucencyEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"isDispersionEnabled",void 0);A([D(),Ce("_markScenePrePassDirty")],As.prototype,"isScatteringEnabled",void 0);A([D()],As.prototype,"_scatteringDiffusionProfileIndex",void 0);A([D()],As.prototype,"refractionIntensity",void 0);A([D()],As.prototype,"translucencyIntensity",void 0);A([D()],As.prototype,"useAlbedoToTintRefraction",void 0);A([D()],As.prototype,"useAlbedoToTintTranslucency",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"thicknessTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"refractionTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"indexOfRefraction",void 0);A([D()],As.prototype,"_volumeIndexOfRefraction",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"volumeIndexOfRefraction",null);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"invertRefractionY",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"linkRefractionWithTransparency",void 0);A([D()],As.prototype,"minimumThickness",void 0);A([D()],As.prototype,"maximumThickness",void 0);A([D()],As.prototype,"useThicknessAsDepth",void 0);A([ds()],As.prototype,"tintColor",void 0);A([D()],As.prototype,"tintColorAtDistance",void 0);A([D()],As.prototype,"dispersion",void 0);A([ds()],As.prototype,"diffusionDistance",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"useMaskFromThicknessTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"refractionIntensityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"translucencyIntensityTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],As.prototype,"useGltfStyleTextures",void 0);const Rc={effect:null,subMesh:null};class k0 extends Wn{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 Ni extends ep{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 Dt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Ni.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=Te.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Te(0,0,0),this._albedoColor=new Te(1,1,1),this._reflectivityColor=new Te(1,1,1),this._reflectionColor=new Te(1,1,1),this._emissiveColor=new Te(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=Ni.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 qs(16),this._globalAmbientColor=new Te(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 rn(this),this.clearCoat=new Tr(this),this.iridescence=new gn(this),this.anisotropy=new xu(this),this.sheen=new tl(this),this.subSurface=new As(this),this.detailMap=new Eh(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),we.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=jx(this.getScene()),this.prePassConfiguration=new P_}get hasRenderTargetTextures(){return we.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===Ni.PBRMATERIAL_OPAQUE||this._transparencyMode===Ni.PBRMATERIAL_ALPHATEST||((e=this.subSurface)===null||e===void 0?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===void 0)&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ni.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Ni.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var s;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo),t.materialDefines=new k0(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),a=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&we.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&we.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&we.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const d=this._getReflectionTexture();if(d&&we.ReflectionTextureEnabled){if(!d.isReadyOrNotBlocking())return!1;if(d.irradianceTexture){if(!d.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!d.sphericalPolynomial&&(!((s=d.getInternalTexture())===null||s===void 0)&&s._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&we.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&we.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(we.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(a.getCaps().standardDerivatives&&this._bumpTexture&&we.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&we.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;!a.getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),G.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&&(Rc.effect=c,Rc.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Rc)),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(),t.effect._wasPreviouslyReady=!u,t.effect._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,a){if(this._prepareDefines(e,t,r,n,a),!t.isDirty)return null;t.markAsProcessed();const h=this.getScene().getEngine(),c=new ec;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=Me.HandleFallbacksForShadows(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=[P.PositionKind];t.NORMAL&&d.push(P.NormalKind),t.TANGENT&&d.push(P.TangentKind);for(let b=1;b<=6;++b)t["UV"+b]&&d.push(`uv${b===1?"":b}`);t.VERTEXCOLOR&&d.push(P.ColorKind),Me.PrepareAttributesForBones(d,e,t,c),Me.PrepareAttributesForInstances(d,t),Me.PrepareAttributesForMorphTargets(d,e,t),Me.PrepareAttributesForBakedVertexAnimation(d,e,t);let f="pbr";const p=["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"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],g=["Material","Scene","Mesh"],v={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=g,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=v,this._callbackPluginEventGeneric(Lr.PrepareEffect,this._eventInfo),P_.AddUniforms(p),Ao(p),jt&&(jt.PrepareUniforms(p,t),jt.PrepareSamplers(_,t)),Me.PrepareUniformsAndSamplersList({uniformsNames:p,uniformBuffersNames:g,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const E={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,g,_,t,d,E));const C=t.toString(),S=h.createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:g,samplers:_,defines:C,fallbacks:c,onCompiled:i,onError:s,indexParameters:v,processFinalCode:E.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},h);return this._eventInfo.customCode=void 0,S}_prepareDefines(e,t,i=null,s=null,r=!1){var n;const a=this.getScene(),l=a.getEngine();Me.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Me.PrepareDefinesForMultiview(a,t);const h=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Me.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!h),Me.PrepareDefinesForOIT(a,t,h),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let c=1;c<=6;++c)t["MAINUV"+c]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,l.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&we.DiffuseTextureEnabled?(Me.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&we.AmbientTextureEnabled?(Me.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&we.OpacityTextureEnabled?(Me.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const c=this._getReflectionTexture();if(c&&we.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,l._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=c.coordinatesMode===ee.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 ee.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case ee.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case ee.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case ee.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case ee.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case ee.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ee.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ee.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ee.CUBIC_MODE:case ee.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!c.boundingBoxSize;break}c.coordinatesMode!==ee.SKYBOX_MODE&&(c.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):c.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.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&&we.LightmapTextureEnabled?(Me.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&we.EmissiveTextureEnabled?(Me.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,we.SpecularTextureEnabled){if(this._metallicTexture?(Me.PrepareDefinesForMergedUV(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Me.PrepareDefinesForMergedUV(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture){const u=this._metallicReflectanceTexture!==null&&this._metallicReflectanceTexture._texture===((n=this._reflectanceTexture)===null||n===void 0?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!u,this._metallicReflectanceTexture?(Me.PrepareDefinesForMergedUV(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)?(Me.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?Me.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;l.getCaps().standardDerivatives&&this._bumpTexture&&we.BumpTextureEnabled&&!this._disableBumpMap?(Me.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&we.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.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&&we.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===Ni.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Ni.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=l.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&&(Me.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(P.NormalKind),t.DEBUGMODE=this._debugMode),Me.PrepareDefinesForFrameBoundValues(a,l,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Me.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==Ni.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Lr.GetDefineNames,this._eventInfo);const r=new k0(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Rc.effect=n,Rc.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Rc)),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 s,r,n,a;const l=this.getScene(),h=i.materialDefines;if(!h)return;const c=i.effect;if(!c)return;this._activeEffect=c,t.getMeshUniformBuffer().bindToEffect(c,"Mesh"),t.transferToEffect(e);const u=l.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,l,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),h.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const d=c._forceRebindOnNextCall||this._mustRebind(l,c,t.visibility);Me.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let f=null;const p=this._uniformBuffer;if(d){if(this.bindViewProjection(c),f=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||c._forceRebindOnNextCall){if(l.texturesEnabled){if(this._albedoTexture&&we.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Me.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&we.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Me.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&we.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Me.BindTextureMatrix(this._opacityTexture,p,"opacity")),f&&we.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",f.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",f.level,0),f.boundingBoxSize){const _=f;p.updateVector3("vReflectionPosition",_.boundingBoxPosition),p.updateVector3("vReflectionSize",_.boundingBoxSize)}if(this.realTimeFiltering){const _=f.getSize().width;p.updateFloat2("vReflectionFilteringInfo",_,ye.Log2(_))}if(!h.USEIRRADIANCEMAP){const _=f.sphericalPolynomial;if(h.USESPHERICALFROMREFLECTIONMAP&&_)if(h.SPHERICAL_HARMONICS){const g=_.preScaledHarmonics;p.updateVector3("vSphericalL00",g.l00),p.updateVector3("vSphericalL1_1",g.l1_1),p.updateVector3("vSphericalL10",g.l10),p.updateVector3("vSphericalL11",g.l11),p.updateVector3("vSphericalL2_2",g.l2_2),p.updateVector3("vSphericalL2_1",g.l2_1),p.updateVector3("vSphericalL20",g.l20),p.updateVector3("vSphericalL21",g.l21),p.updateVector3("vSphericalL22",g.l22)}else p.updateFloat3("vSphericalX",_.x.x,_.x.y,_.x.z),p.updateFloat3("vSphericalY",_.y.x,_.y.y,_.y.z),p.updateFloat3("vSphericalZ",_.z.x,_.z.y,_.z.z),p.updateFloat3("vSphericalXX_ZZ",_.xx.x-_.zz.x,_.xx.y-_.zz.y,_.xx.z-_.zz.z),p.updateFloat3("vSphericalYY_ZZ",_.yy.x-_.zz.x,_.yy.y-_.zz.y,_.yy.z-_.zz.z),p.updateFloat3("vSphericalZZ",_.zz.x,_.zz.y,_.zz.z),p.updateFloat3("vSphericalXY",_.xy.x,_.xy.y,_.xy.z),p.updateFloat3("vSphericalYZ",_.yz.x,_.yz.y,_.yz.z),p.updateFloat3("vSphericalZX",_.zx.x,_.zx.y,_.zx.z)}p.updateFloat3("vReflectionMicrosurfaceInfos",f.getSize().width,f.lodGenerationScale,f.lodGenerationOffset)}this._emissiveTexture&&we.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Me.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&we.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Me.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),we.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Me.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Me.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Me.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&h.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Me.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Me.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&we.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Me.BindTextureMatrix(this._bumpTexture,p,"bump"),l._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),h.METALLICWORKFLOW){gi.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,gi.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,p.updateColor4("vReflectivityColor",gi.Color3[0],1);const _=(r=(s=this.subSurface)===null||s===void 0?void 0:s._indexOfRefraction)!==null&&r!==void 0?r:1.5,g=1,v=Math.pow((_-g)/(_+g),2);this._metallicReflectanceColor.scaleToRef(v*this._metallicF0Factor,gi.Color3[0]);const E=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",gi.Color3[0],E)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",we.EmissiveTextureEnabled?this._emissiveColor:Te.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!h.SS_REFRACTION&&(!((n=this.subSurface)===null||n===void 0)&&n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*l.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),l.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}l.texturesEnabled&&(this._albedoTexture&&we.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&we.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&we.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),f&&we.ReflectionTextureEnabled&&(h.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",f):(p.setTexture("reflectionSampler",f._lodTextureMid||f),p.setTexture("reflectionSamplerLow",f._lodTextureLow||f),p.setTexture("reflectionSamplerHigh",f._lodTextureHigh||f)),h.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",f.irradianceTexture)),h.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&we.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&we.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),we.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&h.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&we.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),so(this._activeEffect,this,l),this.bindEyePosition(c)}else l.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(d||!this.isFrozen)&&(l.lightsEnabled&&!this._disableLighting&&Me.BindLights(l,t,this._activeEffect,h,this._maxSimultaneousLights),(l.fogEnabled&&t.applyFog&&l.fogMode!==Qe.FOGMODE_NONE||f||this.subSurface.refractionTexture||t.receiveShadows||h.PREPASS)&&this.bindView(c),Me.BindFogParameters(l,t,this._activeEffect,!0),h.NUM_MORPH_INFLUENCERS&&Me.BindMorphTargetParameters(t,this._activeEffect),h.BAKED_VERTEX_ANIMATION_TEXTURE&&((a=t.bakedVertexAnimationManager)===null||a===void 0||a.bind(c,h.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Me.BindLogDepth(h,this._activeEffect,l)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var e;if(!(!((e=this.subSurface)===null||e===void 0)&&e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,s,r,n,a,l,h,c,u,d,f,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(a=this._emissiveTexture)===null||a===void 0||a.dispose(),(l=this._metallicTexture)===null||l===void 0||l.dispose(),(h=this._reflectivityTexture)===null||h===void 0||h.dispose(),(c=this._bumpTexture)===null||c===void 0||c.dispose(),(u=this._lightmapTexture)===null||u===void 0||u.dispose(),(d=this._metallicReflectanceTexture)===null||d===void 0||d.dispose(),(f=this._reflectanceTexture)===null||f===void 0||f.dispose(),(p=this._microSurfaceTexture)===null||p===void 0||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Ni.PBRMATERIAL_OPAQUE=Ie.MATERIAL_OPAQUE;Ni.PBRMATERIAL_ALPHATEST=Ie.MATERIAL_ALPHATEST;Ni.PBRMATERIAL_ALPHABLEND=Ie.MATERIAL_ALPHABLEND;Ni.PBRMATERIAL_ALPHATESTANDBLEND=Ie.MATERIAL_ALPHATESTANDBLEND;Ni.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Ni.LIGHTFALLOFF_PHYSICAL=0;Ni.LIGHTFALLOFF_GLTF=1;Ni.LIGHTFALLOFF_STANDARD=2;A([JC()],Ni.prototype,"_imageProcessingConfiguration",void 0);A([Ce("_markAllSubMeshesAsMiscDirty")],Ni.prototype,"debugMode",void 0);class Rt extends Ni{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===Ni.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ni.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Ni.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Ni.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ni.LIGHTFALLOFF_GLTF:this._lightFalloff=Ni.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=Rt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Te.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Te(0,0,0),this.albedoColor=new Te(1,1,1),this.reflectivityColor=new Te(1,1,1),this.reflectionColor=new Te(1,1,1),this.emissiveColor=new Te(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=jx(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Xe.Clone(()=>new Rt(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=Xe.Parse(()=>new Rt(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ie._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}}Rt.PBRMATERIAL_OPAQUE=Ni.PBRMATERIAL_OPAQUE;Rt.PBRMATERIAL_ALPHATEST=Ni.PBRMATERIAL_ALPHATEST;Rt.PBRMATERIAL_ALPHABLEND=Ni.PBRMATERIAL_ALPHABLEND;Rt.PBRMATERIAL_ALPHATESTANDBLEND=Ni.PBRMATERIAL_ALPHATESTANDBLEND;Rt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Ni.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"directIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"environmentIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"specularIntensity",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"disableBumpMap",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"albedoTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTextureStrength",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"opacityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectionTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectivityTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallic",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"roughness",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicF0Factor",void 0);A([ds(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicReflectanceColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"metallicReflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectanceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"microSurfaceTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"bumpTexture",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty",null)],Rt.prototype,"lightmapTexture",void 0);A([ds("ambient"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"ambientColor",void 0);A([ds("albedo"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"albedoColor",void 0);A([ds("reflectivity"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectivityColor",void 0);A([ds("reflection"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"reflectionColor",void 0);A([ds("emissive"),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"emissiveColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"microSurface",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useLightmapAsShadowmap",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"useAlphaFromAlbedoTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"forceAlphaTest",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesAndMiscDirty")],Rt.prototype,"alphaCutOff",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useSpecularOverAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRoughnessFromMetallicTextureGreen",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useMetallnessFromMetallicTextureBlue",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAmbientInGrayScale",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);A([D()],Rt.prototype,"usePhysicalLightFalloff",null);A([D()],Rt.prototype,"useGLTFLightFalloff",null);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRadianceOverAlpha",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useObjectSpaceNormalMap",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useParallax",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useParallaxOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"parallaxScaleBias",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Rt.prototype,"disableLighting",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"forceIrradianceInFragment",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Rt.prototype,"maxSimultaneousLights",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"invertNormalMapX",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"invertNormalMapY",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"twoSidedLighting",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useAlphaFresnel",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useLinearAlphaFresnel",void 0);A([Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"environmentBRDFTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"forceNormalForward",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"enableSpecularAntiAliasing",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useHorizonOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Rt.prototype,"useRadianceOcclusion",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],Rt.prototype,"unlit",void 0);A([D(),Ce("_markAllSubMeshesAsMiscDirty")],Rt.prototype,"applyDecalMapAfterDetailMap",void 0);j("BABYLON.PBRMaterial",Rt);const Z3=542327876,G0=131072,z0=512,W0=4,H0=64,X0=131072;function Nm(o){return o.charCodeAt(0)+(o.charCodeAt(1)<<8)+(o.charCodeAt(2)<<16)+(o.charCodeAt(3)<<24)}function J3(o){return String.fromCharCode(o&255,o>>8&255,o>>16&255,o>>24&255)}const Y0=Nm("DXT1"),$0=Nm("DXT3"),K0=Nm("DXT5"),vv=Nm("DX10"),q0=113,j0=116,Q0=2,Z0=10,ek=88,xv=31,tk=0,ik=1,J0=2,eC=3,Tv=4,tC=7,Ev=20,iC=21,sk=22,rk=23,nk=24,ak=25,ok=26,lk=28,hk=32;class ki{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,xv),i=new Int32Array(e.buffer,e.byteOffset,xv+4);let s=1;t[J0]&G0&&(s=Math.max(1,t[tC]));const r=t[iC],n=r===vv?i[hk]:0;let a=0;switch(r){case q0:a=2;break;case j0:a=1;break;case vv:if(n===Z0){a=2;break}if(n===Q0){a=1;break}}return{width:t[Tv],height:t[eC],mipmapCount:s,isFourCC:(t[Ev]&W0)===W0,isRGB:(t[Ev]&H0)===H0,isLuminance:(t[Ev]&X0)===X0,isCube:(t[lk]&z0)===z0,isCompressed:r===Y0||r===$0||r===K0,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const a=new Float32Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,a,l){const h=new Uint8Array(s),c=new Uint8Array(r,i);let u=0;for(let d=0;d0?s.sphericalPolynomial=vu.ConvertCubeMapToSphericalPolynomial({size:d[Tv],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}}ki.StoreLODInAlphaChannel=!1;We.prototype.createPrefilteredCubeTexture=function(o,e,t,i,s=null,r=null,n,a=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 _h,u._source=Ut.CubePrefiltered,this.getCaps().textureLOD){s&&s(u);return}const d=3,f=this._gl,p=c.width;if(!p)return;const _=[];for(let g=0;g1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),ki.UploadDDSLevels(r,t,c,n,a,6,-1,h),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t):l=n.mipmapCount-1}else{const h=e;n=ki.GetDDSInfo(h),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new _h),a=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),ki.UploadDDSLevels(r,t,h,n,a,6),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t,!1):l=n.mipmapCount-1}r._setCubeMapTextureParams(t,a,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=ki.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,()=>{ki.UploadDDSLevels(t.getEngine(),t,e,s,r,1)})}}re._TextureLoaders.push(new ck);class uk{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=fy(e);if(n){t.width=n.width,t.height=n.width;try{_y(t,n),u2(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},a=>{r==null||r("Can not upload environment levels",a)})}catch(a){r==null||r("Can not upload environment file",a)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}re._TextureLoaders.push(new uk);class Da{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Da.IsValid(e)){this.isInvalid=!0,G.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){G.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){G.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){G.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){G.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=Da.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case Da.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break}}_upload2DCompressedLevels(e,t){let i=Da.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let a=0;a=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}}Da.HEADER_LEN=12+13*4;Da.COMPRESSED_2D=0;Da.COMPRESSED_3D=1;Da.TEX_2D=2;Da.TEX_3D=3;class dk{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 wm extends dk{constructor(e,t,i=wm.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{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))})})}}wm.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var sC;(function(o){o[o.ETC1S=0]="ETC1S",o[o.UASTC4x4=1]="UASTC4x4"})(sC||(sC={}));var rd;(function(o){o[o.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",o[o.BC7_RGBA=1]="BC7_RGBA",o[o.BC3_RGBA=2]="BC3_RGBA",o[o.BC1_RGB=3]="BC1_RGB",o[o.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",o[o.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",o[o.ETC2_RGBA=6]="ETC2_RGBA",o[o.ETC1_RGB=7]="ETC1_RGB",o[o.RGBA32=8]="RGBA32",o[o.R8=9]="R8",o[o.RG8=10]="RG8"})(rd||(rd={}));var zv;(function(o){o[o.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",o[o.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",o[o.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",o[o.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",o[o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",o[o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",o[o.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",o[o.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",o[o.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",o[o.RGBA8Format=32856]="RGBA8Format",o[o.R8Format=33321]="R8Format",o[o.RG8Format=33323]="RG8Format"})(zv||(zv={}));function Wv(o){o.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=o.wasmUASTCToASTC),o.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=o.wasmUASTCToBC7),o.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=o.wasmUASTCToRGBA_UNORM),o.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=o.wasmUASTCToRGBA_SRGB),o.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=o.wasmUASTCToR8_UNORM),o.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=o.wasmUASTCToRG8_UNORM),o.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=o.jsMSCTranscoder),o.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=o.wasmMSCTranscoder),o.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=o.wasmZSTDDecoder)}class fk{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:[rd.BC1_RGB,rd.BC3_RGBA],yes:{transcodeFormat:rd.RGBA32,engineFormat:zv.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Ir{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Ir._WorkerPoolPromise||Ir._DecoderModulePromise)return;const t={jsDecoderModule:fe.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:fe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:fe.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:fe.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:fe.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?Ir._WorkerPoolPromise=new Promise(i=>{const s=`${Wv}(${pk})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new wm(e,()=>new Promise((n,a)=>{const l=new Worker(r),h=u=>{l.removeEventListener("error",h),l.removeEventListener("message",c),a(u)},c=u=>{u.data.action==="init"&&(l.removeEventListener("error",h),l.removeEventListener("message",c),n(l))};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({action:"init",urls:t})})))}):typeof KTX2DECODER>"u"?Ir._DecoderModulePromise=fe.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Wv(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Ir._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=Ir.DefaultNumWorkers){this._engine=e,Ir._Initialize(t)}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(Ir._WorkerPoolPromise)return Ir._WorkerPoolPromise.then(n=>new Promise((a,l)=>{n.push((h,c)=>{const u=p=>{h.removeEventListener("error",u),h.removeEventListener("message",d),l(p),c()},d=p=>{if(p.data.action==="decoded"){if(h.removeEventListener("error",u),h.removeEventListener("message",d),!p.data.success)l({message:p.data.msg});else try{this._createTexture(p.data.decodedData,t,i),a()}catch(_){l({message:_})}c()}};h.addEventListener("error",u),h.addEventListener("message",d),h.postMessage({action:"setDefaultDecoderOptions",options:Ir.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(Ir._DecoderModulePromise)return Ir._DecoderModulePromise.then(n=>(Ir.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=Ir.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((a,l)=>{n.decode(e,s).then(h=>{this._createTexture(h,t),a()}).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=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}}Ir.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};Ir.DefaultNumWorkers=Ir.GetDefaultNumWorkers();Ir.DefaultDecoderOptions=new fk;function pk(){let o;onmessage=e=>{if(e.data)switch(e.data.action){case"init":{const t=e.data.urls;importScripts(t.jsDecoderModule),Wv(t),o=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=e.data.options;break}case"decode":o.decode(e.data.data,e.data.caps,e.data.options).then(t=>{const i=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:t})});break}}}function _k(o){switch(o){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 mk{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 Da(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Da.IsValid(e)){t._invertVScale=!t.invertY;const r=new Da(e,1),n=_k(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 Ir.IsValid(e)?new Ir(t.getEngine()).uploadAsync(e,t,s).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},n=>{G.Warn(`Failed to load KTX2 texture data: ${n.message}`),i(0,0,!1,!1,()=>{},!0)}):(G.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}re._TextureLoaders.unshift(new mk);class Dd extends zn{constructor(e,t,i){super(e,T.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=Se.Identity(),this._referencedPosition=new T,this._trackingState=Oc.NOT_TRACKING,this.onXRCameraInitializedObservable=new he,this.onBeforeCameraTeleport=new he,this.onAfterCameraTeleport=new he,this.onTrackingStateChanged=new he,this.compensateOnFirstFrame=!0,this._rotate180=new Se(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new Se,this.cameraRigMode=et.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.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:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Na(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Na(.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,Se.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=K.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),Se.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(Oc.NOT_TRACKING);return}const t=e.emulatedPosition?Oc.TRACKING_LOST:Oc.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const i={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(i),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(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),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 r;const n=this.rigCameras[s];!n.isLeftCamera&&!n.isRightCamera&&(i.eye==="right"?n._isRightCamera=!0:i.eye==="left"&&(n._isLeftCamera=!0));const a=i.transform.position,l=i.transform.orientation;n.parent=this.parent,n.position.set(a.x,a.y,a.z),n.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),k.FromFloat32ArrayToRefScaled(i.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),s===0&&this._projectionMatrix.copyFrom(n._projectionMatrix);const h=this._xrSessionManager.getRenderTargetTextureForView(i);this._renderingMultiview=((r=h==null?void 0:h._texture)===null||r===void 0?void 0:r.isMultiview)||!1,this._renderingMultiview?s==0&&(this._xrSessionManager.trySetViewportForView(this.viewport,i),this.outputRenderTarget=h):(this._xrSessionManager.trySetViewportForView(n.viewport,i),n.outputRenderTarget=h||this._xrSessionManager.getRenderTargetTextureForView(i)),n.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const t=this.rigCameras.pop();t&&t.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=K.Matrix[0],t=K.Matrix[1],i=K.Matrix[2];k.ComposeToRef(Dd._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),k.ComposeToRef(Dd._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,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}Dd._ScaleReadOnly=T.One();class Qx{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 he,this.onStateChangedObservable=new he,this.state=rr.NOT_IN_XR,this.sessionManager=new xm(e),this.camera=new Dd("webxr",e,this.sessionManager),this.featuresManager=new _s(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new Qx(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(rr.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===void 0||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){var r,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(rr.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"&&G.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=await i.initializeXRLayerAsync(this.sessionManager.session),h={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(oi.LAYERS)||(h.baseLayer=l),this.sessionManager.updateRenderState(h),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(!((n=(r=this._nonVRCamera)===null||r===void 0?void 0:r.inputs)===null||n===void 0)&&n.attachedToElement),(a=this._nonVRCamera)===null||a===void 0||a.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!==rr.EXITING_XR&&this._setState(rr.EXITING_XR),this.camera.rigCameras.forEach(c=>{c.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(rr.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(rr.IN_XR)}),this.sessionManager}catch(l){throw G.Log(l),G.Log(l.message),this._setState(rr.NOT_IN_XR),l}}exitXRAsync(){return this.state!==rr.IN_XR?Promise.resolve():(this._setState(rr.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===rr.IN_XR?(this._spectatorCamera=new _u("webxr-spectator",T.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new Se,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(a=>{a===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===rr.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 la{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 he,this.onButtonStateChangedObservable=new he}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))}}la.BUTTON_TYPE="button";la.SQUEEZE_TYPE="squeeze";la.THUMBSTICK_TYPE="thumbstick";la.TOUCHPAD_TYPE="touchpad";la.TRIGGER_TYPE="trigger";class Tu{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=a=>{if(!a)return;const l=this.layout.components[a],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[a]=new la(a,h,c,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new he,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?G.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(a=>a.filename===t.filename&&a.path===t.path);if(n[0]){n[0].meshes.forEach(a=>a.setEnabled(!0)),r(n[0].meshes);return}}Lt.ImportMesh("",t.path,t.filename,this.scene,n=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:n})),r(n)},null,(n,a)=>{G.Log(a),G.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(a)})})}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;Se.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),T.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 se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=Se.FromEulerAngles(0,Math.PI,0)}}class Od extends Tu{constructor(e,t,i){super(e,gk[i],t,i),this.profileId=Od.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new se(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=Se.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Od.ProfileId="generic-trigger";const gk={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 vk extends Tu{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=Lt.IsPluginForExtensionAvailable(".glb");return e||G.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===la.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,n)},i.type===la.TOUCHPAD_TYPE&&!this._touchDots[s]){const a=Qo(s+"dot",{diameter:.0015,segments:8},this.scene);a.material=new De(s+"mat",this.scene),a.material.diffuseColor=Te.Red(),a.parent=this._buttonMeshMapping[t].states[s].valueMesh||null,a.isVisible=!1,this._touchDots[s]=a}}})})}_setRootMesh(e){this.rootMesh=new se(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;i{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 a=r.visualResponses[n];let l=i.value;if(a.componentProperty==="xAxis"?l=i.axes.x:a.componentProperty==="yAxis"&&(l=i.axes.y),a.valueNodeProperty==="transform")this._lerpTransform(s.states[n],l,a.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 Sv=[];class vr{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,a=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return n.call(this,s,e,t).catch(()=>a.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=fe.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){Sv.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),Sv.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(s=>{for(let r=0;r(this._ProfileLoadingPromises[s]||(this._ProfileLoadingPromises[s]=fe.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${s}/profile.json`,!1).then(r=>JSON.parse(r))),this._ProfileLoadingPromises[s])).then(s=>new vk(i,t,s,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Sv))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew Od(e,o.gamepad,o.handedness));vr.DefaultFallbacks();let xk=0;class Tk{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new T,this._disposed=!1,this.onDisposeObservable=new he,this.onMeshLoadedObservable=new he,this.onMotionControllerInitObservable=new he,this._uniqueId=`controller-${xk++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new hi(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new Se,this.inputSource.gripSpace&&(this.grip=new hi(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new Se),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&vr.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(a=>a.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===void 0||n.dispose())})},()=>{fe.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;T.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const r=s.transform.position;this.pointer.position.set(r.x,r.y,r.z);const n=s.transform.orientation;this.pointer.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const n=r.transform.position,a=r.transform.orientation;this.grip.position.set(n.x,n.y,n.z),this.grip.rotationQuaternion.set(a.x,a.y,a.z,a.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Ek{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new he,this.onControllerRemovedObservable=new he,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._options.customControllersRepositoryURL&&(vr.BaseRepositoryUrl=this._options.customControllersRepositoryURL),vr.UseOnlineRepository=!this._options.disableOnlineControllerRepository,vr.UseOnlineRepository)try{vr.UpdateProfilesList().catch(()=>{vr.UseOnlineRepository=!1})}catch{vr.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(n=>n.inputSource);for(const n of e)if(i.indexOf(n)===-1){const a=new Tk(this.xrSessionManager.scene,n,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(a),this.onControllerAddedObservable.notifyObservers(a)}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(),vr.ClearControllerCache()}}class qo extends Cr{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:s,selectionMesh:r}=this._generateNewMeshPair(i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:s,selectionMesh:r,meshUnderPointer:null,pick:null,tmpRay:new Kt(new T,new T),disabledByNearInteraction:!1,id:qo._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":return this._attachScreenRayMode(i)}},this._controllers={},this._tmpVectorForPickCompare=new T,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Te(.9,.9,.9),this.laserPointerDefaultColor=new Te(.7,.7,.7),this.selectionMeshDefaultColor=new Te(.8,.8,.8),this.selectionMeshPickedColor=new Te(.3,.3,1),this._identityMatrix=k.Identity(),this._screenCoordinatesRef=T.Zero(),this._viewportRef=new Na(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Kt(new T,new T),disabledByNearInteraction:!1,id:qo._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{const i=this._controllers[t];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=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);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 l=this._xrSessionManager.scene,h=this._options.xrInput.xrCamera;h&&(h.viewport.toGlobalToRef(l.getEngine().getRenderWidth(),l.getEngine().getRenderHeight(),this._viewportRef),T.ProjectToRef(s,this._identityMatrix,l.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),typeof this._screenCoordinatesRef.x=="number"&&typeof this._screenCoordinatesRef.y=="number"&&!isNaN(this._screenCoordinatesRef.x)&&!isNaN(this._screenCoordinatesRef.y)&&(l.pointerX=this._screenCoordinatesRef.x,l.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{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,a=0;else if(a>i/10&&(n.isVisible=!0),a+=this._scene.getEngine().getDeltaTime(),a>=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-a/i;n.scaling.set(c,c,c)}else l=!1,a=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 a=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),a?(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)):a&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)}})};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=n=>{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._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(T.Dot(e,t.direction)){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 Vr,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{fe.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Cm("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():Kh("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=Te.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 i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(i=e.pickedPoint)===null||i===void 0||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const s=(this._options.gazeModePointerMovedFactor||1)*.01*t.distance;return this._tmpVectorForPickCompare.length()>s}_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}}qo._IdCounter=200;qo.Name=oi.POINTER_SELECTION;qo.Version=1;_s.AddWebXRFeature(qo.Name,(o,e)=>()=>new qo(o,e),qo.Version,!0);on.prototype._projectOnTrianglesToRef=function(o,e,t,i,s,r){const n=K.Vector3[0],a=K.Vector3[1];let l=1/0;for(let h=this.indexStart;h{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),a=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n,currentAnimationState:ea.DEHYDRATED,grabRay:new Kt(new T,new T),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:jo._IdCounter++,pickedPointVisualCue:a},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 Te(.8,.8,.8),this.selectionMeshPickedColor=new Te(.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=Lh.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;ie.currentAnimationState)switch(e.currentAnimationState){case ea.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===ea.HOVER)break;case ea.HOVER:if(e.touchCollisionMeshFunction(!0),t===ea.TOUCH)break}else switch(e.currentAnimationState){case ea.TOUCH:if(e.touchCollisionMeshFunction(!1),t===ea.HOVER)break;case ea.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===ea.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var s;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(K.Vector3[0]),r.grabRay.direction.copyFrom(K.Vector3[0]),this._options.nearInteractionControllerMode===Lh.CENTERED_IN_FRONT&&!(!((s=r.xrController)===null||s===void 0)&&s.inputSource.hand)&&(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;const s=this._controllers[t],r=(i=s.xrController)===null||i===void 0?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!s.xrController||!r&&(!this._options.nearInteractionControllerMode||!s.xrController.inputSource.gamepad)){s.pick=null;return}if(s.hoverInteraction=!1,s.nearInteraction=!1,s.xrController){if(r){const h=r.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;K.Vector3[0].set(c.transform.position.x,c.transform.position.y,c.transform.position.z*u),K.Quaternion[0].set(c.transform.orientation.x,c.transform.orientation.y,c.transform.orientation.z*u,c.transform.orientation.w*u),this._processTouchPoint(t,K.Vector3[0],K.Quaternion[0])}}}else if(s.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==Lh.DISABLED){let h=s.xrController.pointer;s.xrController.grip&&this._options.nearInteractionControllerMode===Lh.CENTERED_ON_CONTROLLER&&(h=s.xrController.grip),this._processTouchPoint(t,h.position,h.rotationQuaternion)}}else return;const n=(h,c)=>{let u=null;return!c||!c.hit?u=h:!h||!h.hit||c.distance{let c=new Vr,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(!s.grabInteraction){let h=null,c=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(c=this._pickWithSphere(s,this._hoverRadius,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const u=this._pickWithSphere(s,this._hoverRadius,this._scene,f=>this._nearInteractionPredicate(f)),d=n(u,c);if(d&&d.hit&&(h=a(d),h.hit&&(s.hoverInteraction=!0)),s.hoverInteraction){let f=null;const p=r?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(s,p,this._utilityLayerScene,E=>this._nearPickPredicate(E)));const _=this._pickWithSphere(s,p,this._scene,E=>this._nearPickPredicate(E)),g=n(_,f),v=a(g);v.hit&&(h=v,s.nearInteraction=!0)}s.stalePick=s.pick,s.pick=h,s.pick&&s.pick.pickedPoint&&s.pick.hit?(s.meshUnderPointer=s.pick.pickedMesh,s.pickedPointVisualCue.position.copyFrom(s.pick.pickedPoint),s.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!0)):(s.meshUnderPointer=null,s.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(s.id,!1))}let l=ea.DEHYDRATED;s.grabInteraction||s.nearInteraction?l=ea.TOUCH:s.hoverInteraction&&(l=ea.HOVER),this._handleTransitionAnimation(s,l)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("nearInteraction",{diameter:.0035*3},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=Se.Identity();const i=new De("targetMat",e);return i.specularColor=Te.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.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),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)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),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(a=>{if(a.changes.pressed){const l=a.changes.pressed.current;s(l)}}):(t.selectionComponent=n.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(a=>{if(a.changes.pressed){const l=a.changes.pressed.current;s(l)}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=a=>{t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=a=>{t.xrController&&a.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart: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(()=>{const i={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Vr,i)}),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._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:ys.ParseFromSnippetAsync("8RUNKL#3",e).then(I=>{t.material=I});const i=new Gw;i.setEasingMode(ln.EASINGMODE_EASEINOUT);const s=new T(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),r=this._controllerPickRadius*(4/3),n=new T(r,r,r),a=this._controllerPickRadius*(7/6),l=new T(a,a,a),h=this._controllerPickRadius*(4/5),c=new T(h,h,h),u=this._controllerPickRadius*(3/2),d=new T(u,u,u),f=[{frame:0,value:s},{frame:10,value:d},{frame:18,value:n}],p=[{frame:0,value:n},{frame:10,value:c},{frame:18,value:s}],_=[{frame:0,value:T.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],g=[{frame:0,value:s},{frame:10,value:T.ZeroReadOnly},{frame:15,value:T.ZeroReadOnly}],v=new Ee("touch","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),E=new Ee("release","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),C=new Ee("hydrate","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT),S=new Ee("dehydrate","scaling",60,Ee.ANIMATIONTYPE_VECTOR3,Ee.ANIMATIONLOOPMODE_CONSTANT);return v.setEasingFunction(i),E.setEasingFunction(i),C.setEasingFunction(i),S.setEasingFunction(i),v.setKeys(f),E.setKeys(p),C.setKeys(_),S.setKeys(g),{touchCollisionMesh:t,touchCollisionMeshFunction:I=>{const N=I?v:E;e.beginDirectAnimation(t,[N],0,18,!1,1)},hydrateCollisionMeshFunction:I=>{const N=I?C:S;I&&(t.isVisible=!0),e.beginDirectAnimation(t,[N],0,15,!1,1,()=>{I||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,s){const r=new Vr;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,a=Rl.CreateFromCenterAndRadius(n,t);for(let l=0;lu&&(c=0,l.copyFrom(t.center)),c!==-1&&c()=>new jo(o,e),jo.Version,!0);class Sk{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Zx{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new he,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 fe.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 a=".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) }";a+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const l=document.createElement("style");l.appendChild(document.createTextNode(a)),document.getElementsByTagName("head")[0].appendChild(l);const h=document.createElement("button");h.className="babylonVRicon",h.title=`${s} - ${r}`,this._buttons.push(new Sk(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==rr.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)):fe.Warn(`Session mode "${this._buttons[n].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const s=new Zx(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==rr.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==rr.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 Bh;(function(o){o[o.INIT=0]="INIT",o[o.STARTED=1]="STARTED",o[o.ENDED=2]="ENDED"})(Bh||(Bh={}));function rC(o){var e;let t=0;const i=Date.now();o.observableParameters=(e=o.observableParameters)!==null&&e!==void 0?e:{};const s=o.contextObservable.add(r=>{const n=Date.now();t=n-i;const a={startTime:i,currentTime:n,deltaTime:t,completeRate:t/o.timeout,payload:r};o.onTick&&o.onTick(a),o.breakCondition&&o.breakCondition()&&(o.contextObservable.remove(s),o.onAborted&&o.onAborted(a)),t>=o.timeout&&(o.contextObservable.remove(s),o.onEnded&&o.onEnded(a))},o.observableParameters.mask,o.observableParameters.insertFirst,o.observableParameters.scope);return s}class Ck{constructor(e){var t,i;this.onEachCountObservable=new he,this.onTimerAbortedObservable=new he,this.onTimerEndedObservable=new he,this.onStateChangedObservable=new he,this._observer=null,this._breakOnNextTick=!1,this._tick=s=>{const r=Date.now();this._timer=r-this._startTime;const n={startTime:this._startTime,currentTime:r,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:s},a=this._breakOnNextTick||this._breakCondition(n);a||this._timer>=this._timeToEnd?this._stop(n,a):this.onEachCountObservable.notifyObservers(n)},this._setState(Bh.INIT),this._contextObservable=e.contextObservable,this._observableParameters=(t=e.observableParameters)!==null&&t!==void 0?t:{},this._breakCondition=(i=e.breakCondition)!==null&&i!==void 0?i:()=>!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===Bh.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(Bh.STARTED)}stop(){this._state===Bh.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(Bh.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Wc extends Cr{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 Ze(1,1,1,1),this._tmpRay=new Kt(new T,new T),this._tmpVector=new T,this._tmpQuaternion=new Se,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 he,this.teleportationEnabled=!0,this._rotationEnabled=!0,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}};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(la.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(la.TOUCHPAD_TYPE);if(!n||this._options.useMainComponentOnly){const a=i.motionController.getMainComponent();if(!a)return;s.teleportationComponent=a,s.onButtonChangedObserver=a.onButtonStateChangedObservable.add(()=>{if(this.teleportationEnabled&&a.changes.pressed)if(a.changes.pressed.current){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const l=this._options.timeToTeleport||3e3;rC({timeout:l,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!a.pressed,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else s.teleportationState.forward=!1,this._currentTeleportationControllerId=""})}else s.teleportationComponent=n,s.onAxisChangedObserver=n.onAxisValueChangedObservable.add(a=>{if(a.y<=.7&&s.teleportationState.backwards&&(s.teleportationState.backwards=!1),a.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,Se.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(a.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),a.x){if(s.teleportationState.forward)this._currentTeleportationControllerId===s.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{s.teleportationState.currentRotation=Math.atan2(a.x,a.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):s.teleportationState.currentRotation=0);else if(!s.teleportationState.rotating&&Math.abs(a.x)>.7){s.teleportationState.rotating=!0;const l=this.rotationAngle*(a.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);Se.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else s.teleportationState.rotating=!1;a.x===0&&a.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 this._xrSessionManager.scene.onPointerObservable.add(r=>{if(r.type===rt.POINTERDOWN){s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const n=this._options.timeToTeleport||3e3;rC({timeout:n,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})}else r.type===rt.POINTERUP&&(s.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ze(1,0,0,.75),this._setTargetMeshVisibility(!1)}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)}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{if(this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(l)!==-1)return!0;const h=this._floorMeshes.indexOf(l);return h===-1?!1:this._floorMeshes[h].absolutePosition.ythis._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(u)!==-1?!0:this._floorMeshes.indexOf(u)!==-1);if(c&&c.pickedMesh&&this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(c.pickedMesh)!==-1){r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(c);return}else c&&c.pickedPoint&&(r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(c),this._setTargetMeshVisibility(!0),this._showParabolicPath(c))}this._setTargetMeshVisibility(n)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||zs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Tm("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 Pd("teleportationPlaneDynamicTexture",512,e,!0);n.hasAlpha=!0;const a=n.getContext(),l=512/2,h=512/2,c=200;a.beginPath(),a.arc(l,h,c,0,2*Math.PI,!1),a.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",a.fill(),a.lineWidth=10,a.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",a.stroke(),a.closePath(),n.update();const u=new De("teleportationPlaneMaterial",e);u.diffuseTexture=n,t.material=u}const i=Kh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const r=new Ee("animationInnerCircle","position.y",30,Ee.ANIMATIONTYPE_FLOAT,Ee.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 a=new vb;a.setEasingMode(ln.EASINGMODE_EASEINOUT),r.setEasingFunction(a),i.animations=[],i.animations.push(r),e.beginAnimation(i,0,60,!0)}const s=Cm("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(an.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 Te(.3,.3,1):r.diffuseColor=new Te(.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._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 a=T.DistanceSquared(n,e);a<=r&&a{i.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&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||zs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=Lo.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=new Array(26).fill(r||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=ym("teleportation path line",{points:s.getPoints(),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._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,Se.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}Wc.Name=oi.TELEPORTATION;Wc.Version=1;_s.AddWebXRFeature(Wc.Name,(o,e)=>()=>new Wc(o,e),Wc.Version,!0);class Jx{constructor(){}static CreateAsync(e,t={}){const i=new Jx;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const s=Object.assign({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 Zx(e,s)}return Qx.CreateAsync(e).then(s=>{if(i.baseExperience=s,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Ek(s.sessionManager,s.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){const r=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(qo.Name,t.useStablePlugins?"stable":"latest",r),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Wc.Name,t.useStablePlugins?"stable":"latest",Object.assign({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(jo.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),!t.disableDefaultUI)return i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(s=>(G.Error("Error initializing XR"),G.Error(s),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}Qe.prototype.createDefaultLight=function(o=!1){if(o&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),s=i.max.subtract(i.min),r=i.min.add(s.scale(.5));let n,a=s.length()*1.5;if(isFinite(a)||(a=1,r.copyFromFloats(0,0,0)),o){const l=new Ji("default camera",-(Math.PI/2),Math.PI/2,a,r,this);l.lowerRadiusLimit=a*.01,l.wheelPrecision=100/a,n=l}else{const l=new zn("default camera",new T(r.x,r.y,-a),this);l.setTarget(r),n=l}n.minZ=a*.01,n.maxZ=a*1e3,n.speed=a*.2,this.activeCamera=n,t&&n.attachControl()}};Qe.prototype.createDefaultCameraOrLight=function(o=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(o,e,t)};Qe.prototype.createDefaultSkybox=function(o,e=!1,t=1e3,i=0,s=!0){if(!o)return G.Warn("Can not create default skybox without environment texture."),null;s&&o&&(this.environmentTexture=o);const r=bm("hdrSkyBox",{size:t},this);if(e){const n=new Rt("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=o.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=ee.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=o.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=ee.SKYBOX_MODE),n.disableLighting=!0,r.material=n}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r};Qe.prototype.createDefaultEnvironment=function(o){return Qh?new Qh(o,this):null};Qe.prototype.createDefaultVRExperience=function(o={}){return new Jc(this,o)};Qe.prototype.createDefaultXRExperienceAsync=function(o={}){return Jx.CreateAsync(this,o).then(e=>e)};function nC(o){for(;o.firstChild;)o.removeChild(o.firstChild);o.srcObject=null,o.src="",o.removeAttribute("src")}class Ml extends ee{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new he),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):G.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){G.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=ee.TRILINEAR_SAMPLINGMODE,a={},l,h=5){var c;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=()=>{var d;this._texture!=null&&this._texture.dispose(),!this._getEngine().needPOTTextures||fe.IsExponentOfTwo(this.video.videoWidth)&&fe.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=ee.WRAP_ADDRESSMODE,this.wrapV=ee.WRAP_ADDRESSMODE):(this.wrapU=ee.CLAMP_ADDRESSMODE,this.wrapV=ee.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=(d=this._format)!==null&&d!==void 0?d: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._settings.poster&&(!this._settings.autoPlay||!u)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):u&&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 fe.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(fe.SetCorsBehavior(e,t),t.src=e):(fe.SetCorsBehavior(e[0],t),e.forEach(i=>{const s=document.createElement("source");s.src=i,t.appendChild(s)})),this.onDisposeObservable.addOnce(()=>{nC(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 Ml(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),(e=this._externalTexture)===null||e===void 0||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 a=()=>{const l=new Ml("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{r.remove()}),l.onDisposeObservable.addOnce(()=>{nC(r)}),n(l),r.removeEventListener("playing",a)};r.addEventListener("playing",a),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(a=>{a.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){G.Error(n.name)})}}A([D("settings")],Ml.prototype,"_settings",void 0);A([D("src")],Ml.prototype,"_currentSrc",void 0);A([D()],Ml.prototype,"isVideo",void 0);ee._CreateVideoTexture=(o,e,t,i=!1,s=!1,r=ee.TRILINEAR_SAMPLINGMODE,n={},a,l=5)=>new Ml(o,e,t,i,s,r,n,a,l);j("BABYLON.VideoTexture",Ml);class eT extends In{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 Ml((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,ee.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(n=>{var a;((a=n.pickInfo)===null||a===void 0?void 0:a.pickedMesh)===this.mesh&&this._texture.video.play()},rt.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)}}eT.MODE_MONOSCOPIC=In.MODE_MONOSCOPIC;eT.MODE_TOPBOTTOM=In.MODE_TOPBOTTOM;eT.MODE_SIDEBYSIDE=In.MODE_SIDEBYSIDE;const bk="glowMapGenerationPixelShader",yk=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE @@ -7077,7 +7077,7 @@ gl_FragColor=finalColor*glowIntensity; #ifdef HIGHLIGHT gl_FragColor.a=glowColor.a; #endif -}`;ne.ShadersStore[Ek]=Sk;const Ck="glowMapGenerationVertexShader",bk=`attribute vec3 position; +}`;ne.ShadersStore[bk]=yk;const Ak="glowMapGenerationVertexShader",Rk=`attribute vec3 position; #include #include #include @@ -7148,8 +7148,8 @@ vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); vColor=color; #endif #include -}`;ne.ShadersStore[Ck]=bk;class Va{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{if((i||t===0)&&e.subMeshes)for(let s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let r;const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{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 s;const r=this._scene.getEngine(),n=e.getMesh(),a=(s=n._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);const l=e.getMaterial();if(!l)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return l.isReadyForSubMesh(e.getMesh(),e,t);const h=[],c=[P.PositionKind];let u=!1,d=!1;if(l){const C=l.needAlphaTesting(),S=l.getAlphaTestTexture(),b=S&&S.hasAlpha&&(l.useAlphaFromDiffuseTexture||l._useAlphaFromAlbedoTexture);S&&(C||b)&&(h.push("#define DIFFUSE"),n.isVerticesDataPresent(P.UV2Kind)&&S.coordinatesIndex===1?(h.push("#define DIFFUSEUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define DIFFUSEUV1"),u=!0),C&&(h.push("#define ALPHATEST"),h.push("#define ALPHATESTVALUE 0.4")),S.gammaSpace||h.push("#define DIFFUSE_ISLINEAR"));const R=l.opacityTexture;R&&(h.push("#define OPACITY"),n.isVerticesDataPresent(P.UV2Kind)&&R.coordinatesIndex===1?(h.push("#define OPACITYUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define OPACITYUV1"),u=!0))}i&&(h.push("#define EMISSIVE"),n.isVerticesDataPresent(P.UV2Kind)&&i.coordinatesIndex===1?(h.push("#define EMISSIVEUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||h.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(P.ColorKind)&&n.hasVertexAlpha&&l.transparencyMode!==Ie.MATERIAL_OPAQUE&&(c.push(P.ColorKind),h.push("#define VERTEXALPHA")),u&&(c.push(P.UVKind),h.push("#define UV1")),d&&(c.push(P.UV2Kind),h.push("#define UV2"));const f=new Jh;if(n.useBones&&n.computeBonesUsingShaders){c.push(P.MatricesIndicesKind),c.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(c.push(P.MatricesIndicesExtraKind),c.push(P.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const C=n.skeleton;C&&C.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(C?C.bones.length+1:0)),n.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,n)}else h.push("#define NUM_BONE_INFLUENCERS 0");const p=n.morphTargetManager;let _=0;p&&p.numInfluencers>0&&(h.push("#define MORPHTARGETS"),_=p.numInfluencers,h.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(c,n,_)),t&&(h.push("#define INSTANCES"),Me.PushAttributesForInstances(c),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),vh(l,this._scene,h),this._addCustomEffectDefines(h);const g=e._getDrawWrapper(void 0,!0),v=g.defines,E=h.join(` -`);if(v!==E){const C=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Ao(C),g.setEffect(this._engine.createEffect("glowMapGeneration",c,C,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],E,f,void 0,void 0,{maxSimultaneousMorphTargets:_}),E)}return g.effect.isReady()}render(){for(let n=0;nC.setMatrix("world",b))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[P.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return fe.Instantiate(e.customType).Parse(e,t,i)}}Va._SceneComponentInitialization=o=>{throw xt("EffectLayerSceneComponent")};A([D()],Va.prototype,"name",void 0);A([sx()],Va.prototype,"neutralColor",void 0);A([D()],Va.prototype,"isEnabled",void 0);A([tw()],Va.prototype,"camera",null);A([D()],Va.prototype,"renderingGroupId",null);A([D()],Va.prototype,"disableBoundingBoxesFromEffectLayer",void 0);ks.AddParser(Fe.NAME_EFFECTLAYER,(o,e,t,i)=>{if(o.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const a of e.subMeshes)if(!r.isReady(a,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===et.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==et.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{let e=o._getComponent(Fe.NAME_EFFECTLAYER);e||(e=new yk(o),o._addComponent(e))};const Ak="glowMapMergePixelShader",Rk=`varying vec2 vUV;uniform sampler2D textureSampler; +}`;ne.ShadersStore[Ak]=Rk;class Va{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{if((i||t===0)&&e.subMeshes)for(let s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let r;const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{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 s;const r=this._scene.getEngine(),n=e.getMesh(),a=(s=n._internalAbstractMeshDataInfo._materialForRenderPass)===null||s===void 0?void 0:s[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);const l=e.getMaterial();if(!l)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return l.isReadyForSubMesh(e.getMesh(),e,t);const h=[],c=[P.PositionKind];let u=!1,d=!1;if(l){const C=l.needAlphaTesting(),S=l.getAlphaTestTexture(),b=S&&S.hasAlpha&&(l.useAlphaFromDiffuseTexture||l._useAlphaFromAlbedoTexture);S&&(C||b)&&(h.push("#define DIFFUSE"),n.isVerticesDataPresent(P.UV2Kind)&&S.coordinatesIndex===1?(h.push("#define DIFFUSEUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define DIFFUSEUV1"),u=!0),C&&(h.push("#define ALPHATEST"),h.push("#define ALPHATESTVALUE 0.4")),S.gammaSpace||h.push("#define DIFFUSE_ISLINEAR"));const R=l.opacityTexture;R&&(h.push("#define OPACITY"),n.isVerticesDataPresent(P.UV2Kind)&&R.coordinatesIndex===1?(h.push("#define OPACITYUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define OPACITYUV1"),u=!0))}i&&(h.push("#define EMISSIVE"),n.isVerticesDataPresent(P.UV2Kind)&&i.coordinatesIndex===1?(h.push("#define EMISSIVEUV2"),d=!0):n.isVerticesDataPresent(P.UVKind)&&(h.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||h.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(P.ColorKind)&&n.hasVertexAlpha&&l.transparencyMode!==Ie.MATERIAL_OPAQUE&&(c.push(P.ColorKind),h.push("#define VERTEXALPHA")),u&&(c.push(P.UVKind),h.push("#define UV1")),d&&(c.push(P.UV2Kind),h.push("#define UV2"));const f=new ec;if(n.useBones&&n.computeBonesUsingShaders){c.push(P.MatricesIndicesKind),c.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(c.push(P.MatricesIndicesExtraKind),c.push(P.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const C=n.skeleton;C&&C.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(C?C.bones.length+1:0)),n.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,n)}else h.push("#define NUM_BONE_INFLUENCERS 0");const p=n.morphTargetManager;let _=0;p&&p.numInfluencers>0&&(h.push("#define MORPHTARGETS"),_=p.numInfluencers,h.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(c,n,_)),t&&(h.push("#define INSTANCES"),Me.PushAttributesForInstances(c),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),xh(l,this._scene,h),this._addCustomEffectDefines(h);const g=e._getDrawWrapper(void 0,!0),v=g.defines,E=h.join(` +`);if(v!==E){const C=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Ao(C),g.setEffect(this._engine.createEffect("glowMapGeneration",c,C,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],E,f,void 0,void 0,{maxSimultaneousMorphTargets:_}),E)}return g.effect.isReady()}render(){for(let n=0;nC.setMatrix("world",b))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[P.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return fe.Instantiate(e.customType).Parse(e,t,i)}}Va._SceneComponentInitialization=o=>{throw xt("EffectLayerSceneComponent")};A([D()],Va.prototype,"name",void 0);A([nx()],Va.prototype,"neutralColor",void 0);A([D()],Va.prototype,"isEnabled",void 0);A([rw()],Va.prototype,"camera",null);A([D()],Va.prototype,"renderingGroupId",null);A([D()],Va.prototype,"disableBoundingBoxesFromEffectLayer",void 0);ks.AddParser(Fe.NAME_EFFECTLAYER,(o,e,t,i)=>{if(o.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const a of e.subMeshes)if(!r.isReady(a,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===et.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==et.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{let e=o._getComponent(Fe.NAME_EFFECTLAYER);e||(e=new Ik(o),o._addComponent(e))};const Pk="glowMapMergePixelShader",Mk=`varying vec2 vUV;uniform sampler2D textureSampler; #ifdef EMISSIVE uniform sampler2D textureSampler2; #endif @@ -7171,22 +7171,22 @@ baseColor=clamp(baseColor,0.,1.0); #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[Ak]=Rk;const Ik="glowMapMergeVertexShader",Pk=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +}`;ne.ShadersStore[Pk]=Mk;const Dk="glowMapMergeVertexShader",Ok=`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 -}`;ne.ShadersStore[Ik]=Pk;ks.prototype.getGlowLayerByName=function(o){var e;for(let t=0;t<((e=this.effectLayers)===null||e===void 0?void 0:e.length);t++)if(this.effectLayers[t].name===o&&this.effectLayers[t].getEffectName()===Oa.EffectName)return this.effectLayers[t];return null};class Oa extends Va{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 Ze(0,0,0,1),this._options=Object.assign({mainTextureRatio:Oa.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 Oa.EffectName}_createMergeEffect(){let e=`#define EMISSIVE +}`;ne.ShadersStore[Dk]=Ok;ks.prototype.getGlowLayerByName=function(o){var e;for(let t=0;t<((e=this.effectLayers)===null||e===void 0?void 0:e.length);t++)if(this.effectLayers[t].name===o&&this.effectLayers[t].getEffectName()===Oa.EffectName)return this.effectLayers[t];return null};class Oa extends Va{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 Ze(0,0,0,1),this._options=Object.assign({mainTextureRatio:Oa.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 Oa.EffectName}_createMergeEffect(){let e=`#define EMISSIVE `;return this._options.ldrMerge&&(e+=`#define LDR -`),this._engine.createEffect("glowMapMerge",[P.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?re.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?re.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new ms("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=ee.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=ee.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const s=Math.floor(e/2),r=Math.floor(t/2);this._blurTexture2=new ms("GlowLayerBlurRTT2",{width:s,height:r},this._scene,!1,!0,i),this._blurTexture2.wrapU=ee.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=ee.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new or("GlowLayerHBP1",new Re(1,0),n,{width:e,height:t},null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(a=>{a.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new or("GlowLayerVBP1",new Re(0,1),n,{width:e,height:t},null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new or("GlowLayerHBP2",new Re(1,0),n,{width:s,height:r},null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(a=>{a.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new or("GlowLayerVBP2",new Re(0,1),n,{width:s,height:r},null,ee.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 a=this._blurTexture1.renderTarget;if(a){this._scene.postProcessManager.directRender(this._postProcesses1,a,!0);const l=this._blurTexture2.renderTarget;l&&this._scene.postProcessManager.directRender(this._postProcesses2,l,!0),this._engine.unBindFramebuffer(l??a,!0)}}),this._postProcesses.map(a=>{a.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(Ie.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var s;let r=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const n=(s=i.emissiveIntensity)!==null&&s!==void 0?s:1;r*=n,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,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=Xe.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Oa(e.name,t,e.options),e,t,i);let r;for(r=0;r{a.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new or("GlowLayerVBP1",new Re(0,1),n,{width:e,height:t},null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new or("GlowLayerHBP2",new Re(1,0),n,{width:s,height:r},null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(a=>{a.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new or("GlowLayerVBP2",new Re(0,1),n,{width:s,height:r},null,ee.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 a=this._blurTexture1.renderTarget;if(a){this._scene.postProcessManager.directRender(this._postProcesses1,a,!0);const l=this._blurTexture2.renderTarget;l&&this._scene.postProcessManager.directRender(this._postProcesses2,l,!0),this._engine.unBindFramebuffer(l??a,!0)}}),this._postProcesses.map(a=>{a.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(Ie.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var s;let r=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const n=(s=i.emissiveIntensity)!==null&&s!==void 0?s:1;r*=n,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,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=Xe.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Oa(e.name,t,e.options),e,t,i);let r;for(r=0;r{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class _n extends Va{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 he,this.onAfterBlurObservable=new he,this._instanceGlowingMeshStencilReference=_n.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=_n.NeutralColor,this._engine.isStencilEnable||G.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({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 _n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[P.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?re.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?re.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new ms("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ee.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ee.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ee.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new el("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new rC("HighlightLayerHBP",new Re(1,0),this._options.blurHorizontalSize,1,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new rC("HighlightLayerVBP",new Re(0,1),this._options.blurVerticalSize,1,null,ee.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 or("HighlightLayerHBP",new Re(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,ee.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 or("HighlightLayerVBP",new Re(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,ee.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(Ie.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ie.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(_n.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=Xe.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=Xe.Parse(()=>new _n(e.name,t,e.options),e,t,i);let r;for(r=0;r{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class mn extends Va{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 he,this.onAfterBlurObservable=new he,this._instanceGlowingMeshStencilReference=mn.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=mn.NeutralColor,this._engine.isStencilEnable||G.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({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 mn.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[P.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?re.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?re.GetExponentOfTwo(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new ms("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ee.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ee.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ee.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new el("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new aC("HighlightLayerHBP",new Re(1,0),this._options.blurHorizontalSize,1,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new aC("HighlightLayerVBP",new Re(0,1),this._options.blurVerticalSize,1,null,ee.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 or("HighlightLayerHBP",new Re(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,ee.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 or("HighlightLayerVBP",new Re(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,ee.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(Ie.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ie.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(mn.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=Xe.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=Xe.Parse(()=>new mn(e.name,t,e.options),e,t,i);let r;for(r=0;r #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { @@ -7201,25 +7201,25 @@ discard; #endif gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[Ok]=Nk;const wk="layerVertexShader",Fk=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +}`;ne.ShadersStore[Fk]=Lk;const Bk="layerVertexShader",Vk=`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 -}`;ne.ShadersStore[wk]=Fk;class Jx{static AddFlare(e,t,i,s,r){return new Jx(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Te(1,1,1),this.texture=s?new ee(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Or(n),this._drawWrapper.effect=n.createEffect("lensFlare",[P.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 Lk="lensFlarePixelShader",Bk=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +}`;ne.ShadersStore[Bk]=Vk;class tT{static AddFlare(e,t,i,s,r){return new tT(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Te(1,1,1),this.texture=s?new ee(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Or(n),this._drawWrapper.effect=n.createEffect("lensFlare",[P.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 Uk="lensFlarePixelShader",kk=`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 -}`;ne.ShadersStore[Lk]=Bk;const Vk="lensFlareVertexShader",Uk=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +}`;ne.ShadersStore[Uk]=kk;const Gk="lensFlareVertexShader",zk=`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 -}`;ne.ShadersStore[Vk]=Uk;class nu{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||ht.LastCreatedScene,nu._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[P.PositionKind]=new P(s,r,P.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=T.Project(t,k.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=T.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._positionXe.y&&this._positionYi}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._positionXi.x+i.width-this.borderLimit?s=this._positionX-i.x-i.width+this.borderLimit:s=0,this._positionYi.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 a=1-ye.Clamp(n/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=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{throw xt("LensFlareSystemSceneComponent")};ks.AddParser(Fe.NAME_LENSFLARESYSTEM,(o,e,t,i)=>{if(o.lensFlareSystems!==void 0&&o.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let s=0,r=o.lensFlareSystems.length;s{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;fe.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();fe.EndPerformanceCounter("Lens flares",t.length>0)}}}nu._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_LENSFLARESYSTEM);e||(e=new kk(o),o._addComponent(e))};const Gk="bayerDitherFunctions",zk=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +}`;ne.ShadersStore[Gk]=zk;class nu{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||ht.LastCreatedScene,nu._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[P.PositionKind]=new P(s,r,P.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=T.Project(t,k.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=T.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._positionXe.y&&this._positionYi}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._positionXi.x+i.width-this.borderLimit?s=this._positionX-i.x-i.width+this.borderLimit:s=0,this._positionYi.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 a=1-ye.Clamp(n/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=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{throw xt("LensFlareSystemSceneComponent")};ks.AddParser(Fe.NAME_LENSFLARESYSTEM,(o,e,t,i)=>{if(o.lensFlareSystems!==void 0&&o.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let s=0,r=o.lensFlareSystems.length;s{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;fe.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();fe.EndPerformanceCounter("Lens flares",t.length>0)}}}nu._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_LENSFLARESYSTEM);e||(e=new Wk(o),o._addComponent(e))};const Hk="bayerDitherFunctions",Xk=`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);} @@ -7227,7 +7227,7 @@ 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);} -`;ne.IncludesShadersStore[Gk]=zk;const Wk="shadowMapFragmentExtraDeclaration",Hk=`#if SM_FLOAT==0 +`;ne.IncludesShadersStore[Hk]=Xk;const Yk="shadowMapFragmentExtraDeclaration",$k=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 @@ -7242,7 +7242,7 @@ uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif -`;ne.IncludesShadersStore[Wk]=Hk;const Xk="shadowMapFragment",Yk=`float depthSM=vDepthMetricSM; +`;ne.IncludesShadersStore[Yk]=$k;const Kk="shadowMapFragment",qk=`float depthSM=vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; @@ -7269,7 +7269,7 @@ gl_FragColor=vec4(depthSM,1.0,1.0,1.0); #else gl_FragColor=pack(depthSM); #endif -return;`;ne.IncludesShadersStore[Xk]=Yk;const $k="shadowMapPixelShader",Kk=`#include +return;`;ne.IncludesShadersStore[Kk]=qk;const jk="shadowMapPixelShader",Qk=`#include #ifdef ALPHATEXTURE varying vec2 vUV;uniform sampler2D diffuseSampler; #endif @@ -7293,18 +7293,18 @@ if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowS #endif #endif #include -}`;ne.ShadersStore[$k]=Kk;const qk="sceneVertexDeclaration",jk=`uniform mat4 viewProjection; +}`;ne.ShadersStore[jk]=Qk;const Zk="sceneVertexDeclaration",Jk=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`;ne.IncludesShadersStore[qk]=jk;const Qk="meshVertexDeclaration",Zk=`uniform mat4 world;uniform float visibility; -`;ne.IncludesShadersStore[Qk]=Zk;const Jk="shadowMapVertexDeclaration",eG=`#include +`;ne.IncludesShadersStore[Zk]=Jk;const eG="meshVertexDeclaration",tG=`uniform mat4 world;uniform float visibility; +`;ne.IncludesShadersStore[eG]=tG;const iG="shadowMapVertexDeclaration",sG=`#include #include -`;ne.IncludesShadersStore[Jk]=eG;const tG="shadowMapUboDeclaration",iG=`layout(std140,column_major) uniform; +`;ne.IncludesShadersStore[iG]=sG;const rG="shadowMapUboDeclaration",nG=`layout(std140,column_major) uniform; #include #include -`;ne.IncludesShadersStore[tG]=iG;const sG="shadowMapVertexExtraDeclaration",rG=`#if SM_NORMALBIAS==1 +`;ne.IncludesShadersStore[rG]=nG;const aG="shadowMapVertexExtraDeclaration",oG=`#if SM_NORMALBIAS==1 uniform vec3 lightDataSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; @@ -7314,7 +7314,7 @@ varying vec3 vPositionWSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif -`;ne.IncludesShadersStore[sG]=rG;const nG="shadowMapVertexNormalBias",aG=`#if SM_NORMALBIAS==1 +`;ne.IncludesShadersStore[aG]=oG;const lG="shadowMapVertexNormalBias",hG=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 vec3 worldLightDirSM=normalize(-lightDataSM.xyz); #else @@ -7322,7 +7322,7 @@ vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normal #endif float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; #endif -`;ne.IncludesShadersStore[nG]=aG;const oG="shadowMapVertexMetric",lG=`#if SM_USEDISTANCE==1 +`;ne.IncludesShadersStore[lG]=hG;const cG="shadowMapVertexMetric",uG=`#if SM_USEDISTANCE==1 vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 @@ -7346,7 +7346,7 @@ vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif -`;ne.IncludesShadersStore[oG]=lG;const hG="shadowMapVertexShader",cG=`attribute vec3 position; +`;ne.IncludesShadersStore[cG]=uG;const dG="shadowMapVertexShader",fG=`attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif @@ -7408,16 +7408,16 @@ vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif #include -}`;ne.ShadersStore[hG]=cG;const uG="depthBoxBlurPixelShader",dG=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +}`;ne.ShadersStore[dG]=fG;const pG="depthBoxBlurPixelShader",_G=`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)));}`;ne.ShadersStore[uG]=dG;const fG="shadowMapFragmentSoftTransparentShadow",pG=`#if SM_SOFTTRANSPARENTSHADOW==1 +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;ne.ShadersStore[pG]=_G;const mG="shadowMapFragmentSoftTransparentShadow",gG=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; #endif -`;ne.IncludesShadersStore[fG]=pG;class St{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===St.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===St.FILTER_PCF||e===St.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===St.FILTER_PCF||e===St.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===St.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(St.FILTER_POISSONSAMPLING);!e&&this.filter!==St.FILTER_POISSONSAMPLING||(this.filter=e?t:St.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===St.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===St.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===St.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===St.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(St.FILTER_PCF);!e&&this.filter!==St.FILTER_PCF||(this.filter=e?t:St.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===St.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(St.FILTER_PCSS);!e&&this.filter!==St.FILTER_PCSS||(this.filter=e?t:St.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 St.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(){var e;return(e=this._camera)!==null&&e!==void 0?e: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 he,this.onAfterShadowMapRenderObservable=new he,this.onBeforeShadowMapRenderMeshObservable=new he,this.onAfterShadowMapRenderMeshObservable=new he,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=St.FILTER_NONE,this._filteringQuality=St.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=T.Zero(),this._viewMatrix=k.Zero(),this._projectionMatrix=k.Zero(),this._transformMatrix=k.Zero(),this._cachedPosition=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=k.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}")`))),St._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new ms(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 ms(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=ee.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=ee.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(s,r,n,a)=>this._renderForShadowMap(s,r,n,a),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===void 0||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===St.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 s,r;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===St.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)===null||s===void 0||s.call(e,1);return}const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),(r=e._debugPopGroup)===null||r===void 0||r.call(e,1))});const t=new Ze(0,0,0,0),i=new Ze(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===St.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=Fr.MIN_RENDERINGGROUPS;s{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new or(this._light.name+"KernelBlurY",new Re(0,1),this.blurKernel,1,null,ee.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 lt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,ee.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{n!==r&&!S?(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(b)):(n.getMeshUniformBuffer().bindToEffect(v,"Mesh"),n.transferToEffect(S?b:C))}),this.forceBackFacesOnly&&l.setState(!0,0,!1,!1,h.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(v),this.onAfterShadowMapRenderMeshObservable.notifyObservers(r)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===St.FILTER_NONE||this.filter===St.FILTER_PCSS?this._shadowMap.updateSamplingMode(ee.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i=Object.assign({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 a=0;const l=()=>{var h,c;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[a],i.useInstances,(c=(h=n[a].getMaterial())===null||h===void 0?void 0:h.needAlphaBlendingForMesh(n[a].getMesh()))!==null&&c!==void 0?c:!1);)if(a++,a>=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(P.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Yt.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){var s;const r=e.getMaterial(),n=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const l=e._getDrawWrapper(void 0,!0);let h=l.effect,c=l.defines;const u=[P.PositionKind],d=e.getMesh();this.normalBias&&d.isVerticesDataPresent(P.NormalKind)&&(u.push(P.NormalKind),a.push("#define NORMAL"),d.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const f=r.needAlphaTesting();if((f||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const E=(s=r.alphaCutOff)!==null&&s!==void 0?s:St.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),f&&a.push(`#define ALPHATESTVALUE ${E}${E%1===0?".":""}`),d.isVerticesDataPresent(P.UVKind)&&(u.push(P.UVKind),a.push("#define UV1")),d.isVerticesDataPresent(P.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(u.push(P.UV2Kind),a.push("#define UV2"))}const p=new Jh;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){u.push(P.MatricesIndicesKind),u.push(P.MatricesWeightsKind),d.numBoneInfluencers>4&&(u.push(P.MatricesIndicesExtraKind),u.push(P.MatricesWeightsExtraKind));const E=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&p.addCPUSkinningFallback(0,d),E.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(E.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const _=d.morphTargetManager;let g=0;if(_&&_.numInfluencers>0&&(a.push("#define MORPHTARGETS"),g=_.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+g),_.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(u,d,g)),vh(r,this._scene,a),t&&(a.push("#define INSTANCES"),Me.PushAttributesForInstances(u),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const E of this.customShaderOptions.defines)a.indexOf(E)===-1&&a.push(E);const v=a.join(` -`);if(c!==v){c=v;let E="shadowMap";const C=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],S=["diffuseSampler","boneSampler","morphTargets"],b=["Scene","Mesh"];if(Ao(C),this.customShaderOptions){if(E=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const I of this.customShaderOptions.attributes)u.indexOf(I)===-1&&u.push(I);if(this.customShaderOptions.uniforms)for(const I of this.customShaderOptions.uniforms)C.indexOf(I)===-1&&C.push(I);if(this.customShaderOptions.samplers)for(const I of this.customShaderOptions.samplers)S.indexOf(I)===-1&&S.push(I)}const R=this._scene.getEngine();h=R.createEffect(E,{attributes:u,uniformsNames:C,uniformBuffersNames:b,samplers:S,defines:v,fallbacks:p,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:g}},R),l.setEffect(h,c)}if(!h.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===St.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===St.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===St.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===St.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===St.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===St.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),T.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(T.Dot(this._lightDirection,T.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),k.LookAtLHToRef(t,t.add(this._lightDirection),T.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 e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=(e=this._camera)===null||e===void 0?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let s=0;s{throw xt("ShadowGeneratorSceneComponent")};const _G="depthPixelShader",mG=`#ifdef ALPHATEST +`;ne.IncludesShadersStore[mG]=gG;class St{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===St.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===St.FILTER_PCF||e===St.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===St.FILTER_PCF||e===St.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===St.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(St.FILTER_POISSONSAMPLING);!e&&this.filter!==St.FILTER_POISSONSAMPLING||(this.filter=e?t:St.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===St.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===St.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===St.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==St.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:St.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===St.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(St.FILTER_PCF);!e&&this.filter!==St.FILTER_PCF||(this.filter=e?t:St.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===St.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(St.FILTER_PCSS);!e&&this.filter!==St.FILTER_PCSS||(this.filter=e?t:St.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 St.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(){var e;return(e=this._camera)!==null&&e!==void 0?e: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 he,this.onAfterShadowMapRenderObservable=new he,this.onBeforeShadowMapRenderMeshObservable=new he,this.onAfterShadowMapRenderMeshObservable=new he,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=St.FILTER_NONE,this._filteringQuality=St.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=T.Zero(),this._viewMatrix=k.Zero(),this._projectionMatrix=k.Zero(),this._transformMatrix=k.Zero(),this._cachedPosition=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=k.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}")`))),St._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new ms(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 ms(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=ee.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=ee.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(s,r,n,a)=>this._renderForShadowMap(s,r,n,a),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===void 0||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===St.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 s,r;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===St.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)===null||s===void 0||s.call(e,1);return}const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),(r=e._debugPopGroup)===null||r===void 0||r.call(e,1))});const t=new Ze(0,0,0,0),i=new Ze(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===St.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=Fr.MIN_RENDERINGGROUPS;s{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new or(this._light.name+"KernelBlurY",new Re(0,1),this.blurKernel,1,null,ee.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 lt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,ee.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{n!==r&&!S?(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(b)):(n.getMeshUniformBuffer().bindToEffect(v,"Mesh"),n.transferToEffect(S?b:C))}),this.forceBackFacesOnly&&l.setState(!0,0,!1,!1,h.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(v),this.onAfterShadowMapRenderMeshObservable.notifyObservers(r)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===St.FILTER_NONE||this.filter===St.FILTER_PCSS?this._shadowMap.updateSamplingMode(ee.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(ee.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i=Object.assign({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 a=0;const l=()=>{var h,c;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[a],i.useInstances,(c=(h=n[a].getMaterial())===null||h===void 0?void 0:h.needAlphaBlendingForMesh(n[a].getMesh()))!==null&&c!==void 0?c:!1);)if(a++,a>=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(P.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Yt.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){var s;const r=e.getMaterial(),n=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const l=e._getDrawWrapper(void 0,!0);let h=l.effect,c=l.defines;const u=[P.PositionKind],d=e.getMesh();this.normalBias&&d.isVerticesDataPresent(P.NormalKind)&&(u.push(P.NormalKind),a.push("#define NORMAL"),d.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const f=r.needAlphaTesting();if((f||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const E=(s=r.alphaCutOff)!==null&&s!==void 0?s:St.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),f&&a.push(`#define ALPHATESTVALUE ${E}${E%1===0?".":""}`),d.isVerticesDataPresent(P.UVKind)&&(u.push(P.UVKind),a.push("#define UV1")),d.isVerticesDataPresent(P.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(u.push(P.UV2Kind),a.push("#define UV2"))}const p=new ec;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){u.push(P.MatricesIndicesKind),u.push(P.MatricesWeightsKind),d.numBoneInfluencers>4&&(u.push(P.MatricesIndicesExtraKind),u.push(P.MatricesWeightsExtraKind));const E=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&p.addCPUSkinningFallback(0,d),E.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(E.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const _=d.morphTargetManager;let g=0;if(_&&_.numInfluencers>0&&(a.push("#define MORPHTARGETS"),g=_.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+g),_.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(u,d,g)),xh(r,this._scene,a),t&&(a.push("#define INSTANCES"),Me.PushAttributesForInstances(u),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const E of this.customShaderOptions.defines)a.indexOf(E)===-1&&a.push(E);const v=a.join(` +`);if(c!==v){c=v;let E="shadowMap";const C=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],S=["diffuseSampler","boneSampler","morphTargets"],b=["Scene","Mesh"];if(Ao(C),this.customShaderOptions){if(E=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const I of this.customShaderOptions.attributes)u.indexOf(I)===-1&&u.push(I);if(this.customShaderOptions.uniforms)for(const I of this.customShaderOptions.uniforms)C.indexOf(I)===-1&&C.push(I);if(this.customShaderOptions.samplers)for(const I of this.customShaderOptions.samplers)S.indexOf(I)===-1&&S.push(I)}const R=this._scene.getEngine();h=R.createEffect(E,{attributes:u,uniformsNames:C,uniformBuffersNames:b,samplers:S,defines:v,fallbacks:p,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:g}},R),l.setEffect(h,c)}if(!h.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===St.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===St.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===St.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===St.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===St.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===St.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),T.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(T.Dot(this._lightDirection,T.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),k.LookAtLHToRef(t,t.add(this._lightDirection),T.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 e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=(e=this._camera)===null||e===void 0?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let s=0;s{throw xt("ShadowGeneratorSceneComponent")};const vG="depthPixelShader",xG=`#ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include @@ -7457,10 +7457,10 @@ gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); #endif #endif #endif -}`;ne.ShadersStore[_G]=mG;const gG="pointCloudVertexDeclaration",vG=`#ifdef POINTSIZE +}`;ne.ShadersStore[vG]=xG;const TG="pointCloudVertexDeclaration",EG=`#ifdef POINTSIZE uniform float pointSize; #endif -`;ne.IncludesShadersStore[gG]=vG;const xG="depthVertexShader",TG=`attribute vec3 position; +`;ne.IncludesShadersStore[TG]=EG;const SG="depthVertexShader",CG=`attribute vec3 position; #include #include #include @@ -7515,8 +7515,8 @@ vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #include } -`;ne.ShadersStore[xG]=TG;class ic{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=ee.TRILINEAR_SAMPLINGMODE,n=!1,a){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 Ze(1,1,1,1):this.clearColor=new Ze(n?1e8:1,0,0,1),ic._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==ee.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=ee.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=ee.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new ms(a??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=ee.CLAMP_ADDRESSMODE,this._depthMap.wrapV=ee.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===void 0||u.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)===null||u===void 0||u.call(l,1)}),this._depthMap.customIsReadyFunction=(u,d,f)=>{if((f||d===0)&&u.subMeshes)for(let p=0;p{var d,f;const p=u.getRenderingMesh(),_=u.getEffectiveMesh(),g=this._scene,v=g.getEngine(),E=u.getMaterial();if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!E||_.infiniteDistance||E.disableDepthWrite||u.verticesCount===0||u._renderId===g.getRenderId())return;const C=_._getWorldMatrixDeterminant()<0;let S=(d=p.overrideMaterialSideOrientation)!==null&&d!==void 0?d:E.sideOrientation;C&&(S=S===0?1:0);const b=S===0;v.setState(E.backFaceCulling,0,!1,b,this.reverseCulling?!E.cullBackFaces:E.cullBackFaces);const R=p._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(R.mustReturn)return;const I=v.getCaps().instancedArrays&&(R.visibleInstances[u._id]!==null&&R.visibleInstances[u._id]!==void 0||p.hasThinInstances),N=this._camera||g.activeCamera;if(this.isReady(u,I)&&N){u._renderId=g.getRenderId();const O=(f=_._internalAbstractMeshDataInfo._materialForRenderPass)===null||f===void 0?void 0:f[v.currentRenderPassId];let L=u._getDrawWrapper();!L&&O&&(L=O._getDrawWrapper());const B=N.mode===et.ORTHOGRAPHIC_CAMERA;if(!L)return;const V=L.effect;v.enableEffect(L),I||p._bind(u,V,E.fillMode),O?O.bindForSubMesh(_.getWorldMatrix(),_,u):(V.setMatrix("viewProjection",g.getTransformMatrix()),V.setMatrix("world",_.getWorldMatrix()),this._storeCameraSpaceZ&&V.setMatrix("view",g.getViewMatrix()));let Z,ue;if(B?(Z=!v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:1,ue=v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:1):(Z=v.useReverseDepthBuffer&&v.isNDCHalfZRange?N.minZ:v.isNDCHalfZRange?0:N.minZ,ue=v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:N.maxZ),V.setFloat2("depthValues",Z,Z+ue),!O){if(E.needAlphaTesting()){const oe=E.getAlphaTestTexture();oe&&(V.setTexture("diffuseSampler",oe),V.setMatrix("diffuseMatrix",oe.getTextureMatrix()))}if(p.useBones&&p.computeBonesUsingShaders&&p.skeleton){const oe=p.skeleton;if(oe.isUsingTextureForMatrices){const me=oe.getTransformMatrixTexture(p);if(!me)return;V.setTexture("boneSampler",me),V.setFloat("boneTextureWidth",4*(oe.bones.length+1))}else V.setMatrices("mBones",oe.getTransformMatrices(p))}so(V,E,g),Me.BindMorphTargetParameters(p,V),p.morphTargetManager&&p.morphTargetManager.isUsingTextureForTargets&&p.morphTargetManager._bind(V),E.pointsCloud&&V.setFloat("pointSize",E.pointSize)}p._processRendering(_,u,V,E.fillMode,R,I,(oe,me)=>V.setMatrix("world",me))}};this._depthMap.customRenderFunction=(u,d,f,p)=>{let _;if(p.length)for(_=0;_4&&(c.push(P.MatricesIndicesExtraKind),c.push(P.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),h.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0));const g=e.getRenderingMesh().skeleton;g!=null&&g.isUsingTextureForMatrices&&h.push("#define BONETEXTURE")}else h.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let d=0;u&&u.numInfluencers>0&&(d=u.numInfluencers,h.push("#define MORPHTARGETS"),h.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(c,r,d)),l.pointsCloud&&h.push("#define POINTSIZE"),t&&(h.push("#define INSTANCES"),Me.PushAttributesForInstances(c),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&h.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&h.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&h.push("#define PACKED"),vh(l,n,h);const f=e._getDrawWrapper(void 0,!0),p=f.defines,_=h.join(` -`);if(p!==_){const g=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];Ao(g),f.setEffect(s.createEffect("depth",c,g,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),_)}return f.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]}}}ic._SceneComponentInitialization=o=>{throw xt("DepthRendererSceneComponent")};const EG="minmaxReduxPixelShader",SG=`varying vec2 vUV;uniform sampler2D textureSampler; +`;ne.ShadersStore[SG]=CG;class sc{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=ee.TRILINEAR_SAMPLINGMODE,n=!1,a){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 Ze(1,1,1,1):this.clearColor=new Ze(n?1e8:1,0,0,1),sc._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==ee.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=ee.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=ee.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new ms(a??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=ee.CLAMP_ADDRESSMODE,this._depthMap.wrapV=ee.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===void 0||u.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)===null||u===void 0||u.call(l,1)}),this._depthMap.customIsReadyFunction=(u,d,f)=>{if((f||d===0)&&u.subMeshes)for(let p=0;p{var d,f;const p=u.getRenderingMesh(),_=u.getEffectiveMesh(),g=this._scene,v=g.getEngine(),E=u.getMaterial();if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!E||_.infiniteDistance||E.disableDepthWrite||u.verticesCount===0||u._renderId===g.getRenderId())return;const C=_._getWorldMatrixDeterminant()<0;let S=(d=p.overrideMaterialSideOrientation)!==null&&d!==void 0?d:E.sideOrientation;C&&(S=S===0?1:0);const b=S===0;v.setState(E.backFaceCulling,0,!1,b,this.reverseCulling?!E.cullBackFaces:E.cullBackFaces);const R=p._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(R.mustReturn)return;const I=v.getCaps().instancedArrays&&(R.visibleInstances[u._id]!==null&&R.visibleInstances[u._id]!==void 0||p.hasThinInstances),N=this._camera||g.activeCamera;if(this.isReady(u,I)&&N){u._renderId=g.getRenderId();const O=(f=_._internalAbstractMeshDataInfo._materialForRenderPass)===null||f===void 0?void 0:f[v.currentRenderPassId];let L=u._getDrawWrapper();!L&&O&&(L=O._getDrawWrapper());const B=N.mode===et.ORTHOGRAPHIC_CAMERA;if(!L)return;const V=L.effect;v.enableEffect(L),I||p._bind(u,V,E.fillMode),O?O.bindForSubMesh(_.getWorldMatrix(),_,u):(V.setMatrix("viewProjection",g.getTransformMatrix()),V.setMatrix("world",_.getWorldMatrix()),this._storeCameraSpaceZ&&V.setMatrix("view",g.getViewMatrix()));let Z,ue;if(B?(Z=!v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:1,ue=v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:1):(Z=v.useReverseDepthBuffer&&v.isNDCHalfZRange?N.minZ:v.isNDCHalfZRange?0:N.minZ,ue=v.useReverseDepthBuffer&&v.isNDCHalfZRange?0:N.maxZ),V.setFloat2("depthValues",Z,Z+ue),!O){if(E.needAlphaTesting()){const oe=E.getAlphaTestTexture();oe&&(V.setTexture("diffuseSampler",oe),V.setMatrix("diffuseMatrix",oe.getTextureMatrix()))}if(p.useBones&&p.computeBonesUsingShaders&&p.skeleton){const oe=p.skeleton;if(oe.isUsingTextureForMatrices){const me=oe.getTransformMatrixTexture(p);if(!me)return;V.setTexture("boneSampler",me),V.setFloat("boneTextureWidth",4*(oe.bones.length+1))}else V.setMatrices("mBones",oe.getTransformMatrices(p))}so(V,E,g),Me.BindMorphTargetParameters(p,V),p.morphTargetManager&&p.morphTargetManager.isUsingTextureForTargets&&p.morphTargetManager._bind(V),E.pointsCloud&&V.setFloat("pointSize",E.pointSize)}p._processRendering(_,u,V,E.fillMode,R,I,(oe,me)=>V.setMatrix("world",me))}};this._depthMap.customRenderFunction=(u,d,f,p)=>{let _;if(p.length)for(_=0;_4&&(c.push(P.MatricesIndicesExtraKind),c.push(P.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),h.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0));const g=e.getRenderingMesh().skeleton;g!=null&&g.isUsingTextureForMatrices&&h.push("#define BONETEXTURE")}else h.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let d=0;u&&u.numInfluencers>0&&(d=u.numInfluencers,h.push("#define MORPHTARGETS"),h.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&h.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(c,r,d)),l.pointsCloud&&h.push("#define POINTSIZE"),t&&(h.push("#define INSTANCES"),Me.PushAttributesForInstances(c),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&h.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&h.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&h.push("#define PACKED"),xh(l,n,h);const f=e._getDrawWrapper(void 0,!0),p=f.defines,_=h.join(` +`);if(p!==_){const g=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];Ao(g),f.setEffect(s.createEffect("depth",c,g,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),_)}return f.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]}}}sc._SceneComponentInitialization=o=>{throw xt("DepthRendererSceneComponent")};const bG="minmaxReduxPixelShader",yG=`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); @@ -7537,33 +7537,33 @@ void main(void) {glFragColor=vec4(0.);if (true) { discard;}} #endif -`;ne.ShadersStore[EG]=SG;class CG{constructor(e){this.onAfterReductionPerformed=new he,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new A_(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 lt("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 a=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();n.onApply=((c,u)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",c,u)})(a,l),this._reductionSteps.push(n);let h=1;for(;a>1||l>1;){a=Math.max(Math.round(a/2),1),l=Math.max(Math.round(l/2),1);const c=new lt("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:a,height:l},null,1,r.getEngine(),!1,"#define "+(a==1&&l==1?"LAST":a==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)})(a,l),this._reductionSteps.push(c),h++,a==1&&l==1){const u=(d,f,p)=>{const _=new Float32Array(4*d*f),g={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(p.inputTexture.texture,d,f,-1,0,_,!1),g.min=_[0],g.max=_[1],this.onAfterReductionPerformed.notifyObservers(g)}};c.onAfterRenderObservable.add(u(a,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 e,t;const i=this._camera.getScene().getEngine();(e=i._debugPushGroup)===null||e===void 0||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(t=i._debugPopGroup)===null||t===void 0||t.call(i,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;tthis._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;it&&(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 Pr.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.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=0&&e=0&&e{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,i;return(i=(t=(e=this._depthReducer)===null||e===void 0?void 0:e.depthRenderer)===null||t===void 0?void 0:t.getDepthMap().refreshRate)!==null&&i!==void 0?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;!((t=this._depthReducer)===null||t===void 0)&&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=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+r*s,l=t+n*s,h=l-a,c=l/a;for(let u=0;u{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===St.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===void 0||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!==St.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 a=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===St.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===St.FILTER_PCSS){for(let l=0;lnew Pr(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}}Pr._FrustumCornersNDCSpace=[new T(-1,1,-1),new T(1,1,-1),new T(1,-1,-1),new T(-1,-1,-1),new T(-1,1,1),new T(1,1,1),new T(1,-1,1),new T(-1,-1,1)];Pr.CLASSNAME="CascadedShadowGenerator";Pr.DEFAULT_CASCADES_COUNT=4;Pr.MIN_CASCADES_COUNT=2;Pr.MAX_CASCADES_COUNT=4;Pr._SceneComponentInitialization=o=>{throw xt("ShadowGeneratorSceneComponent")};ks.AddParser(Fe.NAME_SHADOWGENERATOR,(o,e)=>{if(o.shadowGenerators!==void 0&&o.shadowGenerators!==null)for(let t=0,i=o.shadowGenerators.length;t{let e=o._getComponent(Fe.NAME_SHADOWGENERATOR);e||(e=new AG(o),o._addComponent(e))};Mi.AddNodeConstructor("Light_Type_0",(o,e)=>()=>new eT(o,T.Zero(),e));class eT extends tc{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 Yt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new T(1,0,0);case 1:return new T(-1,0,0);case 2:return new T(0,-1,0);case 3:return new T(0,1,0);case 4:return new T(0,0,1);case 5:return new T(0,0,-1)}return T.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,n=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:r,a?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}A([D()],eT.prototype,"shadowAngle",null);class th{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);} +`;ne.ShadersStore[bG]=yG;class AG{constructor(e){this.onAfterReductionPerformed=new he,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new A_(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 lt("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 a=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();n.onApply=((c,u)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",c,u)})(a,l),this._reductionSteps.push(n);let h=1;for(;a>1||l>1;){a=Math.max(Math.round(a/2),1),l=Math.max(Math.round(l/2),1);const c=new lt("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:a,height:l},null,1,r.getEngine(),!1,"#define "+(a==1&&l==1?"LAST":a==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)})(a,l),this._reductionSteps.push(c),h++,a==1&&l==1){const u=(d,f,p)=>{const _=new Float32Array(4*d*f),g={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(p.inputTexture.texture,d,f,-1,0,_,!1),g.min=_[0],g.max=_[1],this.onAfterReductionPerformed.notifyObservers(g)}};c.onAfterRenderObservable.add(u(a,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 e,t;const i=this._camera.getScene().getEngine();(e=i._debugPushGroup)===null||e===void 0||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),(t=i._debugPopGroup)===null||t===void 0||t.call(i,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;tthis._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;it&&(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 Pr.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.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=0&&e=0&&e{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,i;return(i=(t=(e=this._depthReducer)===null||e===void 0?void 0:e.depthRenderer)===null||t===void 0?void 0:t.getDepthMap().refreshRate)!==null&&i!==void 0?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;!((t=this._depthReducer)===null||t===void 0)&&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=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+r*s,l=t+n*s,h=l-a,c=l/a;for(let u=0;u{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===St.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===void 0||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!==St.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 a=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===St.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===St.FILTER_PCSS){for(let l=0;lnew Pr(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}}Pr._FrustumCornersNDCSpace=[new T(-1,1,-1),new T(1,1,-1),new T(1,-1,-1),new T(-1,-1,-1),new T(-1,1,1),new T(1,1,1),new T(1,-1,1),new T(-1,-1,1)];Pr.CLASSNAME="CascadedShadowGenerator";Pr.DEFAULT_CASCADES_COUNT=4;Pr.MIN_CASCADES_COUNT=2;Pr.MAX_CASCADES_COUNT=4;Pr._SceneComponentInitialization=o=>{throw xt("ShadowGeneratorSceneComponent")};ks.AddParser(Fe.NAME_SHADOWGENERATOR,(o,e)=>{if(o.shadowGenerators!==void 0&&o.shadowGenerators!==null)for(let t=0,i=o.shadowGenerators.length;t{let e=o._getComponent(Fe.NAME_SHADOWGENERATOR);e||(e=new PG(o),o._addComponent(e))};Mi.AddNodeConstructor("Light_Type_0",(o,e)=>()=>new iT(o,T.Zero(),e));class iT extends ic{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 Yt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new T(1,0,0);case 1:return new T(-1,0,0);case 2:return new T(0,-1,0);case 3:return new T(0,1,0);case 4:return new T(0,0,1);case 5:return new T(0,0,-1)}return T.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,n=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;k.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:r,a?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}A([D()],iT.prototype,"shadowAngle",null);class ih{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;th.DefaultLogoUrl?i.src=th.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(th.DefaultSpinnerUrl?r.src=th.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},a={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=`${a.w}vh`,r.style.height=`${a.h}vh`,r.style.left=`calc(50% - ${a.w/2}vh)`,r.style.top=`calc(50% - ${a.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)}}th.DefaultLogoUrl="";th.DefaultSpinnerUrl="";re.DefaultLoadingScreenFactory=o=>new th(o);class Eh{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),a=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:a,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 a=new ArrayBuffer(e*e*4*3),l=new Float32Array(a),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),p=1/e;let _=0;for(let g=0;gMath.PI;)r-=2*Math.PI;let a=r/Math.PI;const l=n/Math.PI;a=a*.5+.5;let h=Math.round(a*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],p=t[u*i*3+h*3+2];return{r:d,g:f,b:p}}}Eh.FACE_LEFT=[new T(-1,-1,-1),new T(1,-1,-1),new T(-1,1,-1),new T(1,1,-1)];Eh.FACE_RIGHT=[new T(1,-1,1),new T(-1,-1,1),new T(1,1,1),new T(-1,1,1)];Eh.FACE_FRONT=[new T(1,-1,-1),new T(1,-1,1),new T(1,1,-1),new T(1,1,1)];Eh.FACE_BACK=[new T(-1,-1,1),new T(-1,-1,-1),new T(-1,1,1),new T(-1,1,-1)];Eh.FACE_DOWN=[new T(1,1,-1),new T(1,1,1),new T(-1,1,-1),new T(-1,1,1)];Eh.FACE_UP=[new T(-1,-1,-1),new T(-1,-1,1),new T(1,-1,-1),new T(1,-1,1)];class Hv{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-136),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;r32767)throw"HDR Bad header format, unsupported size";return a+=s.length+1,{height:t,width:i,dataPosition:a}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return Eh.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,a,l,h,c=t.dataPosition,u=0,d=0,f=0;const p=new ArrayBuffer(s*4),_=new Uint8Array(p),g=new ArrayBuffer(t.width*t.height*4*3),v=new Float32Array(g);for(;i>0;){if(r=e[c++],n=e[c++],a=e[c++],l=e[c++],r!=2||n!=2||a&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((a<<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;u128){if(h=r-128,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (run)";for(;h-- >0;)_[u++]=n}else{if(h=r,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=n,--h>0)for(let E=0;E0;){for(h=0;h{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)}}ih.DefaultLogoUrl="";ih.DefaultSpinnerUrl="";re.DefaultLoadingScreenFactory=o=>new ih(o);class Sh{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),a=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:a,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 a=new ArrayBuffer(e*e*4*3),l=new Float32Array(a),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),p=1/e;let _=0;for(let g=0;gMath.PI;)r-=2*Math.PI;let a=r/Math.PI;const l=n/Math.PI;a=a*.5+.5;let h=Math.round(a*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],p=t[u*i*3+h*3+2];return{r:d,g:f,b:p}}}Sh.FACE_LEFT=[new T(-1,-1,-1),new T(1,-1,-1),new T(-1,1,-1),new T(1,1,-1)];Sh.FACE_RIGHT=[new T(1,-1,1),new T(-1,-1,1),new T(1,1,1),new T(-1,1,1)];Sh.FACE_FRONT=[new T(1,-1,-1),new T(1,-1,1),new T(1,1,-1),new T(1,1,1)];Sh.FACE_BACK=[new T(-1,-1,1),new T(-1,-1,-1),new T(-1,1,1),new T(-1,1,-1)];Sh.FACE_DOWN=[new T(1,1,-1),new T(1,1,1),new T(-1,1,-1),new T(-1,1,1)];Sh.FACE_UP=[new T(-1,-1,-1),new T(-1,-1,1),new T(1,-1,-1),new T(1,-1,1)];class Hv{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-136),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;r32767)throw"HDR Bad header format, unsupported size";return a+=s.length+1,{height:t,width:i,dataPosition:a}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return Sh.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,a,l,h,c=t.dataPosition,u=0,d=0,f=0;const p=new ArrayBuffer(s*4),_=new Uint8Array(p),g=new ArrayBuffer(t.width*t.height*4*3),v=new Float32Array(g);for(;i>0;){if(r=e[c++],n=e[c++],a=e[c++],l=e[c++],r!=2||n!=2||a&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((a<<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;u128){if(h=r-128,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (run)";for(;h-- >0;)_[u++]=n}else{if(h=r,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=n,--h>0)for(let E=0;E0;){for(h=0;h +}`;ne.ShadersStore[MG]=DG;const OG="hdrFilteringPixelShader",NG=`#include #include #include #include -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);}`;ne.ShadersStore[PG]=MG;class xy{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=ye.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 a=[[new T(0,0,-1),new T(0,-1,0),new T(1,0,0)],[new T(0,0,1),new T(0,-1,0),new T(-1,0,0)],[new T(1,0,0),new T(0,0,1),new T(0,1,0)],[new T(1,0,0),new T(0,0,-1),new T(0,-1,0)],[new T(1,0,0),new T(0,-1,0),new T(0,0,1)],[new T(-1,0,0),new T(0,-1,0),new T(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",a[c][0]),s.setVector3("right",a[c][1]),s.setVector3("front",a[c][2]);for(let u=0;u{this._effectRenderer=new am(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(G.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 Yh extends Ei{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(k.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,a=!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=T.Zero(),this.onLoadObservable=new he,e&&(this._coordinatesMode=ee.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=k.Identity(),this._prefilterOnLoad=a,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?fe.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):!((u=this.getScene())===null||u===void 0)&&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=Hv.GetCubeMapTextureData(r,this._size,this._supersample);if(this._generateHarmonics){const c=vu.ConvertCubeMapToSphericalPolynomial(n);this.sphericalPolynomial=c}const a=[];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[Yh._FacesMapping[c]];if(this.gammaSpace||h||l){for(let d=0;d255){const v=255/g;f*=v,p*=v,_*=v}l[d*3+0]=f,l[d*3+1]=p,l[d*3+2]=_}}h?a.push(h):l?a.push(l):a.push(u)}return a};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const r=this._onLoad,n=new xy(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 Yh(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===void 0||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 Yh(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=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.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}}Yh._FacesMapping=["right","left","up","down","front","back"];j("BABYLON.HDRCubeTexture",Yh);class Hc{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 he,this._onDataLayoutChanged=new he,this._animationPropertiesOverride=null,this._scene=i||ht.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=Xe.Clone(()=>new Hc(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())),Xe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Hc(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;s0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new qs(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=ht.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 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 bl.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(!((e=this._scene)===null||e===void 0)&&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)}clone(){const e=new bl(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>=bl.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){G.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;se&&(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-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 bl(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(Hc.Parse(s,t));return i}}bl.EnableTextureStorage=!0;bl.MaxActiveMorphTargetsInVertexAttributeMode=8;class Fm{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=T.Zero(),this._hitPointWorld=T.Zero(),this._rayFromWorld=T.Zero(),this._rayToWorld=T.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=i??-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=T.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=T.Zero(),t=T.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}}let Ty=class Ey{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("CannonJSPlugin")}constructor(e,t=Ey.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 T(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;t0&&(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){G.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 a in n)Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a]);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(a){const l=i[a];e.physicsBody[a].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(a=>!!a.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 ts.HingeJoint:case ts.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case ts.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case ts.SpringJoint:{const a=r;s=new this.BJSCANNON.Spring(t,i,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case ts.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case ts.PointToPointJoint:case ts.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!==ts.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!==ts.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;si*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))}}Ty.DefaultPluginFactory=()=>new V_;class aC{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=T.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Fm}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){G.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];(a=>{a.getChildMeshes&&a.getChildMeshes().forEach(function(l){l.physicsImpostor&&i.push(l.physicsImpostor)})})(e.object);const r=a=>Math.max(a,$t),n=new Se;i.forEach(a=>{if(!a.object.rotationQuaternion)return;const l=a.object.rotationQuaternion;n.copyFrom(l),a.object.rotationQuaternion.set(0,0,0,1),a.object.computeWorldMatrix(!0);const h=n.toEulerAngles(),c=a.getObjectExtents(),u=57.29577951308232;if(a===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=a.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(a.object.rotationQuaternion.copyFrom(n),a.type){case Ct.ParticleImpostor:G.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Ct.SphereImpostor:{const d=c.x,f=c.y,p=c.z,_=Math.max(r(d),r(f),r(p))/2;t.type.push("sphere"),t.size.push(_),t.size.push(_),t.size.push(_);break}case Ct.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 Ct.PlaneImpostor:case Ct.BoxImpostor:default:{const d=r(c.x),f=r(c.y),p=r(c.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(p);break}}a.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 a={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 ts.BallAndSocketJoint:n="jointBall";break;case ts.SpringJoint:{G.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=s;a.min=l.length||a.min,a.max=Math.max(a.min,a.max)}case ts.DistanceJoint:n="jointDistance",a.max=s.maxDistance;break;case ts.PrismaticJoint:n="jointPrisme";break;case ts.SliderJoint:n="jointSlide";break;case ts.WheelJoint:n="jointWheel";break;case ts.HingeJoint:default:n="jointHinge";break}a.type=n,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){G.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 T(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new T(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?G.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 G.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){G.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class $o{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 Se,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new T,this._tmpContactNormal=new T,this._tmpVec3=new T,this._tmpMatrix=new k,typeof t=="function"){G.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){G.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 Fm,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-i0&&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===Ct.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,a,l;const h=new Array;for(let d=0;d{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 T(0,0,0)),s.connectedPivot||(s.connectedPivot=new T(0,0,0));let r;switch(e.joint.type){case ts.DistanceJoint:{const n=s.maxDistance;n&&(s.mainPivot=new T(0,-n/2,0),s.connectedPivot=new T(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 ts.HingeJoint:{s.mainAxis||(s.mainAxis=new T(0,0,0)),s.connectedAxis||(s.connectedAxis=new T(0,0,0));const n=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),a=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,a);break}case ts.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:G.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(P.PositionKind);n||(n=[]);let a;if(t&&t!==i){let h;t.rotationQuaternion?h=t.rotationQuaternion:t.rotation?h=Se.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):h=Se.Identity(),k.Compose(T.One(),h,t.position).invertToRef(this._tmpMatrix),a=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else k.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),a=this._tmpMatrix;const l=r.length/3;for(let h=0;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(P.PositionKind);i||(i=[]);let s=t.getVerticesData(P.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let l=0;ld*d),l=(d,f)=>d+f;if(a.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 G.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(P.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const a=r.length/3;for(let l=0;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 a=0;if(n.forEach(l=>{const h=l.getPhysicsImpostor();if(h){if(h.type==Ct.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 T;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(),a++}}),a>0){if(e.type!=Ct.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 Ct.SphereImpostor:if(ye.WithinEpsilon(r.x,r.y,1e-4)&&ye.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)],a=[1];s=new this.bjsAMMO.btMultiSphereShape(n,a,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case Ct.CapsuleImpostor:{const n=r.x/2;s=new this.bjsAMMO.btCapsuleShape(n,r.y-n*2)}break;case Ct.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Ct.PlaneImpostor:case Ct.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Ct.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 Ct.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 Ct.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case Ct.CustomImpostor:s=this._createCustom(e);break;case Ct.SoftbodyImpostor:s=this._createSoftbody(e);break;case Ct.ClothImpostor:s=this._createCloth(e);break;case Ct.RopeImpostor:s=this._createRope(e);break;default:G.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)>$t||Math.abs(s.getOrigin().y()-t.y)>$t||Math.abs(s.getOrigin().z()-t.z)>$t||Math.abs(s.getRotation().x()-i.x)>$t||Math.abs(s.getRotation().y()-i.y)>$t||Math.abs(s.getRotation().z()-i.z)>$t||Math.abs(s.getRotation().w()-i.w)>$t)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 T(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 T(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:(G.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===Ct.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):G.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(G.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):G.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(G.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):G.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(G.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):G.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const a=e.segments,l=Math.round((a-1)*i),h=Math.round((a-1)*s),c=a-1-h,u=l+a*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(){G.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){G.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)}}$o._DISABLE_COLLISION_FLAG=4;$o._KINEMATIC_FLAG=2;$o._DISABLE_DEACTIVATION_FLAG=4;ks.prototype.removeReflectionProbe=function(o){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(o);return e!==-1&&this.reflectionProbes.splice(e,1),e};ks.prototype.addReflectionProbe=function(o){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(o)};class op{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=k.Identity(),this._target=T.Zero(),this._add=T.Zero(),this._invertYAxis=!1,this.position=T.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 a=0;if(r){const c=this._scene.getEngine().getCaps();c.textureHalfFloatRender?a=2:c.textureFloatRender&&(a=1)}this._renderTargetTexture=new ms(e,t,i,s,!0,a,!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?k.LookAtRHToRef:k.LookAtLHToRef,d=i.useRightHandedSystem?k.PerspectiveFovRH:k.PerspectiveFovLH;u(this.position,this._target,T.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===void 0||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===void 0||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=Xe.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;rs||new op(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}}A([Qf()],op.prototype,"_attachedMesh",void 0);A([kr()],op.prototype,"position",void 0);class S_{}S_.LoaderInjectedPhysicsEngine=void 0;let Pc={},ih={};const oC=(o,e,t,i)=>{if(!e.materials)return null;for(let s=0,r=e.materials.length;s{for(const i in e)if(o.name===e[i])return t.push(o.id),!0;return o.parentId!==void 0&&t.indexOf(o.parentId)!==-1?(t.push(o.id),!0):!1},Fc=(o,e)=>o+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),Sy=(o,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 a=0;a0&&t.addLODLevel(n,null),s===!0&&t.setEnabled(!0)}else fe.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},d_=(o,e,t)=>{if(typeof o!="number"){const s=t.getLastEntryById(o);return s&&e!==void 0&&e!==null?s.instances[parseInt(e)]:s}const i=Pc[o];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},U_=(o,e)=>typeof o!="number"?e.getLastMaterialById(o,!0):ih[o],lC=(o,e,t,i,s=!1)=>{const r=new iF(o);let n="importScene has failed JSON parse";try{var a=JSON.parse(e);n="";const l=Ft.loggingLevel===Ft.DETAILED_LOGGING;let h,c;if(a.environmentTexture!==void 0&&a.environmentTexture!==null){const d=a.isPBR!==void 0?a.isPBR:!0;if(a.environmentTextureType&&a.environmentTextureType==="BABYLON.HDRCubeTexture"){const f=a.environmentTextureSize?a.environmentTextureSize:128,p=new Yh((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,f,!0,!d,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(p.rotationY=a.environmentTextureRotationY),o.environmentTexture=p}else if(typeof a.environmentTexture=="object"){const f=lr.Parse(a.environmentTexture,o,t);o.environmentTexture=f}else if(a.environmentTexture.endsWith(".env")){const f=new lr((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(f.rotationY=a.environmentTextureRotationY),o.environmentTexture=f}else{const f=lr.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(f.rotationY=a.environmentTextureRotationY),o.environmentTexture=f}if(a.createDefaultSkybox===!0){const f=o.activeCamera!==void 0&&o.activeCamera!==null?(o.activeCamera.maxZ-o.activeCamera.minZ)/2:1e3,p=a.skyboxBlurLevel||0;o.createDefaultSkybox(o.environmentTexture,d,f,p)}r.environmentTexture=o.environmentTexture}if(a.environmentIntensity!==void 0&&a.environmentIntensity!==null&&(o.environmentIntensity=a.environmentIntensity),a.lights!==void 0&&a.lights!==null)for(h=0,c=a.lights.length;h{this._effectRenderer=new am(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(G.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 $h extends Ei{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(k.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,a=!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=T.Zero(),this.onLoadObservable=new he,e&&(this._coordinatesMode=ee.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=k.Identity(),this._prefilterOnLoad=a,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?fe.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):!((u=this.getScene())===null||u===void 0)&&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=Hv.GetCubeMapTextureData(r,this._size,this._supersample);if(this._generateHarmonics){const c=vu.ConvertCubeMapToSphericalPolynomial(n);this.sphericalPolynomial=c}const a=[];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[$h._FacesMapping[c]];if(this.gammaSpace||h||l){for(let d=0;d255){const v=255/g;f*=v,p*=v,_*=v}l[d*3+0]=f,l[d*3+1]=p,l[d*3+2]=_}}h?a.push(h):l?a.push(l):a.push(u)}return a};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const r=this._onLoad,n=new Ey(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 $h(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===void 0||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 $h(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=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.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}}$h._FacesMapping=["right","left","up","down","front","back"];j("BABYLON.HDRCubeTexture",$h);class Hc{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 he,this._onDataLayoutChanged=new he,this._animationPropertiesOverride=null,this._scene=i||ht.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=Xe.Clone(()=>new Hc(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())),Xe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Hc(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;s0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new qs(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=ht.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 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 bl.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(!((e=this._scene)===null||e===void 0)&&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)}clone(){const e=new bl(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>=bl.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){G.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;se&&(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-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 bl(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(Hc.Parse(s,t));return i}}bl.EnableTextureStorage=!0;bl.MaxActiveMorphTargetsInVertexAttributeMode=8;class Fm{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=T.Zero(),this._hitPointWorld=T.Zero(),this._rayFromWorld=T.Zero(),this._rayToWorld=T.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=i??-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=T.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=T.Zero(),t=T.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}}let Sy=class Cy{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("CannonJSPlugin")}constructor(e,t=Cy.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 T(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;t0&&(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){G.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 a in n)Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a]);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(a){const l=i[a];e.physicsBody[a].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(a=>!!a.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 ts.HingeJoint:case ts.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case ts.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case ts.SpringJoint:{const a=r;s=new this.BJSCANNON.Spring(t,i,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case ts.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case ts.PointToPointJoint:case ts.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!==ts.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!==ts.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;si*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))}}Sy.DefaultPluginFactory=()=>new V_;class lC{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=T.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Fm}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){G.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];(a=>{a.getChildMeshes&&a.getChildMeshes().forEach(function(l){l.physicsImpostor&&i.push(l.physicsImpostor)})})(e.object);const r=a=>Math.max(a,$t),n=new Se;i.forEach(a=>{if(!a.object.rotationQuaternion)return;const l=a.object.rotationQuaternion;n.copyFrom(l),a.object.rotationQuaternion.set(0,0,0,1),a.object.computeWorldMatrix(!0);const h=n.toEulerAngles(),c=a.getObjectExtents(),u=57.29577951308232;if(a===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=a.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(a.object.rotationQuaternion.copyFrom(n),a.type){case Ct.ParticleImpostor:G.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Ct.SphereImpostor:{const d=c.x,f=c.y,p=c.z,_=Math.max(r(d),r(f),r(p))/2;t.type.push("sphere"),t.size.push(_),t.size.push(_),t.size.push(_);break}case Ct.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 Ct.PlaneImpostor:case Ct.BoxImpostor:default:{const d=r(c.x),f=r(c.y),p=r(c.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(p);break}}a.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 a={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 ts.BallAndSocketJoint:n="jointBall";break;case ts.SpringJoint:{G.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=s;a.min=l.length||a.min,a.max=Math.max(a.min,a.max)}case ts.DistanceJoint:n="jointDistance",a.max=s.maxDistance;break;case ts.PrismaticJoint:n="jointPrisme";break;case ts.SliderJoint:n="jointSlide";break;case ts.WheelJoint:n="jointWheel";break;case ts.HingeJoint:default:n="jointHinge";break}a.type=n,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){G.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 T(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new T(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?G.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 G.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){G.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class $o{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 Se,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new T,this._tmpContactNormal=new T,this._tmpVec3=new T,this._tmpMatrix=new k,typeof t=="function"){G.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){G.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 Fm,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-i0&&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===Ct.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,a,l;const h=new Array;for(let d=0;d{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 T(0,0,0)),s.connectedPivot||(s.connectedPivot=new T(0,0,0));let r;switch(e.joint.type){case ts.DistanceJoint:{const n=s.maxDistance;n&&(s.mainPivot=new T(0,-n/2,0),s.connectedPivot=new T(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 ts.HingeJoint:{s.mainAxis||(s.mainAxis=new T(0,0,0)),s.connectedAxis||(s.connectedAxis=new T(0,0,0));const n=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),a=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,a);break}case ts.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:G.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(P.PositionKind);n||(n=[]);let a;if(t&&t!==i){let h;t.rotationQuaternion?h=t.rotationQuaternion:t.rotation?h=Se.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):h=Se.Identity(),k.Compose(T.One(),h,t.position).invertToRef(this._tmpMatrix),a=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else k.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),a=this._tmpMatrix;const l=r.length/3;for(let h=0;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(P.PositionKind);i||(i=[]);let s=t.getVerticesData(P.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let l=0;ld*d),l=(d,f)=>d+f;if(a.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 G.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(P.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const a=r.length/3;for(let l=0;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 a=0;if(n.forEach(l=>{const h=l.getPhysicsImpostor();if(h){if(h.type==Ct.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 T;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(),a++}}),a>0){if(e.type!=Ct.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 Ct.SphereImpostor:if(ye.WithinEpsilon(r.x,r.y,1e-4)&&ye.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)],a=[1];s=new this.bjsAMMO.btMultiSphereShape(n,a,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case Ct.CapsuleImpostor:{const n=r.x/2;s=new this.bjsAMMO.btCapsuleShape(n,r.y-n*2)}break;case Ct.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Ct.PlaneImpostor:case Ct.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Ct.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 Ct.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 Ct.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case Ct.CustomImpostor:s=this._createCustom(e);break;case Ct.SoftbodyImpostor:s=this._createSoftbody(e);break;case Ct.ClothImpostor:s=this._createCloth(e);break;case Ct.RopeImpostor:s=this._createRope(e);break;default:G.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)>$t||Math.abs(s.getOrigin().y()-t.y)>$t||Math.abs(s.getOrigin().z()-t.z)>$t||Math.abs(s.getRotation().x()-i.x)>$t||Math.abs(s.getRotation().y()-i.y)>$t||Math.abs(s.getRotation().z()-i.z)>$t||Math.abs(s.getRotation().w()-i.w)>$t)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 T(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 T(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:(G.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===Ct.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):G.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(G.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):G.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(G.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):G.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(G.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):G.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const a=e.segments,l=Math.round((a-1)*i),h=Math.round((a-1)*s),c=a-1-h,u=l+a*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(){G.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){G.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)}}$o._DISABLE_COLLISION_FLAG=4;$o._KINEMATIC_FLAG=2;$o._DISABLE_DEACTIVATION_FLAG=4;ks.prototype.removeReflectionProbe=function(o){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(o);return e!==-1&&this.reflectionProbes.splice(e,1),e};ks.prototype.addReflectionProbe=function(o){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(o)};class op{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=k.Identity(),this._target=T.Zero(),this._add=T.Zero(),this._invertYAxis=!1,this.position=T.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 a=0;if(r){const c=this._scene.getEngine().getCaps();c.textureHalfFloatRender?a=2:c.textureFloatRender&&(a=1)}this._renderTargetTexture=new ms(e,t,i,s,!0,a,!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?k.LookAtRHToRef:k.LookAtLHToRef,d=i.useRightHandedSystem?k.PerspectiveFovRH:k.PerspectiveFovLH;u(this.position,this._target,T.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===void 0||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===void 0||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=Xe.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;rs||new op(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}}A([Qf()],op.prototype,"_attachedMesh",void 0);A([kr()],op.prototype,"position",void 0);class S_{}S_.LoaderInjectedPhysicsEngine=void 0;let Pc={},sh={};const hC=(o,e,t,i)=>{if(!e.materials)return null;for(let s=0,r=e.materials.length;s{for(const i in e)if(o.name===e[i])return t.push(o.id),!0;return o.parentId!==void 0&&t.indexOf(o.parentId)!==-1?(t.push(o.id),!0):!1},Fc=(o,e)=>o+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),by=(o,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 a=0;a0&&t.addLODLevel(n,null),s===!0&&t.setEnabled(!0)}else fe.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},d_=(o,e,t)=>{if(typeof o!="number"){const s=t.getLastEntryById(o);return s&&e!==void 0&&e!==null?s.instances[parseInt(e)]:s}const i=Pc[o];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},U_=(o,e)=>typeof o!="number"?e.getLastMaterialById(o,!0):sh[o],cC=(o,e,t,i,s=!1)=>{const r=new nF(o);let n="importScene has failed JSON parse";try{var a=JSON.parse(e);n="";const l=Lt.loggingLevel===Lt.DETAILED_LOGGING;let h,c;if(a.environmentTexture!==void 0&&a.environmentTexture!==null){const d=a.isPBR!==void 0?a.isPBR:!0;if(a.environmentTextureType&&a.environmentTextureType==="BABYLON.HDRCubeTexture"){const f=a.environmentTextureSize?a.environmentTextureSize:128,p=new $h((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,f,!0,!d,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(p.rotationY=a.environmentTextureRotationY),o.environmentTexture=p}else if(typeof a.environmentTexture=="object"){const f=lr.Parse(a.environmentTexture,o,t);o.environmentTexture=f}else if(a.environmentTexture.endsWith(".env")){const f=new lr((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(f.rotationY=a.environmentTextureRotationY),o.environmentTexture=f}else{const f=lr.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":t)+a.environmentTexture,o,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(f.rotationY=a.environmentTextureRotationY),o.environmentTexture=f}if(a.createDefaultSkybox===!0){const f=o.activeCamera!==void 0&&o.activeCamera!==null?(o.activeCamera.maxZ-o.activeCamera.minZ)/2:1e3,p=a.skyboxBlurLevel||0;o.createDefaultSkybox(o.environmentTexture,d,f,p)}r.environmentTexture=o.environmentTexture}if(a.environmentIntensity!==void 0&&a.environmentIntensity!==null&&(o.environmentIntensity=a.environmentIntensity),a.lights!==void 0&&a.lights!==null)for(h=0,c=a.lights.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)}))}if(a.multiMaterials!==void 0&&a.multiMaterials!==null)for(h=0,c=a.multiMaterials.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)}))}if(a.multiMaterials!==void 0&&a.multiMaterials!==null)for(h=0,c=a.multiMaterials.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)})}if(a.morphTargetManagers!==void 0&&a.morphTargetManagers!==null)for(const d of a.morphTargetManagers){const f=bl.Parse(d,o);r.morphTargetManagers.push(f),f._parentContainer=r}if(a.skeletons!==void 0&&a.skeletons!==null)for(h=0,c=a.skeletons.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)})}if(a.morphTargetManagers!==void 0&&a.morphTargetManagers!==null)for(const d of a.morphTargetManagers){const f=bl.Parse(d,o);r.morphTargetManagers.push(f),f._parentContainer=r}if(a.skeletons!==void 0&&a.skeletons!==null)for(h=0,c=a.skeletons.length;h{p&&(r.geometries.push(p),p._parentContainer=r)})}if(a.transformNodes!==void 0&&a.transformNodes!==null)for(h=0,c=a.transformNodes.length;h{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(U_(f,o))}),d._waitingSubMaterialsUniqueIds=[]}),o.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=U_(d._waitingMaterialId,o),d._waitingMaterialId=null)}),h=0,c=o.skeletons.length;h{if(f._waitingTransformNodeId){const p=o.getLastEntryById(f._waitingTransformNodeId);p&&f.linkTransformNode(p),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(h=0,c=o.meshes.length;h0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),ks.Parse(a,o,r,t),h=0,c=o.meshes.length;ho.indexOf("babylon")!==-1,importMesh:(o,e,t,i,s,r,n,a)=>{var l;let h="importMesh has failed JSON parse";try{var c=JSON.parse(t);h="";const u=Ft.loggingLevel===Ft.DETAILED_LOGGING;o?Array.isArray(o)||(o=[o]):o=null;const d=[],f=new Map,p=[];if(c.transformNodes!==void 0&&c.transformNodes!==null)for(let _=0,g=c.transformNodes.length;_{N===!0||!c.geometries[O]||!Array.isArray(c.geometries[O])||c.geometries[O].forEach(L=>{if(L.id===R.geometryId){switch(O){case"vertexData":sn.Parse(L,e,i);break}N=!0}})}),N===!1&&G.Warn("Geometry not found for mesh "+R.id)}if(R.materialUniqueId||R.materialId){const N=R.materialUniqueId?v:g;let O=N.indexOf(R.materialUniqueId||R.materialId)!==-1;if(O===!1&&c.multiMaterials!==void 0&&c.multiMaterials!==null){const L=(B,V)=>{N.push(B);const Z=oC(V,c,e,i);Z&&Z.material&&(ih[Z.parsedMaterial.uniqueId||Z.parsedMaterial.id]=Z.material,h+=` - Material `+Z.material.toString(u))};for(let B=0,V=c.multiMaterials.length;BL(oe,me=>me.uniqueId===oe)):Z.materials.forEach(oe=>L(oe,me=>me.id===oe)),N.push(Z.uniqueId||Z.id);const ue=dh.ParseMultiMaterial(Z,e);ih[Z.uniqueId||Z.id]=ue,ue&&(O=!0,h+=` - Multi-Material `+ue.toString(u));break}}}if(O===!1){N.push(R.materialUniqueId||R.materialId);const L=oC(B=>R.materialUniqueId&&B.uniqueId===R.materialUniqueId||B.id===R.materialId,c,e,i);!L||!L.material?G.Warn("Material not found for mesh "+R.id):(ih[L.parsedMaterial.uniqueId||L.parsedMaterial.id]=L.material,h+=` - Material `+L.material.toString(u))}}if(R.skeletonId!==null&&R.skeletonId!==void 0&&c.skeletonId!==-1&&c.skeletons!==void 0&&c.skeletons!==null&&!(_.indexOf(R.skeletonId)>-1))for(let O=0,L=c.skeletons.length;O{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(U_(f,o))}),d._waitingSubMaterialsUniqueIds=[]}),o.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=U_(d._waitingMaterialId,o),d._waitingMaterialId=null)}),h=0,c=o.skeletons.length;h{if(f._waitingTransformNodeId){const p=o.getLastEntryById(f._waitingTransformNodeId);p&&f.linkTransformNode(p),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(h=0,c=o.meshes.length;h0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),ks.Parse(a,o,r,t),h=0,c=o.meshes.length;ho.indexOf("babylon")!==-1,importMesh:(o,e,t,i,s,r,n,a)=>{var l;let h="importMesh has failed JSON parse";try{var c=JSON.parse(t);h="";const u=Lt.loggingLevel===Lt.DETAILED_LOGGING;o?Array.isArray(o)||(o=[o]):o=null;const d=[],f=new Map,p=[];if(c.transformNodes!==void 0&&c.transformNodes!==null)for(let _=0,g=c.transformNodes.length;_{N===!0||!c.geometries[O]||!Array.isArray(c.geometries[O])||c.geometries[O].forEach(L=>{if(L.id===R.geometryId){switch(O){case"vertexData":sn.Parse(L,e,i);break}N=!0}})}),N===!1&&G.Warn("Geometry not found for mesh "+R.id)}if(R.materialUniqueId||R.materialId){const N=R.materialUniqueId?v:g;let O=N.indexOf(R.materialUniqueId||R.materialId)!==-1;if(O===!1&&c.multiMaterials!==void 0&&c.multiMaterials!==null){const L=(B,V)=>{N.push(B);const Z=hC(V,c,e,i);Z&&Z.material&&(sh[Z.parsedMaterial.uniqueId||Z.parsedMaterial.id]=Z.material,h+=` + Material `+Z.material.toString(u))};for(let B=0,V=c.multiMaterials.length;BL(oe,me=>me.uniqueId===oe)):Z.materials.forEach(oe=>L(oe,me=>me.id===oe)),N.push(Z.uniqueId||Z.id);const ue=fh.ParseMultiMaterial(Z,e);sh[Z.uniqueId||Z.id]=ue,ue&&(O=!0,h+=` + Multi-Material `+ue.toString(u));break}}}if(O===!1){N.push(R.materialUniqueId||R.materialId);const L=hC(B=>R.materialUniqueId&&B.uniqueId===R.materialUniqueId||B.id===R.materialId,c,e,i);!L||!L.material?G.Warn("Material not found for mesh "+R.id):(sh[L.parsedMaterial.uniqueId||L.parsedMaterial.id]=L.material,h+=` + Material `+L.material.toString(u))}}if(R.skeletonId!==null&&R.skeletonId!==void 0&&c.skeletonId!==-1&&c.skeletons!==void 0&&c.skeletons!==null&&!(_.indexOf(R.skeletonId)>-1))for(let O=0,L=c.skeletons.length;O-1&&c.morphTargetManagers!==void 0&&c.morphTargetManagers!==null&&!(E.indexOf(R.morphTargetManagerId)>-1))for(let O=0,L=c.morphTargetManagers.length;O{S._waitingSubMaterialsUniqueIds.forEach(b=>{S.subMaterials.push(U_(b,e))}),S._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(S=>{S._waitingMaterialId!==null&&(S.material=U_(S._waitingMaterialId,e),S._waitingMaterialId=null)});for(let S=0,b=e.transformNodes.length;S-1&&p.splice(N,1)}C._waitingParentId=null}C._waitingData.lods&&Sy(e,C)}for(const S of p)S.dispose();for(let S=0,b=e.skeletons.length;S{if(I._waitingTransformNodeId){const N=e.getLastEntryById(I._waitingTransformNodeId);N&&I.linkTransformNode(N),I._waitingTransformNodeId=null}}),R._hasWaitingData=null)}for(let S=0,b=e.meshes.length;S{_._loadedUniqueId=""}),!0}catch(u){const d=Fc("importMesh",c?c.producer:"Unknown")+h;if(a)a(d,u);else throw G.Log(d),u}finally{h!==null&&Ft.loggingLevel!==Ft.NO_LOGGING&&G.Log(Fc("importMesh",c?c.producer:"Unknown")+(Ft.loggingLevel!==Ft.MINIMAL_LOGGING?h:"")),ih={}}return!1},load:(o,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&&(o.useDelayedTextureLoading=r.useDelayedTextureLoading&&!Ft.ForceFullSceneLoadingForIncremental),r.autoClear!==void 0&&r.autoClear!==null&&(o.autoClear=r.autoClear),r.clearColor!==void 0&&r.clearColor!==null&&(o.clearColor=Ze.FromArray(r.clearColor)),r.ambientColor!==void 0&&r.ambientColor!==null&&(o.ambientColor=Te.FromArray(r.ambientColor)),r.gravity!==void 0&&r.gravity!==null&&(o.gravity=T.FromArray(r.gravity)),r.useRightHandedSystem!==void 0&&(o.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&r.fogMode!==0)switch(o.fogMode=r.fogMode,o.fogColor=Te.FromArray(r.fogColor),o.fogStart=r.fogStart,o.fogEnd=r.fogEnd,o.fogDensity=r.fogDensity,s+=" Fog mode for scene: ",o.fogMode){case 1:s+=`exp + Mesh `+I.toString(u)}}e.multiMaterials.forEach(S=>{S._waitingSubMaterialsUniqueIds.forEach(b=>{S.subMaterials.push(U_(b,e))}),S._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(S=>{S._waitingMaterialId!==null&&(S.material=U_(S._waitingMaterialId,e),S._waitingMaterialId=null)});for(let S=0,b=e.transformNodes.length;S-1&&p.splice(N,1)}C._waitingParentId=null}C._waitingData.lods&&by(e,C)}for(const S of p)S.dispose();for(let S=0,b=e.skeletons.length;S{if(I._waitingTransformNodeId){const N=e.getLastEntryById(I._waitingTransformNodeId);N&&I.linkTransformNode(N),I._waitingTransformNodeId=null}}),R._hasWaitingData=null)}for(let S=0,b=e.meshes.length;S{_._loadedUniqueId=""}),!0}catch(u){const d=Fc("importMesh",c?c.producer:"Unknown")+h;if(a)a(d,u);else throw G.Log(d),u}finally{h!==null&&Lt.loggingLevel!==Lt.NO_LOGGING&&G.Log(Fc("importMesh",c?c.producer:"Unknown")+(Lt.loggingLevel!==Lt.MINIMAL_LOGGING?h:"")),sh={}}return!1},load:(o,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&&(o.useDelayedTextureLoading=r.useDelayedTextureLoading&&!Lt.ForceFullSceneLoadingForIncremental),r.autoClear!==void 0&&r.autoClear!==null&&(o.autoClear=r.autoClear),r.clearColor!==void 0&&r.clearColor!==null&&(o.clearColor=Ze.FromArray(r.clearColor)),r.ambientColor!==void 0&&r.ambientColor!==null&&(o.ambientColor=Te.FromArray(r.ambientColor)),r.gravity!==void 0&&r.gravity!==null&&(o.gravity=T.FromArray(r.gravity)),r.useRightHandedSystem!==void 0&&(o.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&r.fogMode!==0)switch(o.fogMode=r.fogMode,o.fogColor=Te.FromArray(r.fogColor),o.fogStart=r.fogStart,o.fogEnd=r.fogEnd,o.fogDensity=r.fogDensity,s+=" Fog mode for scene: ",o.fogMode){case 1:s+=`exp `;break;case 2:s+=`exp2 `;break;case 3:s+=`linear -`;break}if(r.physicsEnabled){let a;r.physicsEngine==="cannon"||r.physicsEngine===V_.name?a=new V_(void 0,void 0,S_.LoaderInjectedPhysicsEngine):r.physicsEngine==="oimo"||r.physicsEngine===aC.name?a=new aC(void 0,S_.LoaderInjectedPhysicsEngine):(r.physicsEngine==="ammo"||r.physicsEngine===$o.name)&&(a=new $o(void 0,S_.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+` enabled -`;const l=r.physicsGravity?T.FromArray(r.physicsGravity):null;o.enablePhysics(l,a)}return r.metadata!==void 0&&r.metadata!==null&&(o.metadata=r.metadata),r.collisionsEnabled!==void 0&&r.collisionsEnabled!==null&&(o.collisionsEnabled=r.collisionsEnabled),lC(o,e,t,i,!0)?(r.autoAnimate&&o.beginAnimation(o,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),r.activeCameraID!==void 0&&r.activeCameraID!==null&&o.setActiveCameraById(r.activeCameraID),!0):!1}catch(n){const a=Fc("importScene",r?r.producer:"Unknown")+s;if(i)i(a,n);else throw G.Log(a),n}finally{s!==null&&Ft.loggingLevel!==Ft.NO_LOGGING&&G.Log(Fc("importScene",r?r.producer:"Unknown")+(Ft.loggingLevel!==Ft.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(o,e,t,i)=>lC(o,e,t,i)});class k_{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,re.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||Te.White(),this.rightColor=e.rightColor||Te.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new k_;return Ur.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 k_({isEnabled:e.isEnabled,leftColor:Te.FromArray(e.leftColor),rightColor:Te.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Xe._FresnelParametersParser=k_.Parse;class Pn extends Ni{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 Te(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Pn.prototype,"maxSimultaneousLights",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Pn.prototype,"disableLighting",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Pn.prototype,"environmentTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"invertNormalMapX",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"invertNormalMapY",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Pn.prototype,"normalTexture",void 0);A([ds("emissive"),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"emissiveColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"emissiveTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Pn.prototype,"occlusionStrength",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Pn.prototype,"occlusionTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Pn.prototype,"alphaCutOff",void 0);A([D()],Pn.prototype,"doubleSided",null);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty",null)],Pn.prototype,"lightmapTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"useLightmapAsShadowmap",void 0);class Dl extends Pn{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=Xe.Clone(()=>new Dl(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=Xe.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=Xe.Parse(()=>new Dl(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}}A([ds(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Dl.prototype,"baseColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Dl.prototype,"baseTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Dl.prototype,"metallic",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Dl.prototype,"roughness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Dl.prototype,"metallicRoughnessTexture",void 0);j("BABYLON.PBRMetallicRoughnessMaterial",Dl);class Ol extends Pn{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Xe.Clone(()=>new Ol(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=Xe.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=Xe.Parse(()=>new Ol(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}}A([ds("diffuse"),Ce("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Ol.prototype,"diffuseColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Ol.prototype,"diffuseTexture",void 0);A([ds("specular"),Ce("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Ol.prototype,"specularColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_microSurface")],Ol.prototype,"glossiness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Ol.prototype,"specularGlossinessTexture",void 0);j("BABYLON.PBRSpecularGlossinessMaterial",Ol);class Xc extends Ei{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=k.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,a=null,l;const h=r.split(` -`);let c=0,u=0,d=0,f=0,p=0;for(let _=0;_0&&(_+1)%4===0)n[_]=255;else{const g=a[_];n[_]=g/p*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 Xc(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 Xc(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}}Xc._NoneEmptyLineRegex=/\S+/;j("BABYLON.ColorGradingTexture",Xc);class G_ extends Ei{constructor(e,t,i,s=!1,r=!0,n=null,a=null,l=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=ee.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=a,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?fe.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");Zf(this.url,n=>{this._width=n.width,this._height=n.height,r.width=this._width,r.height=this._height;const a=r.getContext("2d");a.drawImage(n,0,0);const l=a.getImageData(0,0,n.width,n.height);this._buffer=l.data.buffer,r.remove(),e()},(n,a)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,a)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const r=this._getFloat32ArrayFromArrayBuffer(this._buffer),n=Eh.ConvertPanoramaToCubemap(r,this._width,this._height,this._size,this._supersample),a=[];for(let l=0;l<6;l++){const h=n[G_._FacesMapping[l]];a.push(h)}return a};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;re.length){G.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 FG:s=!0;case OG:r=!0;break;case LG:s=!0;case NG:break;case BG:s=!0;case wG:n=!0;break}let a;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){a=new Uint8Array(h);let S,b,R,I=0;const N=new Uint8Array(l);for(;t>UG){default:case zG:u=0,f=1,g=i.width,d=0,p=1,_=i.height;break;case kG:u=0,f=1,g=i.width,d=i.height-1,p=-1,_=-1;break;case WG:u=i.width-1,f=-1,g=-1,d=0,p=1,_=i.height;break;case GG:u=i.width-1,f=-1,g=-1,d=i.height-1,p=-1,_=-1;break}const v="_getImageData"+(n?"Grey":"")+i.pixel_size+"bits",E=jG[v](i,c,a,d,p,_,u,f,g);o.getEngine()._uploadDataToTextureDirectly(o,E)}function HG(o,e,t,i,s,r,n,a,l){const h=t,c=e,u=o.width,d=o.height;let f,p=0,_,g;const v=new Uint8Array(u*d*4);for(g=i;g!==r;g+=s)for(_=n;_!==l;_+=a,p++)f=h[p],v[(_+u*g)*4+3]=255,v[(_+u*g)*4+2]=c[f*3+0],v[(_+u*g)*4+1]=c[f*3+1],v[(_+u*g)*4+0]=c[f*3+2];return v}function XG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d,f=0,p,_;const g=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(p=n;p!==l;p+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const v=((d&31744)>>10)*255/31|0,E=((d&992)>>5)*255/31|0,C=(d&31)*255/31|0;g[(p+c*_)*4+0]=v,g[(p+c*_)*4+1]=E,g[(p+c*_)*4+2]=C,g[(p+c*_)*4+3]=d&32768?0:255}return g}function YG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=3)_[(f+c*p)*4+3]=255,_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+1]=h[d+1],_[(f+c*p)*4+0]=h[d+2];return _}function $G(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=4)_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+1]=h[d+1],_[(f+c*p)*4+0]=h[d+2],_[(f+c*p)*4+3]=h[d+3];return _}function KG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d,f=0,p,_;const g=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(p=n;p!==l;p+=a,f++)d=h[f],g[(p+c*_)*4+0]=d,g[(p+c*_)*4+1]=d,g[(p+c*_)*4+2]=d,g[(p+c*_)*4+3]=255;return g}function qG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=2)_[(f+c*p)*4+0]=h[d+0],_[(f+c*p)*4+1]=h[d+0],_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+3]=h[d+1];return _}const jG={GetTGAHeader:Lm,UploadContent:Cy,_getImageData8bits:HG,_getImageData16bits:XG,_getImageData24bits:YG,_getImageData32bits:$G,_getImageDataGrey8bits:KG,_getImageDataGrey16bits:qG};class QG{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=Lm(s);i(r.width,r.height,t.generateMipMaps,!1,()=>{Cy(t,s)})}}re._TextureLoaders.push(new QG);class ZG{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=Hv.RGBE_ReadHeader(s),n=Hv.RGBE_ReadPixels(s,r),a=r.width*r.height,l=new Float32Array(a*4);for(let h=0;h{const h=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,h._uploadDataToTextureDirectly(t,l)})}}re._TextureLoaders.push(new ZG);var El;(function(o){o[o.cTFETC1=0]="cTFETC1",o[o.cTFETC2=1]="cTFETC2",o[o.cTFBC1=2]="cTFBC1",o[o.cTFBC3=3]="cTFBC3",o[o.cTFBC4=4]="cTFBC4",o[o.cTFBC5=5]="cTFBC5",o[o.cTFBC7=6]="cTFBC7",o[o.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",o[o.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",o[o.cTFASTC_4x4=10]="cTFASTC_4x4",o[o.cTFATC_RGB=11]="cTFATC_RGB",o[o.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",o[o.cTFRGBA32=13]="cTFRGBA32",o[o.cTFRGB565=14]="cTFRGB565",o[o.cTFBGR565=15]="cTFBGR565",o[o.cTFRGBA4444=16]="cTFRGBA4444",o[o.cTFFXT1_RGB=17]="cTFFXT1_RGB",o[o.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",o[o.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",o[o.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",o[o.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(El||(El={}));const gh={JSModuleURL:`${fe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${fe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},JG=(o,e)=>{let t;switch(o){case El.cTFETC1:t=36196;break;case El.cTFBC1:t=33776;break;case El.cTFBC4:t=33779;break;case El.cTFASTC_4x4:t=37808;break;case El.cTFETC2:t=37496;break;case El.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let Cv=null,Bo=null,ez=0;const tz=!1,iz=()=>(Cv||(Cv=new Promise((o,e)=>{Bo?o(Bo):fe.LoadFileAsync(fe.GetBabylonScriptURL(gh.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${sz})()`],{type:"application/javascript"}));Bo=new Worker(i);const s=r=>{r.data.action==="init"?(Bo.removeEventListener("message",s),o(Bo)):r.data.action==="error"&&e(r.data.error||"error initializing worker")};Bo.addEventListener("message",s),Bo.postMessage({action:"init",url:fe.GetBabylonScriptURL(gh.JSModuleURL),wasmBinary:t})}).catch(e)})),Cv),Xv=(o,e)=>{const t=o instanceof ArrayBuffer?new Uint8Array(o):o;return new Promise((i,s)=>{iz().then(()=>{const r=ez++,n=l=>{l.data.action==="transcode"&&l.data.id===r&&(Bo.removeEventListener("message",n),l.data.success?i(l.data):s("Transcode is not supported on this device"))};Bo.addEventListener("message",n);const a=new Uint8Array(t.byteLength);a.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),Bo.postMessage({action:"transcode",id:r,imageData:a,config:e,ignoreSupportedFormats:tz},[a.buffer])},r=>{s(r)})})},f_=(o,e)=>{var t,i;let s=(t=e._gl)===null||t===void 0?void 0:t.TEXTURE_2D;o.isCube&&(s=(i=e._gl)===null||i===void 0?void 0:i.TEXTURE_CUBE_MAP),e._bindTextureDirectly(s,o,!0)},Yv=(o,e)=>{const t=o.getEngine();for(let i=0;i{t._releaseTexture(r),f_(o,t)})}else o._invertVScale=!o.invertY,o.width=s.width+3&-4,o.height=s.height+3&-4,o.samplingMode=2,f_(o,t),t._uploadDataToTextureDirectly(o,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0);else{o.width=s.width,o.height=s.height,o.generateMipMaps=e.fileInfo.images[i].levels.length>1;const r=sT.GetInternalFormatFromBasisFormat(e.format,t);o.format=r,f_(o,t),e.fileInfo.images[i].levels.forEach((n,a)=>{t._uploadCompressedDataToTextureDirectly(o,r,n.width,n.height,n.transcodedPixels,i,a)}),t._features.basisNeedsPOT&&(ye.Log2(o.width)%1!==0||ye.Log2(o.height)%1!==0)&&(fe.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."),o._cachedWrapU=ee.CLAMP_ADDRESSMODE,o._cachedWrapV=ee.CLAMP_ADDRESSMODE)}}},sT={JSModuleURL:gh.JSModuleURL,WasmModuleURL:gh.WasmModuleURL,GetInternalFormatFromBasisFormat:JG,TranscodeAsync:Xv,LoadTextureFromTranscodeResult:Yv};function sz(){const o={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(!e){try{importScripts(n.data.url)}catch(a){postMessage({action:"error",error:a})}e=BASIS({wasmBinary:n.data.wasmBinary})}e!==null&&e.then(a=>{BASIS=a,a.initializeBasis(),postMessage({action:"init"})})}else if(n.data.action==="transcode"){const a=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?o.cTFBC3:o.cTFBC1);let f=!0;h.startTranscoding()||(f=!1);const p=[];for(let _=0;_>2&3],u[C++]=c[E>>4&3],u[C++]=c[E>>6&3]}}return u}}Object.defineProperty(sT,"JSModuleURL",{get:function(){return gh.JSModuleURL},set:function(o){gh.JSModuleURL=o}});Object.defineProperty(sT,"WasmModuleURL",{get:function(){return gh.WasmModuleURL},set:function(o){gh.WasmModuleURL=o}});class rz{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(),a={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Xv(e,a).then(l=>{const h=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Yv(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";fe.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}};Xv(e,r).then(n=>{const a=n.fileInfo.images[0].levels[0],l=n.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(a.width,a.height,l,n.format!==-1,()=>{Yv(t,n)})}).catch(n=>{fe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),fe.Warn(`Failed to transcode Basis file: ${n}`),i(0,0,!1,!1,()=>{},!0)})}}re._TextureLoaders.push(new rz);class Bh extends ms{get isSupported(){var e,t;return(t=(e=this._engine)===null||e===void 0?void 0:e.getCaps().drawBuffersExtension)!==null&&t!==void 0?t:!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;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,a,l,h,c){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;const i=(e=this._renderTarget)===null||e===void 0?void 0:e.textures;if(i){for(let s=i.length-1;s>=0;s--)this._textures[s]._texture=null;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null}}}const nz="noisePixelShader",az=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) +`;break}if(r.physicsEnabled){let a;r.physicsEngine==="cannon"||r.physicsEngine===V_.name?a=new V_(void 0,void 0,S_.LoaderInjectedPhysicsEngine):r.physicsEngine==="oimo"||r.physicsEngine===lC.name?a=new lC(void 0,S_.LoaderInjectedPhysicsEngine):(r.physicsEngine==="ammo"||r.physicsEngine===$o.name)&&(a=new $o(void 0,S_.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+` enabled +`;const l=r.physicsGravity?T.FromArray(r.physicsGravity):null;o.enablePhysics(l,a)}return r.metadata!==void 0&&r.metadata!==null&&(o.metadata=r.metadata),r.collisionsEnabled!==void 0&&r.collisionsEnabled!==null&&(o.collisionsEnabled=r.collisionsEnabled),cC(o,e,t,i,!0)?(r.autoAnimate&&o.beginAnimation(o,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),r.activeCameraID!==void 0&&r.activeCameraID!==null&&o.setActiveCameraById(r.activeCameraID),!0):!1}catch(n){const a=Fc("importScene",r?r.producer:"Unknown")+s;if(i)i(a,n);else throw G.Log(a),n}finally{s!==null&&Lt.loggingLevel!==Lt.NO_LOGGING&&G.Log(Fc("importScene",r?r.producer:"Unknown")+(Lt.loggingLevel!==Lt.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(o,e,t,i)=>cC(o,e,t,i)});class k_{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,re.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||Te.White(),this.rightColor=e.rightColor||Te.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new k_;return Ur.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 k_({isEnabled:e.isEnabled,leftColor:Te.FromArray(e.leftColor),rightColor:Te.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Xe._FresnelParametersParser=k_.Parse;class Pn extends Ni{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 Te(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Pn.prototype,"maxSimultaneousLights",void 0);A([D(),Ce("_markAllSubMeshesAsLightsDirty")],Pn.prototype,"disableLighting",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Pn.prototype,"environmentTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"invertNormalMapX",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"invertNormalMapY",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Pn.prototype,"normalTexture",void 0);A([ds("emissive"),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"emissiveColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"emissiveTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Pn.prototype,"occlusionStrength",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Pn.prototype,"occlusionTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Pn.prototype,"alphaCutOff",void 0);A([D()],Pn.prototype,"doubleSided",null);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty",null)],Pn.prototype,"lightmapTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Pn.prototype,"useLightmapAsShadowmap",void 0);class Dl extends Pn{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=Xe.Clone(()=>new Dl(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=Xe.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=Xe.Parse(()=>new Dl(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}}A([ds(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Dl.prototype,"baseColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Dl.prototype,"baseTexture",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Dl.prototype,"metallic",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],Dl.prototype,"roughness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Dl.prototype,"metallicRoughnessTexture",void 0);j("BABYLON.PBRMetallicRoughnessMaterial",Dl);class Ol extends Pn{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Xe.Clone(()=>new Ol(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=Xe.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=Xe.Parse(()=>new Ol(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}}A([ds("diffuse"),Ce("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Ol.prototype,"diffuseColor",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Ol.prototype,"diffuseTexture",void 0);A([ds("specular"),Ce("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Ol.prototype,"specularColor",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty","_microSurface")],Ol.prototype,"glossiness",void 0);A([Jt(),Ce("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Ol.prototype,"specularGlossinessTexture",void 0);j("BABYLON.PBRSpecularGlossinessMaterial",Ol);class Xc extends Ei{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=k.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,a=null,l;const h=r.split(` +`);let c=0,u=0,d=0,f=0,p=0;for(let _=0;_0&&(_+1)%4===0)n[_]=255;else{const g=a[_];n[_]=g/p*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 Xc(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 Xc(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}}Xc._NoneEmptyLineRegex=/\S+/;j("BABYLON.ColorGradingTexture",Xc);class G_ extends Ei{constructor(e,t,i,s=!1,r=!0,n=null,a=null,l=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=ee.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=a,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?fe.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");Zf(this.url,n=>{this._width=n.width,this._height=n.height,r.width=this._width,r.height=this._height;const a=r.getContext("2d");a.drawImage(n,0,0);const l=a.getImageData(0,0,n.width,n.height);this._buffer=l.data.buffer,r.remove(),e()},(n,a)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,a)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const r=this._getFloat32ArrayFromArrayBuffer(this._buffer),n=Sh.ConvertPanoramaToCubemap(r,this._width,this._height,this._size,this._supersample),a=[];for(let l=0;l<6;l++){const h=n[G_._FacesMapping[l]];a.push(h)}return a};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;re.length){G.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 VG:s=!0;case FG:r=!0;break;case UG:s=!0;case LG:break;case kG:s=!0;case BG:n=!0;break}let a;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){a=new Uint8Array(h);let S,b,R,I=0;const N=new Uint8Array(l);for(;t>zG){default:case XG:u=0,f=1,g=i.width,d=0,p=1,_=i.height;break;case WG:u=0,f=1,g=i.width,d=i.height-1,p=-1,_=-1;break;case YG:u=i.width-1,f=-1,g=-1,d=0,p=1,_=i.height;break;case HG:u=i.width-1,f=-1,g=-1,d=i.height-1,p=-1,_=-1;break}const v="_getImageData"+(n?"Grey":"")+i.pixel_size+"bits",E=JG[v](i,c,a,d,p,_,u,f,g);o.getEngine()._uploadDataToTextureDirectly(o,E)}function $G(o,e,t,i,s,r,n,a,l){const h=t,c=e,u=o.width,d=o.height;let f,p=0,_,g;const v=new Uint8Array(u*d*4);for(g=i;g!==r;g+=s)for(_=n;_!==l;_+=a,p++)f=h[p],v[(_+u*g)*4+3]=255,v[(_+u*g)*4+2]=c[f*3+0],v[(_+u*g)*4+1]=c[f*3+1],v[(_+u*g)*4+0]=c[f*3+2];return v}function KG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d,f=0,p,_;const g=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(p=n;p!==l;p+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const v=((d&31744)>>10)*255/31|0,E=((d&992)>>5)*255/31|0,C=(d&31)*255/31|0;g[(p+c*_)*4+0]=v,g[(p+c*_)*4+1]=E,g[(p+c*_)*4+2]=C,g[(p+c*_)*4+3]=d&32768?0:255}return g}function qG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=3)_[(f+c*p)*4+3]=255,_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+1]=h[d+1],_[(f+c*p)*4+0]=h[d+2];return _}function jG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=4)_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+1]=h[d+1],_[(f+c*p)*4+0]=h[d+2],_[(f+c*p)*4+3]=h[d+3];return _}function QG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d,f=0,p,_;const g=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(p=n;p!==l;p+=a,f++)d=h[f],g[(p+c*_)*4+0]=d,g[(p+c*_)*4+1]=d,g[(p+c*_)*4+2]=d,g[(p+c*_)*4+3]=255;return g}function ZG(o,e,t,i,s,r,n,a,l){const h=t,c=o.width,u=o.height;let d=0,f,p;const _=new Uint8Array(c*u*4);for(p=i;p!==r;p+=s)for(f=n;f!==l;f+=a,d+=2)_[(f+c*p)*4+0]=h[d+0],_[(f+c*p)*4+1]=h[d+0],_[(f+c*p)*4+2]=h[d+0],_[(f+c*p)*4+3]=h[d+1];return _}const JG={GetTGAHeader:Lm,UploadContent:yy,_getImageData8bits:$G,_getImageData16bits:KG,_getImageData24bits:qG,_getImageData32bits:jG,_getImageDataGrey8bits:QG,_getImageDataGrey16bits:ZG};class ez{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=Lm(s);i(r.width,r.height,t.generateMipMaps,!1,()=>{yy(t,s)})}}re._TextureLoaders.push(new ez);class tz{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=Hv.RGBE_ReadHeader(s),n=Hv.RGBE_ReadPixels(s,r),a=r.width*r.height,l=new Float32Array(a*4);for(let h=0;h{const h=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,h._uploadDataToTextureDirectly(t,l)})}}re._TextureLoaders.push(new tz);var El;(function(o){o[o.cTFETC1=0]="cTFETC1",o[o.cTFETC2=1]="cTFETC2",o[o.cTFBC1=2]="cTFBC1",o[o.cTFBC3=3]="cTFBC3",o[o.cTFBC4=4]="cTFBC4",o[o.cTFBC5=5]="cTFBC5",o[o.cTFBC7=6]="cTFBC7",o[o.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",o[o.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",o[o.cTFASTC_4x4=10]="cTFASTC_4x4",o[o.cTFATC_RGB=11]="cTFATC_RGB",o[o.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",o[o.cTFRGBA32=13]="cTFRGBA32",o[o.cTFRGB565=14]="cTFRGB565",o[o.cTFBGR565=15]="cTFBGR565",o[o.cTFRGBA4444=16]="cTFRGBA4444",o[o.cTFFXT1_RGB=17]="cTFFXT1_RGB",o[o.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",o[o.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",o[o.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",o[o.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(El||(El={}));const vh={JSModuleURL:`${fe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${fe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},iz=(o,e)=>{let t;switch(o){case El.cTFETC1:t=36196;break;case El.cTFBC1:t=33776;break;case El.cTFBC4:t=33779;break;case El.cTFASTC_4x4:t=37808;break;case El.cTFETC2:t=37496;break;case El.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let Cv=null,Bo=null,sz=0;const rz=!1,nz=()=>(Cv||(Cv=new Promise((o,e)=>{Bo?o(Bo):fe.LoadFileAsync(fe.GetBabylonScriptURL(vh.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${az})()`],{type:"application/javascript"}));Bo=new Worker(i);const s=r=>{r.data.action==="init"?(Bo.removeEventListener("message",s),o(Bo)):r.data.action==="error"&&e(r.data.error||"error initializing worker")};Bo.addEventListener("message",s),Bo.postMessage({action:"init",url:fe.GetBabylonScriptURL(vh.JSModuleURL),wasmBinary:t})}).catch(e)})),Cv),Xv=(o,e)=>{const t=o instanceof ArrayBuffer?new Uint8Array(o):o;return new Promise((i,s)=>{nz().then(()=>{const r=sz++,n=l=>{l.data.action==="transcode"&&l.data.id===r&&(Bo.removeEventListener("message",n),l.data.success?i(l.data):s("Transcode is not supported on this device"))};Bo.addEventListener("message",n);const a=new Uint8Array(t.byteLength);a.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),Bo.postMessage({action:"transcode",id:r,imageData:a,config:e,ignoreSupportedFormats:rz},[a.buffer])},r=>{s(r)})})},f_=(o,e)=>{var t,i;let s=(t=e._gl)===null||t===void 0?void 0:t.TEXTURE_2D;o.isCube&&(s=(i=e._gl)===null||i===void 0?void 0:i.TEXTURE_CUBE_MAP),e._bindTextureDirectly(s,o,!0)},Yv=(o,e)=>{const t=o.getEngine();for(let i=0;i{t._releaseTexture(r),f_(o,t)})}else o._invertVScale=!o.invertY,o.width=s.width+3&-4,o.height=s.height+3&-4,o.samplingMode=2,f_(o,t),t._uploadDataToTextureDirectly(o,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0);else{o.width=s.width,o.height=s.height,o.generateMipMaps=e.fileInfo.images[i].levels.length>1;const r=nT.GetInternalFormatFromBasisFormat(e.format,t);o.format=r,f_(o,t),e.fileInfo.images[i].levels.forEach((n,a)=>{t._uploadCompressedDataToTextureDirectly(o,r,n.width,n.height,n.transcodedPixels,i,a)}),t._features.basisNeedsPOT&&(ye.Log2(o.width)%1!==0||ye.Log2(o.height)%1!==0)&&(fe.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."),o._cachedWrapU=ee.CLAMP_ADDRESSMODE,o._cachedWrapV=ee.CLAMP_ADDRESSMODE)}}},nT={JSModuleURL:vh.JSModuleURL,WasmModuleURL:vh.WasmModuleURL,GetInternalFormatFromBasisFormat:iz,TranscodeAsync:Xv,LoadTextureFromTranscodeResult:Yv};function az(){const o={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(!e){try{importScripts(n.data.url)}catch(a){postMessage({action:"error",error:a})}e=BASIS({wasmBinary:n.data.wasmBinary})}e!==null&&e.then(a=>{BASIS=a,a.initializeBasis(),postMessage({action:"init"})})}else if(n.data.action==="transcode"){const a=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?o.cTFBC3:o.cTFBC1);let f=!0;h.startTranscoding()||(f=!1);const p=[];for(let _=0;_>2&3],u[C++]=c[E>>4&3],u[C++]=c[E>>6&3]}}return u}}Object.defineProperty(nT,"JSModuleURL",{get:function(){return vh.JSModuleURL},set:function(o){vh.JSModuleURL=o}});Object.defineProperty(nT,"WasmModuleURL",{get:function(){return vh.WasmModuleURL},set:function(o){vh.WasmModuleURL=o}});class oz{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(),a={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Xv(e,a).then(l=>{const h=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Yv(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";fe.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}};Xv(e,r).then(n=>{const a=n.fileInfo.images[0].levels[0],l=n.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(a.width,a.height,l,n.format!==-1,()=>{Yv(t,n)})}).catch(n=>{fe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),fe.Warn(`Failed to transcode Basis file: ${n}`),i(0,0,!1,!1,()=>{},!0)})}}re._TextureLoaders.push(new oz);class Vh extends ms{get isSupported(){var e,t;return(t=(e=this._engine)===null||e===void 0?void 0:e.getCaps().drawBuffersExtension)!==null&&t!==void 0?t:!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;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,a,l,h,c){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;const i=(e=this._renderTarget)===null||e===void 0?void 0:e.textures;if(i){for(let s=i.length-1;s>=0;s--)this._textures[s]._texture=null;(t=this._renderTarget)===null||t===void 0||t.dispose(),this._renderTarget=null}}}const lz="noisePixelShader",hz=`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); @@ -7596,12 +7596,12 @@ 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);} -`;ne.ShadersStore[nz]=az;class z_ extends Jo{constructor(e,t=256,i=ht.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 z_(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){var i;const s=new z_(e.name,e.size,t,void 0,e.generateMipMaps);return s.brightness=e.brightness,s.octaves=e.octaves,s.persistence=e.persistence,s.animationSpeedFactor=e.animationSpeedFactor,s.time=(i=e.time)!==null&&i!==void 0?i:0,s}}j("BABYLON.NoiseProceduralTexture",z_);class Ss extends Zc{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Ss&&e._blockName===this._blockName?Ca.Compatible:Ca.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class oz extends nt{constructor(e){super(e,W.Vertex),this.registerInput("matricesIndices",M.Vector4),this.registerInput("matricesWeights",M.Vector4),this.registerInput("matricesIndicesExtra",M.Vector4,!0),this.registerInput("matricesWeightsExtra",M.Vector4,!0),this.registerInput("world",M.Matrix),this.registerOutput("output",M.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 Bt("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 Bt("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.World&&t(s));i||(i=new Bt("world"),i.setAsSystemValue(Gt.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Me.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Me.PrepareDefinesForBones(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 +`;ne.ShadersStore[lz]=hz;class z_ extends Jo{constructor(e,t=256,i=ht.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 z_(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){var i;const s=new z_(e.name,e.size,t,void 0,e.generateMipMaps);return s.brightness=e.brightness,s.octaves=e.octaves,s.persistence=e.persistence,s.animationSpeedFactor=e.animationSpeedFactor,s.time=(i=e.time)!==null&&i!==void 0?i:0,s}}j("BABYLON.NoiseProceduralTexture",z_);class Cs extends Zc{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Cs&&e._blockName===this._blockName?Ca.Compatible:Ca.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class cz extends nt{constructor(e){super(e,W.Vertex),this.registerInput("matricesIndices",M.Vector4),this.registerInput("matricesWeights",M.Vector4),this.registerInput("matricesIndicesExtra",M.Vector4,!0),this.registerInput("matricesWeightsExtra",M.Vector4,!0),this.registerInput("world",M.Matrix),this.registerOutput("output",M.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 Vt("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 Vt("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.World&&t(s));i||(i=new Vt("world"),i.setAsSystemValue(Gt.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Me.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Me.PrepareDefinesForBones(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}}j("BABYLON.BonesBlock",oz);class lz extends nt{constructor(e){super(e,W.Vertex),this.registerInput("world0",M.Vector4),this.registerInput("world1",M.Vector4),this.registerInput("world2",M.Vector4),this.registerInput("world3",M.Vector4),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Matrix),this.registerOutput("instanceID",M.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 Bt("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 Bt("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 Bt("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 Bt("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 Bt("world"),i.setAsSystemValue(Gt.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,a=this.world2,l=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,this}}j("BABYLON.BonesBlock",cz);class uz extends nt{constructor(e){super(e,W.Vertex),this.registerInput("world0",M.Vector4),this.registerInput("world1",M.Vector4),this.registerInput("world2",M.Vector4),this.registerInput("world3",M.Vector4),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Matrix),this.registerOutput("instanceID",M.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 Vt("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 Vt("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 Vt("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 Vt("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 Vt("world"),i.setAsSystemValue(Gt.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,a=this.world2,l=this.world3;return e.compilationString+=`#ifdef INSTANCES `,e.compilationString+=this._declareOutput(i,e)+` = mat4(${r.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${l.associatedVariableName}); `,e.compilationString+=`#ifdef THIN_INSTANCES `,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; @@ -7612,7 +7612,7 @@ void main(void) `,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; `,e.compilationString+=this._declareOutput(s,e)+` = 0.0; `,e.compilationString+=`#endif -`,this}}j("BABYLON.InstancesBlock",lz);class by extends nt{constructor(e){super(e,W.Vertex),this.registerInput("position",M.Vector3),this.registerInput("normal",M.Vector3),this.registerInput("tangent",M.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(M.Color4|M.Vector4|M.Vector3),this.registerInput("uv",M.Vector2),this.registerOutput("positionOutput",M.Vector3),this.registerOutput("normalOutput",M.Vector3),this.registerOutput("tangentOutput",M.Vector4),this.registerOutput("uvOutput",M.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 Bt("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 Bt("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 Bt("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 Bt("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.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&Me.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Me.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,a=this.tangent,l=this.uv,h=this.positionOutput,c=this.normalOutput,u=this.tangentOutput,d=this.uvOutput,f=e,p=s.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,g=_&&_.supportsNormals&&s.NORMAL,v=_&&_.supportsTangents&&s.TANGENT,E=_&&_.supportsUVs&&s.UV1;let C="";_!=null&&_.isUsingTextureForTargets&&p>0&&(C+=`float vertexID; +`,this}}j("BABYLON.InstancesBlock",uz);class Ay extends nt{constructor(e){super(e,W.Vertex),this.registerInput("position",M.Vector3),this.registerInput("normal",M.Vector3),this.registerInput("tangent",M.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(M.Color4|M.Vector4|M.Vector3),this.registerInput("uv",M.Vector2),this.registerOutput("positionOutput",M.Vector3),this.registerOutput("normalOutput",M.Vector3),this.registerOutput("tangentOutput",M.Vector4),this.registerOutput("uvOutput",M.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 Vt("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 Vt("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 Vt("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 Vt("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.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&Me.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Me.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,a=this.tangent,l=this.uv,h=this.positionOutput,c=this.normalOutput,u=this.tangentOutput,d=this.uvOutput,f=e,p=s.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,g=_&&_.supportsNormals&&s.NORMAL,v=_&&_.supportsTangents&&s.TANGENT,E=_&&_.supportsUVs&&s.UV1;let C="";_!=null&&_.isUsingTextureForTargets&&p>0&&(C+=`float vertexID; `);for(let S=0;S!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.isSystemValue&&s.systemValue===Gt.World&&t(s));i||(i=new Bt("world"),i.setAsSystemValue(Gt.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 Bt("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===M.Vector4&&t(s));i||(i=new Bt("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var s,r,n,a;const l=this.normal,h=this.tangent;let c=l.isConnected;!((s=l.connectInputBlock)===null||s===void 0)&&s.isAttribute&&!e.isVerticesDataPresent((r=l.connectInputBlock)===null||r===void 0?void 0:r.name)&&(c=!1);let u=h.isConnected;!((n=h.connectInputBlock)===null||n===void 0)&&n.isAttribute&&!e.isVerticesDataPresent((a=h.connectInputBlock)===null||a===void 0?void 0:a.name)&&(u=!1);const d=c&&u;i.setValue("TBNBLOCK",d,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,a=this.row1,l=this.row2;return e.target===W.Fragment&&(e.compilationString+=` +`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var s;super._deserialize(e,t,i),this.convertInputToLinearSpace=(s=e.convertInputToLinearSpace)!==null&&s!==void 0?s:!0}}A([ft("Convert input to linear space",ut.Boolean,"ADVANCED")],Ry.prototype,"convertInputToLinearSpace",void 0);j("BABYLON.ImageProcessingBlock",Ry);class Eu extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("normal",M.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(M.Color4|M.Vector4|M.Vector3),this.registerInput("tangent",M.Vector4,!1),this.registerInput("world",M.Matrix,!1),this.registerOutput("TBN",M.Object,W.Fragment,new Cs("TBN",this,as.Output,Eu,"TBNBlock")),this.registerOutput("row0",M.Vector3,W.Fragment),this.registerOutput("row1",M.Vector3,W.Fragment),this.registerOutput("row2",M.Vector3,W.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 W.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.isSystemValue&&s.systemValue===Gt.World&&t(s));i||(i=new Vt("world"),i.setAsSystemValue(Gt.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 Vt("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===M.Vector4&&t(s));i||(i=new Vt("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var s,r,n,a;const l=this.normal,h=this.tangent;let c=l.isConnected;!((s=l.connectInputBlock)===null||s===void 0)&&s.isAttribute&&!e.isVerticesDataPresent((r=l.connectInputBlock)===null||r===void 0?void 0:r.name)&&(c=!1);let u=h.isConnected;!((n=h.connectInputBlock)===null||n===void 0)&&n.isAttribute&&!e.isVerticesDataPresent((a=h.connectInputBlock)===null||a===void 0?void 0:a.name)&&(u=!1);const d=c&&u;i.setValue("TBNBLOCK",d,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,a=this.row1,l=this.row2;return e.target===W.Fragment&&(e.compilationString+=` // ${this.name} vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); @@ -7683,7 +7683,7 @@ void main(void) `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]); `),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,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}}j("BABYLON.TBNBlock",Eu);class lp extends nt{constructor(e){super(e,W.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",M.Vector4,!1),this.registerInput("worldNormal",M.Vector4,!1),this.registerInput("worldTangent",M.Vector4,!0),this.registerInput("uv",M.Vector2,!1),this.registerInput("normalMapColor",M.Color3,!1),this.registerInput("strength",M.Float,!1),this.registerInput("viewDirection",M.Vector3,!0),this.registerInput("parallaxScale",M.Float,!0),this.registerInput("parallaxHeight",M.Float,!0),this.registerInput("TBN",M.Object,!0,W.VertexAndFragment,new Ss("TBN",this,as.Input,Eu,"TBNBlock")),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Vector4),this.registerOutput("uvOffset",M.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 Bt("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new Bt("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 a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!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?` +`),e.sharedData.blocksWithDefines.push(this)),this}}j("BABYLON.TBNBlock",Eu);class lp extends nt{constructor(e){super(e,W.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",M.Vector4,!1),this.registerInput("worldNormal",M.Vector4,!1),this.registerInput("worldTangent",M.Vector4,!0),this.registerInput("uv",M.Vector2,!1),this.registerInput("normalMapColor",M.Color3,!1),this.registerInput("strength",M.Float,!1),this.registerInput("viewDirection",M.Vector3,!0),this.registerInput("parallaxScale",M.Float,!0),this.registerInput("parallaxHeight",M.Float,!0),this.registerInput("TBN",M.Object,!0,W.VertexAndFragment,new Cs("TBN",this,as.Input,Eu,"TBNBlock")),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Vector4),this.registerOutput("uvOffset",M.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 Vt("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new Vt("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 a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!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 @@ -7705,18 +7705,18 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p `;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}}A([ft("Invert X axis",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"invertX",void 0);A([ft("Invert Y axis",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"invertY",void 0);A([ft("Use parallax occlusion",ut.Boolean)],lp.prototype,"useParallaxOcclusion",void 0);A([ft("Object Space Mode",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"useObjectSpaceNormalMap",void 0);j("BABYLON.PerturbNormalBlock",lp);class cz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("value",M.Float,!0),this.registerInput("cutoff",M.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}}j("BABYLON.DiscardBlock",cz);class uz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("output",M.Float,W.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===W.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}}j("BABYLON.FrontFacingBlock",uz);class dz extends nt{constructor(e){super(e,W.Fragment),this.registerInput("input",M.AutoDetect,!1),this.registerOutput("dx",M.BasedOnInput),this.registerOutput("dy",M.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}); +`,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}}A([ft("Invert X axis",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"invertX",void 0);A([ft("Invert Y axis",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"invertY",void 0);A([ft("Use parallax occlusion",ut.Boolean)],lp.prototype,"useParallaxOcclusion",void 0);A([ft("Object Space Mode",ut.Boolean,"PROPERTIES",{notifiers:{update:!1}})],lp.prototype,"useObjectSpaceNormalMap",void 0);j("BABYLON.PerturbNormalBlock",lp);class fz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("value",M.Float,!0),this.registerInput("cutoff",M.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}}j("BABYLON.DiscardBlock",fz);class pz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("output",M.Float,W.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===W.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}}j("BABYLON.FrontFacingBlock",pz);class _z extends nt{constructor(e){super(e,W.Fragment),this.registerInput("input",M.AutoDetect,!1),this.registerOutput("dx",M.BasedOnInput),this.registerOutput("dy",M.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}}j("BABYLON.DerivativeBlock",dz);class fz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("xy",M.Vector2,W.Fragment),this.registerOutput("xyz",M.Vector3,W.Fragment),this.registerOutput("xyzw",M.Vector4,W.Fragment),this.registerOutput("x",M.Float,W.Fragment),this.registerOutput("y",M.Float,W.Fragment),this.registerOutput("z",M.Float,W.Fragment),this.registerOutput("w",M.Float,W.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===W.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}j("BABYLON.FragCoordBlock",fz);class pz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("xy",M.Vector2,W.Fragment),this.registerOutput("x",M.Float,W.Fragment),this.registerOutput("y",M.Float,W.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===W.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}}j("BABYLON.ScreenSizeBlock",pz);class _z extends nt{constructor(e){super(e,W.Fragment),this.registerInput("vector",M.AutoDetect),this.registerInput("worldViewProjection",M.Matrix),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.WorldViewProjection&&t(s));i||(i=new Bt("worldViewProjection"),i.setAsSystemValue(Gt.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 M.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0); +`),this}}j("BABYLON.DerivativeBlock",_z);class mz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("xy",M.Vector2,W.Fragment),this.registerOutput("xyz",M.Vector3,W.Fragment),this.registerOutput("xyzw",M.Vector4,W.Fragment),this.registerOutput("x",M.Float,W.Fragment),this.registerOutput("y",M.Float,W.Fragment),this.registerOutput("z",M.Float,W.Fragment),this.registerOutput("w",M.Float,W.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===W.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}j("BABYLON.FragCoordBlock",mz);class gz extends nt{constructor(e){super(e,W.Fragment),this.registerOutput("xy",M.Vector2,W.Fragment),this.registerOutput("x",M.Float,W.Fragment),this.registerOutput("y",M.Float,W.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===W.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}}j("BABYLON.ScreenSizeBlock",gz);class vz extends nt{constructor(e){super(e,W.Fragment),this.registerInput("vector",M.AutoDetect),this.registerInput("worldViewProjection",M.Matrix),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.WorldViewProjection&&t(s));i||(i=new Vt("worldViewProjection"),i.setAsSystemValue(Gt.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 M.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0); `;break;case M.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}}j("BABYLON.ScreenSpaceBlock",_z);class mz extends nt{constructor(e){super(e,W.Fragment),this.registerInput("input",M.Vector2),this.registerInput("strength",M.Float),this.registerInput("center",M.Vector2),this.registerInput("offset",M.Vector2),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.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 Bt("center");e.value=new Re(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Bt("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Bt("offset");e.value=new Re(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+=` +`),this}}j("BABYLON.ScreenSpaceBlock",vz);class xz extends nt{constructor(e){super(e,W.Fragment),this.registerInput("input",M.Vector2),this.registerInput("strength",M.Float),this.registerInput("center",M.Vector2),this.registerInput("offset",M.Vector2),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.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 Vt("center");e.value=new Re(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Vt("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Vt("offset");e.value=new Re(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; @@ -7725,7 +7725,7 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p `,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}}j("BABYLON.TwirlBlock",mz);class Bm extends nt{constructor(e){super(e,W.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",M.Float),this.registerInput("worldPosition",M.Vector3),this.registerInput("worldNormal",M.Vector3),this.registerInput("worldTangent",M.AutoDetect,!0),this.registerOutput("output",M.Vector4),this.registerOutput("xyz",M.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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&&G.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":` +`),this}}j("BABYLON.TwirlBlock",xz);class Bm extends nt{constructor(e){super(e,W.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",M.Float),this.registerInput("worldPosition",M.Vector3),this.registerInput("worldNormal",M.Vector3),this.registerInput("worldTangent",M.AutoDetect,!0),this.registerOutput("output",M.Vector4),this.registerOutput("xyz",M.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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&&G.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?"":` @@ -7751,7 +7751,7 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p `),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}}A([ft("Generate in world space instead of tangent space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"generateInWorldSpace",void 0);A([ft("Force normalization for the worldNormal input",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"automaticNormalizationNormal",void 0);A([ft("Force normalization for the worldTangent input",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"automaticNormalizationTangent",void 0);j("BABYLON.HeightToNormalBlock",Bm);class gz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("depth",M.Float,!0),this.registerInput("worldPos",M.Vector4,!0),this.registerInput("viewProjection",M.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}; +`,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}}A([ft("Generate in world space instead of tangent space",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"generateInWorldSpace",void 0);A([ft("Force normalization for the worldNormal input",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"automaticNormalizationNormal",void 0);A([ft("Force normalization for the worldTangent input",ut.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bm.prototype,"automaticNormalizationTangent",void 0);j("BABYLON.HeightToNormalBlock",Bm);class Tz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("depth",M.Float,!0),this.registerInput("worldPos",M.Vector4,!0),this.registerInput("viewProjection",M.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; @@ -7760,7 +7760,7 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p #endif gl_FragDepth = v; - `:G.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}j("BABYLON.FragDepthBlock",gz);class vz extends nt{constructor(e){super(e,W.Fragment),this.registerInput("worldPosition",M.Vector4,!1),this.registerInput("viewProjection",M.Matrix,!1),this.registerInput("worldNormal",M.AutoDetect,!0),this.registerOutput("depth",M.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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}; + `:G.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}j("BABYLON.FragDepthBlock",Tz);class Ez extends nt{constructor(e){super(e,W.Fragment),this.registerInput("worldPosition",M.Vector4,!1),this.registerInput("viewProjection",M.Matrix,!1),this.registerInput("worldNormal",M.AutoDetect,!0),this.registerOutput("depth",M.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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; @@ -7775,7 +7775,7 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p #endif #endif `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); -`,this}}j("BABYLON.ShadowMapBlock",vz);class xz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("viewDepth",M.Float,!0),this.registerInput("worldPosition",M.AutoDetect,!0),this.registerInput("viewNormal",M.AutoDetect,!0),this.registerInput("reflectivity",M.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4|M.Color3|M.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 +`,this}}j("BABYLON.ShadowMapBlock",Ez);class Sz extends nt{constructor(e){super(e,W.Fragment,!0),this.registerInput("viewDepth",M.Float,!0),this.registerInput("worldPosition",M.AutoDetect,!0),this.registerInput("viewNormal",M.AutoDetect,!0),this.registerInput("reflectivity",M.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4|M.Color3|M.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 @@ -7793,14 +7793,14 @@ vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float p `: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}}j("BABYLON.PrePassOutputBlock",xz);class Tz extends nt{constructor(e){super(e,W.VertexAndFragment,!1),this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("view",M.Matrix,!1,W.Vertex),this.registerInput("input",M.AutoDetect,!1,W.Fragment),this.registerInput("fogColor",M.AutoDetect,!1,W.Fragment),this.registerOutput("output",M.Color3,W.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.View&&t(s));i||(i=new Bt("view"),i.setAsSystemValue(Gt.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.FogColor&&t(s));i||(i=new Bt("fogColor",void 0,M.Color3),i.setAsSystemValue(Gt.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&Me.GetFogState(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===W.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 +`,this}}j("BABYLON.PrePassOutputBlock",Sz);class Cz extends nt{constructor(e){super(e,W.VertexAndFragment,!1),this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("view",M.Matrix,!1,W.Vertex),this.registerInput("input",M.AutoDetect,!1,W.Fragment),this.registerInput("fogColor",M.AutoDetect,!1,W.Fragment),this.registerOutput("output",M.Color3,W.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.View&&t(s));i||(i=new Vt("view"),i.setAsSystemValue(Gt.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.FogColor&&t(s));i||(i=new Vt("fogColor",void 0,M.Color3),i.setAsSystemValue(Gt.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&Me.GetFogState(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===W.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}}j("BABYLON.FogBlock",Tz);class $v extends nt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,G.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e,W.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("glossiness",M.Float,!0,W.Fragment),this.registerInput("glossPower",M.Float,!0,W.Fragment),this.registerInput("diffuseColor",M.Color3,!0,W.Fragment),this.registerInput("specularColor",M.Color3,!0,W.Fragment),this.registerInput("view",M.Matrix,!0),this.registerOutput("diffuseOutput",M.Color3,W.Fragment),this.registerOutput("specularOutput",M.Color3,W.Fragment),this.registerOutput("shadow",M.Float,W.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===Gt.CameraPosition&&t(s));i||(i=new Bt("cameraPosition"),i.setAsSystemValue(Gt.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(!this.light)Me.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights);else{const r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Me.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Me.PrepareUniformsAndSamplersForLight(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Me.BindLight(this.light,this._lightId,s,e,!0):Me.BindLights(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}; +`}return this}}j("BABYLON.FogBlock",Cz);class $v extends nt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,G.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e,W.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("glossiness",M.Float,!0,W.Fragment),this.registerInput("glossPower",M.Float,!0,W.Fragment),this.registerInput("diffuseColor",M.Color3,!0,W.Fragment),this.registerInput("specularColor",M.Color3,!0,W.Fragment),this.registerInput("view",M.Matrix,!0),this.registerOutput("diffuseOutput",M.Color3,W.Fragment),this.registerOutput("specularOutput",M.Color3,W.Fragment),this.registerOutput("shadow",M.Float,W.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===Gt.CameraPosition&&t(s));i||(i=new Vt("cameraPosition"),i.setAsSystemValue(Gt.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(!this.light)Me.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights);else{const r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Me.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Me.PrepareUniformsAndSamplersForLight(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Me.BindLight(this.light,this._lightId,s,e,!0):Me.BindLights(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!==W.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}; @@ -7818,7 +7818,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `);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()}}A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:$v._OnGenerateOnlyFragmentCodeChanged}})],$v.prototype,"generateOnlyFragmentCode",void 0);j("BABYLON.LightBlock",$v);class bo extends nt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,W.VertexAndFragment),this.registerOutput("source",M.Object,W.VertexAndFragment,new Ss("source",this,as.Output,bo,"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===W.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}); +`),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()}}A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:$v._OnGenerateOnlyFragmentCodeChanged}})],$v.prototype,"generateOnlyFragmentCode",void 0);j("BABYLON.LightBlock",$v);class bo extends nt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,W.VertexAndFragment),this.registerOutput("source",M.Object,W.VertexAndFragment,new Cs("source",this,as.Output,bo,"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===W.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}; @@ -7829,7 +7829,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `,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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}j("BABYLON.ImageSourceBlock",bo);class W_ extends nt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _IsPrePassTextureBlock(e){return(e==null?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return W_._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!W_._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){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?W.Fragment:W.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerInput("source",M.Object,!0,W.VertexAndFragment,new Ss("source",this,as.Input,bo,"ImageSourceBlock")),this.registerInput("layer",M.Float,!0),this.registerInput("lod",M.Float,!0),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this.registerOutput("level",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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 W.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return W.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===W.Fragment)return W.Fragment;if(e.target===W.Vertex)return W.VertexAndFragment;if(e.target===W.Neutral||e.target===W.VertexAndFragment){const t=e.ownerBlock;if(t.target===W.Fragment)return W.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return W.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===Cn.PostProcess){const i=e.getBlockByPredicate(s=>s.name==="uv"&&t(s));i&&i.connectTo(this)}else{const i=e.mode===Cn.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name===i&&t(r));s||(s=new Bt("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!==W.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}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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}j("BABYLON.ImageSourceBlock",bo);class W_ extends nt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _IsPrePassTextureBlock(e){return(e==null?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return W_._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!W_._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){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?W.Fragment:W.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerInput("source",M.Object,!0,W.VertexAndFragment,new Cs("source",this,as.Input,bo,"ImageSourceBlock")),this.registerInput("layer",M.Float,!0),this.registerInput("lod",M.Float,!0),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this.registerOutput("level",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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 W.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return W.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===W.Fragment)return W.Fragment;if(e.target===W.Vertex)return W.VertexAndFragment;if(e.target===W.Neutral||e.target===W.VertexAndFragment){const t=e.ownerBlock;if(t.target===W.Fragment)return W.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return W.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===bn.PostProcess){const i=e.getBlockByPredicate(s=>s.name==="uv"&&t(s));i&&i.connectTo(this)}else{const i=e.mode===bn.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name===i&&t(r));s||(s=new Vt("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!==W.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; @@ -7863,7 +7863,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `,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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}j("BABYLON.TextureBlock",W_);class Od extends nt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment)}constructor(e){super(e,W.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 Bt("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.World&&t(s));i||(i=new Bt("world"),i.setAsSystemValue(Gt.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Bt("view"),i.setAsSystemValue(Gt.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){const s=this._getTexture();if(!(!i||!s)&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const r=s;e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===W.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}; +`),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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}j("BABYLON.TextureBlock",W_);class Nd extends nt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment)}constructor(e){super(e,W.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 Vt("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.World&&t(s));i||(i=new Vt("world"),i.setAsSystemValue(Gt.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Vt("view"),i.setAsSystemValue(Gt.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){const s=this._getTexture();if(!(!i||!s)&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const r=s;e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===W.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 @@ -7941,30 +7941,30 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `);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&&!ys.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=lr.Parse(e.texture,t,i):this.texture=ee.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Od._OnGenerateOnlyFragmentCodeChanged}})],Od.prototype,"generateOnlyFragmentCode",void 0);j("BABYLON.ReflectionTextureBaseBlock",Od);class Ez extends Od{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,G.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,G.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?W.Fragment:W.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e),this.registerInput("position",M.AutoDetect,!1,W.Vertex),this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("world",M.Matrix,!1,W.Vertex),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("view",M.Matrix,!1,W.Fragment),this.registerOutput("rgb",M.Color3,W.Fragment),this.registerOutput("rgba",M.Color4,W.Fragment),this.registerOutput("r",M.Float,W.Fragment),this.registerOutput("g",M.Float,W.Fragment),this.registerOutput("b",M.Float,W.Fragment),this.registerOutput("a",M.Float,W.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.CameraPosition&&t(s));i||(i=new Bt("cameraPosition"),i.setAsSystemValue(Gt.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!==W.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}}j("BABYLON.ReflectionTextureBlock",Ez);class Vm extends nt{constructor(e){super(e,W.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("depth",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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?W.VertexAndFragment:W.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===M.Vector3?"3":t.type===M.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,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&&!ys.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=lr.Parse(e.texture,t,i):this.texture=ee.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Nd._OnGenerateOnlyFragmentCodeChanged}})],Nd.prototype,"generateOnlyFragmentCode",void 0);j("BABYLON.ReflectionTextureBaseBlock",Nd);class bz extends Nd{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,G.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,G.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?W.Fragment:W.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e),this.registerInput("position",M.AutoDetect,!1,W.Vertex),this.registerInput("worldPosition",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("world",M.Matrix,!1,W.Vertex),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("view",M.Matrix,!1,W.Fragment),this.registerOutput("rgb",M.Color3,W.Fragment),this.registerOutput("rgba",M.Color4,W.Fragment),this.registerOutput("r",M.Float,W.Fragment),this.registerOutput("g",M.Float,W.Fragment),this.registerOutput("b",M.Float,W.Fragment),this.registerOutput("a",M.Float,W.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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===Gt.CameraPosition&&t(s));i||(i=new Vt("cameraPosition"),i.setAsSystemValue(Gt.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!==W.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}}j("BABYLON.ReflectionTextureBlock",bz);class Vm extends nt{constructor(e){super(e,W.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",M.AutoDetect,!1,W.VertexAndFragment),this.registerOutput("depth",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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?W.VertexAndFragment:W.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===M.Vector3?"3":t.type===M.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===W.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); `;return}if(this.uv.ownerBlock.target===W.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===W.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===W.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!==W.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}}A([ft("Use non linear depth",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(o,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),o&&o.disableDepthRenderer(),i}}})],Vm.prototype,"useNonLinearDepth",void 0);A([ft("Store Camera space Z",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(o,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),o&&o.disableDepthRenderer(),i}}})],Vm.prototype,"storeCameraSpaceZ",void 0);A([ft("Force 32 bits float",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:o=>o==null?void 0:o.disableDepthRenderer()}})],Vm.prototype,"force32itsFloat",void 0);j("BABYLON.SceneDepthBlock",Vm);class Sz extends nt{constructor(e){super(e,W.VertexAndFragment,!0),this.registerInput("worldPosition",M.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 W.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var s,r,n,a,l,h;const c=e.getScene(),u=!!((s=t.clipPlane)!==null&&s!==void 0?s:c.clipPlane),d=!!((r=t.clipPlane2)!==null&&r!==void 0?r:c.clipPlane2),f=!!((n=t.clipPlane3)!==null&&n!==void 0?n:c.clipPlane3),p=!!((a=t.clipPlane4)!==null&&a!==void 0?a:c.clipPlane4),_=!!((l=t.clipPlane5)!==null&&l!==void 0?l:c.clipPlane5),g=!!((h=t.clipPlane6)!==null&&h!==void 0?h:c.clipPlane6);i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",d,!0),i.setValue("CLIPPLANE3",f,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",g,!0)}bind(e,t,i){if(!i)return;const s=i.getScene();so(e,t,s)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==W.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}}j("BABYLON.ClipPlanesBlock",Sz);class Cz extends nt{get texture(){return null}set texture(e){}constructor(e,t=W.VertexAndFragment){super(e,t,!1),this.registerOutput("position",M.Object,W.VertexAndFragment,new Ss("position",this,as.Output,bo,"ImageSourceBlock")),this.registerOutput("depth",M.Object,W.VertexAndFragment,new Ss("depth",this,as.Output,bo,"ImageSourceBlock")),this.registerOutput("normal",M.Object,W.VertexAndFragment,new Ss("normal",this,as.Output,bo,"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!==W.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)]))}}j("BABYLON.PrePassTextureBlock",Cz);class bz extends nt{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==W.VertexAndFragment)return t.target;if(e.connectedPoint.target!==W.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,W.Neutral),this._endpoints=[],this.registerInput("input",M.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=[]}}j("BABYLON.NodeMaterialTeleportInBlock",bz);class yz extends nt{constructor(e){super(e,W.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",M.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}; +`}_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!==W.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}}A([ft("Use non linear depth",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(o,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),o&&o.disableDepthRenderer(),i}}})],Vm.prototype,"useNonLinearDepth",void 0);A([ft("Store Camera space Z",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(o,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),o&&o.disableDepthRenderer(),i}}})],Vm.prototype,"storeCameraSpaceZ",void 0);A([ft("Force 32 bits float",ut.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:o=>o==null?void 0:o.disableDepthRenderer()}})],Vm.prototype,"force32itsFloat",void 0);j("BABYLON.SceneDepthBlock",Vm);class yz extends nt{constructor(e){super(e,W.VertexAndFragment,!0),this.registerInput("worldPosition",M.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 W.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var s,r,n,a,l,h;const c=e.getScene(),u=!!((s=t.clipPlane)!==null&&s!==void 0?s:c.clipPlane),d=!!((r=t.clipPlane2)!==null&&r!==void 0?r:c.clipPlane2),f=!!((n=t.clipPlane3)!==null&&n!==void 0?n:c.clipPlane3),p=!!((a=t.clipPlane4)!==null&&a!==void 0?a:c.clipPlane4),_=!!((l=t.clipPlane5)!==null&&l!==void 0?l:c.clipPlane5),g=!!((h=t.clipPlane6)!==null&&h!==void 0?h:c.clipPlane6);i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",d,!0),i.setValue("CLIPPLANE3",f,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",g,!0)}bind(e,t,i){if(!i)return;const s=i.getScene();so(e,t,s)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==W.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}}j("BABYLON.ClipPlanesBlock",yz);class Az extends nt{get texture(){return null}set texture(e){}constructor(e,t=W.VertexAndFragment){super(e,t,!1),this.registerOutput("position",M.Object,W.VertexAndFragment,new Cs("position",this,as.Output,bo,"ImageSourceBlock")),this.registerOutput("depth",M.Object,W.VertexAndFragment,new Cs("depth",this,as.Output,bo,"ImageSourceBlock")),this.registerOutput("normal",M.Object,W.VertexAndFragment,new Cs("normal",this,as.Output,bo,"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!==W.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)]))}}j("BABYLON.PrePassTextureBlock",Az);class Rz extends nt{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==W.VertexAndFragment)return t.target;if(e.connectedPoint.target!==W.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,W.Neutral),this._endpoints=[],this.registerInput("input",M.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=[]}}j("BABYLON.NodeMaterialTeleportInBlock",Rz);class Iz extends nt{constructor(e){super(e,W.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",M.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 e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}j("BABYLON.NodeMaterialTeleportOutBlock",yz);class Az extends nt{constructor(e){super(e,W.Neutral),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].acceptedConnectionPointTypes.push(M.Float),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.AddBlock",Az);class Rz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerInput("factor",M.Float),this.registerOutput("output",M.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}}j("BABYLON.ScaleBlock",Rz);class rT extends nt{constructor(e){super(e,W.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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)}); +`),e}serialize(){var e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}j("BABYLON.NodeMaterialTeleportOutBlock",Iz);class Pz extends nt{constructor(e){super(e,W.Neutral),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].acceptedConnectionPointTypes.push(M.Float),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.AddBlock",Pz);class Mz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerInput("factor",M.Float),this.registerOutput("output",M.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}}j("BABYLON.ScaleBlock",Mz);class aT extends nt{constructor(e){super(e,W.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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}}A([ft("Minimum",ut.Float)],rT.prototype,"minimum",void 0);A([ft("Maximum",ut.Float)],rT.prototype,"maximum",void 0);j("BABYLON.ClampBlock",rT);class Iz extends nt{constructor(e){super(e,W.Neutral),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.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Vector2),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.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}}j("BABYLON.CrossBlock",Iz);class Pz extends nt{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"),a=e._getGLType(r.type);t=t.replace(n,a),i=i.replace(n,a)}),this._outputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(n,a),i=i.replace(n,a)}),e._emitFunction(i,t,""),this._outputs.forEach(r=>{e.compilationString+=this._declareOutput(r,e)+`; +`,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}}A([ft("Minimum",ut.Float)],aT.prototype,"minimum",void 0);A([ft("Maximum",ut.Float)],aT.prototype,"maximum",void 0);j("BABYLON.ClampBlock",aT);class Dz extends nt{constructor(e){super(e,W.Neutral),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.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Vector2),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.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}}j("BABYLON.CrossBlock",Dz);class Oz extends nt{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"),a=e._getGLType(r.type);t=t.replace(n,a),i=i.replace(n,a)}),this._outputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(n,a),i=i.replace(n,a)}),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 a,l,h;n>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(r.name)!==-1?e.compilationString+=(h=(l=(a=r.connectedPoint)===null||a===void 0?void 0:a.ownerBlock)===null||l===void 0?void 0:l.samplerName)!==null&&h!==void 0?h: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=W[e.target],(t=e.inParameters)===null||t===void 0||t.forEach((r,n)=>{const a=M[r.type];r.type==="sampler2D"||r.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(r.name),this.registerInput(r.name,M.Object,!0,W.VertexAndFragment,new Ss(r.name,this,as.Input,bo,"ImageSourceBlock"))):this.registerInput(r.name,a),Object.defineProperty(this,r.name,{get:function(){return this._inputs[n]},enumerable:!0,configurable:!0})}),(i=e.outParameters)===null||i===void 0||i.forEach((r,n)=>{this.registerOutput(r.name,M[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===void 0||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{const a=M[r.type];r.type==="sampler2D"||r.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(r.name),this.registerInput(r.name,M.Object,!0,W.VertexAndFragment,new Cs(r.name,this,as.Input,bo,"ImageSourceBlock"))):this.registerInput(r.name,a),Object.defineProperty(this,r.name,{get:function(){return this._inputs[n]},enumerable:!0,configurable:!0})}),(i=e.outParameters)===null||i===void 0||i.forEach((r,n)=>{this.registerOutput(r.name,M[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===void 0||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!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.CameraPosition&&t(s));i||(i=new Bt("cameraPosition"),i.setAsSystemValue(Gt.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}}j("BABYLON.ViewDirectionBlock",Ry);class Vz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("worldNormal",M.Vector4),this.registerInput("viewDirection",M.Vector3),this.registerInput("bias",M.Float),this.registerInput("power",M.Float),this.registerOutput("fresnel",M.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 Ry("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new Bt("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new Bt("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}}j("BABYLON.FresnelBlock",Vz);class Uz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.MaxBlock",Uz);class kz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.MinBlock",kz);class Gz extends nt{constructor(e){super(e,W.Neutral),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.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.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}}j("BABYLON.DistanceBlock",Gz);class zz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.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}}j("BABYLON.LengthBlock",zz);class Wz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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}}j("BABYLON.NegateBlock",Wz);class Hz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.PowBlock",Hz);class Xz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("seed",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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}}j("BABYLON.RandomNumberBlock",Xz);class Yz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("x",M.Float),this.registerInput("y",M.Float),this.registerOutput("output",M.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}}j("BABYLON.ArcTan2Block",Yz);class $z extends nt{constructor(e){super(e,W.Neutral),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]}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}}j("BABYLON.SmoothStepBlock",$z);class Kz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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===M.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`),this}}j("BABYLON.VectorSplitterBlock",Lz);class Bz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerInput("gradient",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.LerpBlock",Bz);class Vz extends nt{constructor(e){super(e,W.Neutral),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].acceptedConnectionPointTypes.push(M.Float),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.DivideBlock",Vz);class Uz extends nt{constructor(e){super(e,W.Neutral),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].acceptedConnectionPointTypes.push(M.Float),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.SubtractBlock",Uz);class kz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("value",M.Float),this.registerInput("edge",M.Float),this.registerOutput("output",M.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}}j("BABYLON.StepBlock",kz);class Iy extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(M.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}}j("BABYLON.OneMinusBlock",Iy);j("BABYLON.OppositeBlock",Iy);class Py extends nt{constructor(e){super(e,W.Neutral),this.registerInput("worldPosition",M.Vector4),this.registerInput("cameraPosition",M.Vector3),this.registerOutput("output",M.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===Gt.CameraPosition&&t(s));i||(i=new Vt("cameraPosition"),i.setAsSystemValue(Gt.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}}j("BABYLON.ViewDirectionBlock",Py);class Gz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("worldNormal",M.Vector4),this.registerInput("viewDirection",M.Vector3),this.registerInput("bias",M.Float),this.registerInput("power",M.Float),this.registerOutput("fresnel",M.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 Py("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new Vt("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new Vt("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}}j("BABYLON.FresnelBlock",Gz);class zz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.MaxBlock",zz);class Wz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.MinBlock",Wz);class Hz extends nt{constructor(e){super(e,W.Neutral),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.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.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}}j("BABYLON.DistanceBlock",Hz);class Xz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.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}}j("BABYLON.LengthBlock",Xz);class Yz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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}}j("BABYLON.NegateBlock",Yz);class $z extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.PowBlock",$z);class Kz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("seed",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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}}j("BABYLON.RandomNumberBlock",Kz);class qz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("x",M.Float),this.registerInput("y",M.Float),this.registerOutput("output",M.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}}j("BABYLON.ArcTan2Block",qz);class jz extends nt{constructor(e){super(e,W.Neutral),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]}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}}j("BABYLON.SmoothStepBlock",jz);class Qz extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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===M.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); `:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; -`,this}}j("BABYLON.ReciprocalBlock",Kz);class qz extends nt{constructor(e){super(e,W.Neutral),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"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)+`; +`,this}}j("BABYLON.ReciprocalBlock",Qz);class Zz extends nt{constructor(e){super(e,W.Neutral),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"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}}j("BABYLON.ReplaceColorBlock",qz);class jz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.PosterizeBlock",jz);var Lc;(function(o){o[o.SawTooth=0]="SawTooth",o[o.Square=1]="Square",o[o.Triangle=2]="Triangle"})(Lc||(Lc={}));class Qz extends nt{constructor(e){super(e,W.Neutral),this.kind=Lc.SawTooth,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.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 Lc.SawTooth:{e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`,this}}j("BABYLON.ReplaceColorBlock",Zz);class Jz extends nt{constructor(e){super(e,W.Neutral),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)}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}}j("BABYLON.PosterizeBlock",Jz);var Lc;(function(o){o[o.SawTooth=0]="SawTooth",o[o.Square=1]="Square",o[o.Triangle=2]="Triangle"})(Lc||(Lc={}));class e4 extends nt{constructor(e){super(e,W.Neutral),this.kind=Lc.SawTooth,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.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 Lc.SawTooth:{e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); `;break}case Lc.Square:{e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); `;break}case Lc.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}}j("BABYLON.WaveBlock",Qz);class bv{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 Zz extends nt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,W.Neutral),this.colorSteps=[new bv(0,Te.Black()),new bv(1,Te.White())],this.onValueChangedObservable=new he,this.registerInput("gradient",M.AutoDetect),this.registerOutput("output",M.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Float|M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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.); +`;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}}j("BABYLON.WaveBlock",e4);class bv{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 t4 extends nt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,W.Neutral),this.colorSteps=[new bv(0,Te.Black()),new bv(1,Te.White())],this.onValueChangedObservable=new he,this.registerInput("gradient",M.AutoDetect),this.registerOutput("output",M.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Float|M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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!==M.Float&&(r+=".x");for(let n=1;n!0){if(!this.intensity.isConnected){const i=new Bt("Refraction intensity",W.Fragment,M.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Bt("view"),i.setAsSystemValue(Gt.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 s,r,n,a;super.bind(e,t,i);const l=this._getTexture();if(!l)return;l.isCube?e.setTexture(this._cubeSamplerName,l):e.setTexture(this._2DSamplerName,l),e.setMatrix(this._refractionMatrixName,l.getRefractionTextureMatrix());let h=1;l.isCube||l.depth&&(h=l.depth);const c=(a=(r=(s=this.volumeIndexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:(n=this.indexOfRefractionConnectionPoint.connectInputBlock)===null||n===void 0?void 0:n.value)!==null&&a!==void 0?a:1.5;e.setFloat4(this._vRefractionInfosName,l.level,1/c,h,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset,1/c);const u=l.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,u,ye.Log2(u)),l.boundingBoxSize){const d=l;e.setVector3("vRefractionPosition",d.boundingBoxPosition),e.setVector3("vRefractionSize",d.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} +`,t}_buildBlock(e){return e.target===W.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)}}j("BABYLON.IridescenceBlock",wd);class rc extends nt{constructor(e){super(e,W.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",M.Float,!1,W.Fragment),this.registerInput("tintAtDistance",M.Float,!0,W.Fragment),this.registerInput("volumeIndexOfRefraction",M.Float,!0,W.Fragment),this.registerOutput("refraction",M.Object,W.Fragment,new Cs("refraction",this,as.Output,rc,"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 Vt("Refraction intensity",W.Fragment,M.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Vt("view"),i.setAsSystemValue(Gt.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 s,r,n,a;super.bind(e,t,i);const l=this._getTexture();if(!l)return;l.isCube?e.setTexture(this._cubeSamplerName,l):e.setTexture(this._2DSamplerName,l),e.setMatrix(this._refractionMatrixName,l.getRefractionTextureMatrix());let h=1;l.isCube||l.depth&&(h=l.depth);const c=(a=(r=(s=this.volumeIndexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:(n=this.indexOfRefractionConnectionPoint.connectInputBlock)===null||n===void 0?void 0:n.value)!==null&&a!==void 0?a:1.5;e.setFloat4(this._vRefractionInfosName,l.level,1/c,h,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset,1/c);const u=l.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,u,ye.Log2(u)),l.boundingBoxSize){const d=l;e.setVector3("vRefractionPosition",d.boundingBoxPosition),e.setVector3("vRefractionSize",d.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}; @@ -8517,7 +8517,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `),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=lr.Parse(e.texture,t,i):this.texture=ee.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}A([ft("Link refraction to transparency",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],sc.prototype,"linkRefractionWithTransparency",void 0);A([ft("Invert refraction Y",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],sc.prototype,"invertRefractionY",void 0);A([ft("Use thickness as depth",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],sc.prototype,"useThicknessAsDepth",void 0);j("BABYLON.RefractionBlock",sc);class wd extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("thickness",M.Float,!1,W.Fragment),this.registerInput("tintColor",M.Color3,!0,W.Fragment),this.registerInput("translucencyIntensity",M.Float,!0,W.Fragment),this.registerInput("translucencyDiffusionDist",M.Color3,!0,W.Fragment),this.registerInput("refraction",M.Object,!0,W.Fragment,new Ss("refraction",this,as.Input,sc,"RefractionBlock")),this.registerInput("dispersion",M.Float,!0,W.Fragment),this.registerOutput("subsurface",M.Object,W.Fragment,new Ss("subsurface",this,as.Output,wd,"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 Bt("SubSurface thickness",W.Fragment,M.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 r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S;let b="";const R=t!=null&&t.thickness.isConnected?t.thickness.associatedVariableName:"0.",I=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",N=t!=null&&t.translucencyIntensity.isConnected?t==null?void 0:t.translucencyIntensity.associatedVariableName:"1.",O=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",L=t!=null&&t.refraction.isConnected?(r=t==null?void 0:t.refraction.connectedPoint)===null||r===void 0?void 0:r.ownerBlock:null,B=L!=null&&L.tintAtDistance.isConnected?L.tintAtDistance.associatedVariableName:"1.",V=L!=null&&L.intensity.isConnected?L.intensity.associatedVariableName:"1.",Z=L!=null&&L.view.isConnected?L.view.associatedVariableName:"",ue=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0";return b+=(n=L==null?void 0:L.getCode(e))!==null&&n!==void 0?n:"",b+=`subSurfaceOutParams subSurfaceOut; +`,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=lr.Parse(e.texture,t,i):this.texture=ee.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}A([ft("Link refraction to transparency",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],rc.prototype,"linkRefractionWithTransparency",void 0);A([ft("Invert refraction Y",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],rc.prototype,"invertRefractionY",void 0);A([ft("Use thickness as depth",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],rc.prototype,"useThicknessAsDepth",void 0);j("BABYLON.RefractionBlock",rc);class Fd extends nt{constructor(e){super(e,W.Fragment),this._isUnique=!0,this.registerInput("thickness",M.Float,!1,W.Fragment),this.registerInput("tintColor",M.Color3,!0,W.Fragment),this.registerInput("translucencyIntensity",M.Float,!0,W.Fragment),this.registerInput("translucencyDiffusionDist",M.Color3,!0,W.Fragment),this.registerInput("refraction",M.Object,!0,W.Fragment,new Cs("refraction",this,as.Input,rc,"RefractionBlock")),this.registerInput("dispersion",M.Float,!0,W.Fragment),this.registerOutput("subsurface",M.Object,W.Fragment,new Cs("subsurface",this,as.Output,Fd,"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 Vt("SubSurface thickness",W.Fragment,M.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 r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S;let b="";const R=t!=null&&t.thickness.isConnected?t.thickness.associatedVariableName:"0.",I=t!=null&&t.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",N=t!=null&&t.translucencyIntensity.isConnected?t==null?void 0:t.translucencyIntensity.associatedVariableName:"1.",O=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",L=t!=null&&t.refraction.isConnected?(r=t==null?void 0:t.refraction.connectedPoint)===null||r===void 0?void 0:r.ownerBlock:null,B=L!=null&&L.tintAtDistance.isConnected?L.tintAtDistance.associatedVariableName:"1.",V=L!=null&&L.intensity.isConnected?L.intensity.associatedVariableName:"1.",Z=L!=null&&L.view.isConnected?L.view.associatedVariableName:"",ue=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0";return b+=(n=L==null?void 0:L.getCode(e))!==null&&n!==void 0?n:"",b+=`subSurfaceOutParams subSurfaceOut; #ifdef SUBSURFACE vec2 vThicknessParam = vec2(0., ${R}); @@ -8614,7 +8614,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; #else subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; #endif -`,b}_buildBlock(e){return e.target===W.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}j("BABYLON.SubSurfaceBlock",wd);const a4={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 cr extends nt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,G.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e,W.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Te.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",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("view",M.Matrix,!1),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("perturbedNormal",M.Vector4,!0,W.Fragment),this.registerInput("baseColor",M.Color3,!0,W.Fragment),this.registerInput("metallic",M.Float,!1,W.Fragment),this.registerInput("roughness",M.Float,!1,W.Fragment),this.registerInput("ambientOcc",M.Float,!0,W.Fragment),this.registerInput("opacity",M.Float,!0,W.Fragment),this.registerInput("indexOfRefraction",M.Float,!0,W.Fragment),this.registerInput("ambientColor",M.Color3,!0,W.Fragment),this.registerInput("reflection",M.Object,!0,W.Fragment,new Ss("reflection",this,as.Input,Cu,"ReflectionBlock")),this.registerInput("clearcoat",M.Object,!0,W.Fragment,new Ss("clearcoat",this,as.Input,au,"ClearCoatBlock")),this.registerInput("sheen",M.Object,!0,W.Fragment,new Ss("sheen",this,as.Input,Su,"SheenBlock")),this.registerInput("subsurface",M.Object,!0,W.Fragment,new Ss("subsurface",this,as.Input,wd,"SubSurfaceBlock")),this.registerInput("anisotropy",M.Object,!0,W.Fragment,new Ss("anisotropy",this,as.Input,Um,"AnisotropyBlock")),this.registerInput("iridescence",M.Object,!0,W.Fragment,new Ss("iridescence",this,as.Input,Nd,"IridescenceBlock")),this.registerOutput("ambientClr",M.Color3,W.Fragment),this.registerOutput("diffuseDir",M.Color3,W.Fragment),this.registerOutput("specularDir",M.Color3,W.Fragment),this.registerOutput("clearcoatDir",M.Color3,W.Fragment),this.registerOutput("sheenDir",M.Color3,W.Fragment),this.registerOutput("diffuseInd",M.Color3,W.Fragment),this.registerOutput("specularInd",M.Color3,W.Fragment),this.registerOutput("clearcoatInd",M.Color3,W.Fragment),this.registerOutput("sheenInd",M.Color3,W.Fragment),this.registerOutput("refraction",M.Color3,W.Fragment),this.registerOutput("lighting",M.Color3,W.Fragment),this.registerOutput("shadow",M.Float,W.Fragment),this.registerOutput("alpha",M.Float,W.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===Gt.CameraPosition&&t(s));i||(i=new Bt("cameraPosition"),i.setAsSystemValue(Gt.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Bt("view"),i.setAsSystemValue(Gt.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===Ni.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Ni.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&&we.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)Me.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Me.PrepareDefinesForMultiview(r,i);else{const a={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Me.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,a),a.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Me.PrepareUniformsAndSamplersForLight(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 s,r;if(!i)return;const n=i.getScene();this.light?Me.BindLight(this.light,this._lightId,n,e,!0):Me.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);const l=n.useRightHandedSystem===(n._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const h=1,c=(r=(s=this.indexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:1.5,u=Math.pow((c-h)/(c+h),2);this._metallicReflectanceColor.scaleToRef(u*this._metallicF0Factor,gi.Color3[0]);const d=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,gi.Color3[0],d),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const s=this.worldPosition,r=`//${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",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+s.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${s.associatedVariableName}; +`,b}_buildBlock(e){return e.target===W.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}j("BABYLON.SubSurfaceBlock",Fd);const h4={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 cr extends nt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,G.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?W.Fragment:W.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?W.Fragment:W.Vertex}constructor(e){super(e,W.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Te.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",M.Vector4,!1,W.Vertex),this.registerInput("worldNormal",M.Vector4,!1,W.Fragment),this.registerInput("view",M.Matrix,!1),this.registerInput("cameraPosition",M.Vector3,!1,W.Fragment),this.registerInput("perturbedNormal",M.Vector4,!0,W.Fragment),this.registerInput("baseColor",M.Color3,!0,W.Fragment),this.registerInput("metallic",M.Float,!1,W.Fragment),this.registerInput("roughness",M.Float,!1,W.Fragment),this.registerInput("ambientOcc",M.Float,!0,W.Fragment),this.registerInput("opacity",M.Float,!0,W.Fragment),this.registerInput("indexOfRefraction",M.Float,!0,W.Fragment),this.registerInput("ambientColor",M.Color3,!0,W.Fragment),this.registerInput("reflection",M.Object,!0,W.Fragment,new Cs("reflection",this,as.Input,Cu,"ReflectionBlock")),this.registerInput("clearcoat",M.Object,!0,W.Fragment,new Cs("clearcoat",this,as.Input,au,"ClearCoatBlock")),this.registerInput("sheen",M.Object,!0,W.Fragment,new Cs("sheen",this,as.Input,Su,"SheenBlock")),this.registerInput("subsurface",M.Object,!0,W.Fragment,new Cs("subsurface",this,as.Input,Fd,"SubSurfaceBlock")),this.registerInput("anisotropy",M.Object,!0,W.Fragment,new Cs("anisotropy",this,as.Input,Um,"AnisotropyBlock")),this.registerInput("iridescence",M.Object,!0,W.Fragment,new Cs("iridescence",this,as.Input,wd,"IridescenceBlock")),this.registerOutput("ambientClr",M.Color3,W.Fragment),this.registerOutput("diffuseDir",M.Color3,W.Fragment),this.registerOutput("specularDir",M.Color3,W.Fragment),this.registerOutput("clearcoatDir",M.Color3,W.Fragment),this.registerOutput("sheenDir",M.Color3,W.Fragment),this.registerOutput("diffuseInd",M.Color3,W.Fragment),this.registerOutput("specularInd",M.Color3,W.Fragment),this.registerOutput("clearcoatInd",M.Color3,W.Fragment),this.registerOutput("sheenInd",M.Color3,W.Fragment),this.registerOutput("refraction",M.Color3,W.Fragment),this.registerOutput("lighting",M.Color3,W.Fragment),this.registerOutput("shadow",M.Float,W.Fragment),this.registerOutput("alpha",M.Float,W.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===Gt.CameraPosition&&t(s));i||(i=new Vt("cameraPosition"),i.setAsSystemValue(Gt.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===Gt.View&&t(s));i||(i=new Vt("view"),i.setAsSystemValue(Gt.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===Ni.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Ni.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&&we.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)Me.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Me.PrepareDefinesForMultiview(r,i);else{const a={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Me.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,a),a.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Me.PrepareUniformsAndSamplersForLight(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 s,r;if(!i)return;const n=i.getScene();this.light?Me.BindLight(this.light,this._lightId,n,e,!0):Me.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);const l=n.useRightHandedSystem===(n._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const h=1,c=(r=(s=this.indexOfRefraction.connectInputBlock)===null||s===void 0?void 0:s.value)!==null&&r!==void 0?r:1.5,u=Math.pow((c-h)/(c+h),2);this._metallicReflectanceColor.scaleToRef(u*this._metallicF0Factor,gi.Color3[0]);const d=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,gi.Color3[0],d),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const s=this.worldPosition,r=`//${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",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+s.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${s.associatedVariableName}; `);const a=this.reflection.isConnected?(t=this.reflection.connectedPoint)===null||t===void 0?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=(i=a==null?void 0:a.handleVertexSide(e))!==null&&i!==void 0?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 `,e._injectAtEnd+=`vClipSpacePosition = gl_Position; `,e._injectAtEnd+=`#endif @@ -8675,7 +8675,7 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; #endif -`,t}_buildBlock(e){var t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S,b,R,I,N,O,L,B,V,Z,ue,oe,me,le,ae,ce,ie,w,H,X,te,Q,_e;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=Kx(this._scene));const q=this.reflection.isConnected?(t=this.reflection.connectedPoint)===null||t===void 0?void 0:t.ownerBlock:null;if(q&&(q.worldPositionConnectionPoint=this.worldPosition,q.cameraPositionConnectionPoint=this.cameraPosition,q.worldNormalConnectionPoint=this.worldNormal,q.viewConnectionPoint=this.view),e.target!==W.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 de=`//${this.name}`,ge=this.perturbedNormal;let ve=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(ve=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${ve}; +`,t}_buildBlock(e){var t,i,s,r,n,a,l,h,c,u,d,f,p,_,g,v,E,C,S,b,R,I,N,O,L,B,V,Z,ue,oe,me,le,ae,ce,ie,w,H,X,te,Q,_e;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=jx(this._scene));const q=this.reflection.isConnected?(t=this.reflection.connectedPoint)===null||t===void 0?void 0:t.ownerBlock:null;if(q&&(q.worldPositionConnectionPoint=this.worldPosition,q.cameraPositionConnectionPoint=this.cameraPosition,q.worldNormalConnectionPoint=this.worldNormal,q.viewConnectionPoint=this.view),e.target!==W.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 de=`//${this.name}`,ge=this.perturbedNormal;let ve=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(ve=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${ve}; `,de),e.compilationString+=`${ve} = ${this.worldPosition.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",de,{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); @@ -8687,10 +8687,10 @@ ${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb; `,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",de,{replaceStrings:[{search:/vPositionW/g,replace:ve+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",de),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",de),e.compilationString+=`#ifdef UNLIT vec3 diffuseBase = vec3(1., 1., 1.); #else -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",de,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(s=q==null?void 0:q._defineSkyboxName)!==null&&s!==void 0?s:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(r=q==null?void 0:q._define3DName)!==null&&r!==void 0?r:"REFLECTIONMAP_3D"}]});const be=this.anisotropy.isConnected?(n=this.anisotropy.connectedPoint)===null||n===void 0?void 0:n.ownerBlock:null;be&&(be.worldPositionConnectionPoint=this.worldPosition,be.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=be.getCode(e,!this.perturbedNormal.isConnected)),q&&q.hasTexture&&(e.compilationString+=q.getCode(e,be?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",de,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(a=q==null?void 0:q._define3DName)!==null&&a!==void 0?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(l=q==null?void 0:q._defineOppositeZ)!==null&&l!==void 0?l:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(h=q==null?void 0:q._defineProjectionName)!==null&&h!==void 0?h:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(c=q==null?void 0:q._defineSkyboxName)!==null&&c!==void 0?c:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(u=q==null?void 0:q._defineLODReflectionAlpha)!==null&&u!==void 0?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(d=q==null?void 0:q._defineLinearSpecularReflection)!==null&&d!==void 0?d:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(f=q==null?void 0:q._vReflectionFilteringInfoName)!==null&&f!==void 0?f:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",de,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const Le=this.sheen.isConnected?(p=this.sheen.connectedPoint)===null||p===void 0?void 0:p.ownerBlock:null;Le&&(e.compilationString+=Le.getCode(q)),e._emitFunctionFromInclude("pbrBlockSheen",de,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(_=q==null?void 0:q._define3DName)!==null&&_!==void 0?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(g=q==null?void 0:q._defineSkyboxName)!==null&&g!==void 0?g:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(v=q==null?void 0:q._defineLODReflectionAlpha)!==null&&v!==void 0?v:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(E=q==null?void 0:q._defineLinearSpecularReflection)!==null&&E!==void 0?E:"LINEARSPECULARREFLECTION"}]});const Ye=this.iridescence.isConnected?(C=this.iridescence.connectedPoint)===null||C===void 0?void 0:C.ownerBlock:null;e.compilationString+=Nd.GetCode(Ye),e._emitFunctionFromInclude("pbrBlockIridescence",de,{replaceStrings:[]});const He=this.clearcoat.isConnected?(S=this.clearcoat.connectedPoint)===null||S===void 0?void 0:S.ownerBlock:null,Be=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Ge=this.perturbedNormal.isConnected&&((R=((b=this.perturbedNormal.connectedPoint)===null||b===void 0?void 0:b.ownerBlock).worldTangent)===null||R===void 0?void 0:R.isConnected),Lt=this.anisotropy.isConnected&&((I=this.anisotropy.connectedPoint)===null||I===void 0?void 0:I.ownerBlock).worldTangent.isConnected;let Mt=Ge||!this.perturbedNormal.isConnected&≪e.compilationString+=au.GetCode(e,He,q,ve,Be,Mt,this.worldNormal.associatedVariableName),Be&&(Mt=(N=He==null?void 0:He.worldTangent.isConnected)!==null&&N!==void 0?N:!1),e._emitFunctionFromInclude("pbrBlockClearcoat",de,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(O=q==null?void 0:q._define3DName)!==null&&O!==void 0?O:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(L=q==null?void 0:q._defineOppositeZ)!==null&&L!==void 0?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(B=q==null?void 0:q._defineProjectionName)!==null&&B!==void 0?B:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(V=q==null?void 0:q._defineSkyboxName)!==null&&V!==void 0?V:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(Z=q==null?void 0:q._defineLODReflectionAlpha)!==null&&Z!==void 0?Z:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(ue=q==null?void 0:q._defineLinearSpecularReflection)!==null&&ue!==void 0?ue:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:Mt?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",de,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(oe=q==null?void 0:q._defineSkyboxName)!==null&&oe!==void 0?oe:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(me=q==null?void 0:q._define3DName)!==null&&me!==void 0?me:"REFLECTIONMAP_3D"}]});const Vi=this.subsurface.isConnected?(le=this.subsurface.connectedPoint)===null||le===void 0?void 0:le.ownerBlock:null,at=this.subsurface.isConnected?(ce=((ae=this.subsurface.connectedPoint)===null||ae===void 0?void 0:ae.ownerBlock).refraction.connectedPoint)===null||ce===void 0?void 0:ce.ownerBlock:null;at&&(at.viewConnectionPoint=this.view,at.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=wd.GetCode(e,Vi,q,ve),e._emitFunctionFromInclude("pbrBlockSubSurface",de,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(ie=q==null?void 0:q._define3DName)!==null&&ie!==void 0?ie:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(w=q==null?void 0:q._defineOppositeZ)!==null&&w!==void 0?w:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(H=q==null?void 0:q._defineProjectionName)!==null&&H!==void 0?H:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(X=at==null?void 0:at._define3DName)!==null&&X!==void 0?X:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(te=at==null?void 0:at._defineLODRefractionAlpha)!==null&&te!==void 0?te:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(Q=at==null?void 0:at._defineLinearSpecularRefraction)!==null&&Q!==void 0?Q:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(_e=at==null?void 0:at._defineOppositeZ)!==null&&_e!==void 0?_e:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",de),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",de,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:ve+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",de,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${ve}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",de),e.compilationString+=`#endif +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",de,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(s=q==null?void 0:q._defineSkyboxName)!==null&&s!==void 0?s:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(r=q==null?void 0:q._define3DName)!==null&&r!==void 0?r:"REFLECTIONMAP_3D"}]});const be=this.anisotropy.isConnected?(n=this.anisotropy.connectedPoint)===null||n===void 0?void 0:n.ownerBlock:null;be&&(be.worldPositionConnectionPoint=this.worldPosition,be.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=be.getCode(e,!this.perturbedNormal.isConnected)),q&&q.hasTexture&&(e.compilationString+=q.getCode(e,be?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",de,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(a=q==null?void 0:q._define3DName)!==null&&a!==void 0?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(l=q==null?void 0:q._defineOppositeZ)!==null&&l!==void 0?l:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(h=q==null?void 0:q._defineProjectionName)!==null&&h!==void 0?h:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(c=q==null?void 0:q._defineSkyboxName)!==null&&c!==void 0?c:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(u=q==null?void 0:q._defineLODReflectionAlpha)!==null&&u!==void 0?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(d=q==null?void 0:q._defineLinearSpecularReflection)!==null&&d!==void 0?d:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(f=q==null?void 0:q._vReflectionFilteringInfoName)!==null&&f!==void 0?f:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",de,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const Le=this.sheen.isConnected?(p=this.sheen.connectedPoint)===null||p===void 0?void 0:p.ownerBlock:null;Le&&(e.compilationString+=Le.getCode(q)),e._emitFunctionFromInclude("pbrBlockSheen",de,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(_=q==null?void 0:q._define3DName)!==null&&_!==void 0?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(g=q==null?void 0:q._defineSkyboxName)!==null&&g!==void 0?g:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(v=q==null?void 0:q._defineLODReflectionAlpha)!==null&&v!==void 0?v:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(E=q==null?void 0:q._defineLinearSpecularReflection)!==null&&E!==void 0?E:"LINEARSPECULARREFLECTION"}]});const Ye=this.iridescence.isConnected?(C=this.iridescence.connectedPoint)===null||C===void 0?void 0:C.ownerBlock:null;e.compilationString+=wd.GetCode(Ye),e._emitFunctionFromInclude("pbrBlockIridescence",de,{replaceStrings:[]});const He=this.clearcoat.isConnected?(S=this.clearcoat.connectedPoint)===null||S===void 0?void 0:S.ownerBlock:null,Be=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Ge=this.perturbedNormal.isConnected&&((R=((b=this.perturbedNormal.connectedPoint)===null||b===void 0?void 0:b.ownerBlock).worldTangent)===null||R===void 0?void 0:R.isConnected),Bt=this.anisotropy.isConnected&&((I=this.anisotropy.connectedPoint)===null||I===void 0?void 0:I.ownerBlock).worldTangent.isConnected;let Mt=Ge||!this.perturbedNormal.isConnected&&Bt;e.compilationString+=au.GetCode(e,He,q,ve,Be,Mt,this.worldNormal.associatedVariableName),Be&&(Mt=(N=He==null?void 0:He.worldTangent.isConnected)!==null&&N!==void 0?N:!1),e._emitFunctionFromInclude("pbrBlockClearcoat",de,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(O=q==null?void 0:q._define3DName)!==null&&O!==void 0?O:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(L=q==null?void 0:q._defineOppositeZ)!==null&&L!==void 0?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(B=q==null?void 0:q._defineProjectionName)!==null&&B!==void 0?B:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(V=q==null?void 0:q._defineSkyboxName)!==null&&V!==void 0?V:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(Z=q==null?void 0:q._defineLODReflectionAlpha)!==null&&Z!==void 0?Z:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(ue=q==null?void 0:q._defineLinearSpecularReflection)!==null&&ue!==void 0?ue:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:Mt?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",de,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(oe=q==null?void 0:q._defineSkyboxName)!==null&&oe!==void 0?oe:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(me=q==null?void 0:q._define3DName)!==null&&me!==void 0?me:"REFLECTIONMAP_3D"}]});const Vi=this.subsurface.isConnected?(le=this.subsurface.connectedPoint)===null||le===void 0?void 0:le.ownerBlock:null,at=this.subsurface.isConnected?(ce=((ae=this.subsurface.connectedPoint)===null||ae===void 0?void 0:ae.ownerBlock).refraction.connectedPoint)===null||ce===void 0?void 0:ce.ownerBlock:null;at&&(at.viewConnectionPoint=this.view,at.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Fd.GetCode(e,Vi,q,ve),e._emitFunctionFromInclude("pbrBlockSubSurface",de,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(ie=q==null?void 0:q._define3DName)!==null&&ie!==void 0?ie:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(w=q==null?void 0:q._defineOppositeZ)!==null&&w!==void 0?w:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(H=q==null?void 0:q._defineProjectionName)!==null&&H!==void 0?H:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:(X=at==null?void 0:at._define3DName)!==null&&X!==void 0?X:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:(te=at==null?void 0:at._defineLODRefractionAlpha)!==null&&te!==void 0?te:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:(Q=at==null?void 0:at._defineLinearSpecularRefraction)!==null&&Q!==void 0?Q:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:(_e=at==null?void 0:at._defineOppositeZ)!==null&&_e!==void 0?_e:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",de),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",de,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:ve+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",de,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${ve}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",de),e.compilationString+=`#endif `;const ei=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let di=Ni.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();di.indexOf(".")===-1&&(di+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",de,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ei+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:di}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",de,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",de,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",de,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:ve},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.); gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); -`}]});for(const ci of this._outputs)if(ci.hasEndpoints){const Yi=a4[ci.name];if(Yi){const[Zt,zi]=Yi;zi&&(e.compilationString+=`#if ${zi} +`}]});for(const ci of this._outputs)if(ci.hasEndpoints){const Yi=h4[ci.name];if(Yi){const[Zt,zi]=Yi;zi&&(e.compilationString+=`#if ${zi} `),e.compilationString+=`${this._declareOutput(ci,e)} = ${Zt}; `,zi&&(e.compilationString+=`#else `,e.compilationString+=`${this._declareOutput(ci,e)} = vec3(0.); @@ -8712,9 +8712,9 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `,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){var s,r;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=(s=e.lightFalloff)!==null&&s!==void 0?s: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=(r=e.realTimeFilteringQuality)!==null&&r!==void 0?r: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()}}A([ft("Direct lights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"directIntensity",void 0);A([ft("Environment lights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"environmentIntensity",void 0);A([ft("Specular highlights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"specularIntensity",void 0);A([ft("Light falloff",ut.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Ni.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Ni.LIGHTFALLOFF_GLTF},{label:"Standard",value:Ni.LIGHTFALLOFF_STANDARD}]})],cr.prototype,"lightFalloff",void 0);A([ft("Alpha Testing",ut.Boolean,"OPACITY")],cr.prototype,"useAlphaTest",void 0);A([ft("Alpha CutOff",ut.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"alphaTestCutoff",void 0);A([ft("Alpha blending",ut.Boolean,"OPACITY")],cr.prototype,"useAlphaBlending",void 0);A([ft("Radiance over alpha",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"useRadianceOverAlpha",void 0);A([ft("Specular over alpha",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"useSpecularOverAlpha",void 0);A([ft("Specular anti-aliasing",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"enableSpecularAntiAliasing",void 0);A([ft("Realtime filtering",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"realTimeFiltering",void 0);A([ft("Realtime filtering quality",ut.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],cr.prototype,"realTimeFilteringQuality",void 0);A([ft("Energy Conservation",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useEnergyConservation",void 0);A([ft("Radiance occlusion",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useRadianceOcclusion",void 0);A([ft("Horizon occlusion",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useHorizonOcclusion",void 0);A([ft("Unlit",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"unlit",void 0);A([ft("Force normal forward",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"forceNormalForward",void 0);A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:cr._OnGenerateOnlyFragmentCodeChanged}})],cr.prototype,"generateOnlyFragmentCode",void 0);A([ft("Debug mode",ut.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}]})],cr.prototype,"debugMode",void 0);A([ft("Split position",ut.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],cr.prototype,"debugLimit",void 0);A([ft("Output factor",ut.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],cr.prototype,"debugFactor",void 0);j("BABYLON.PBRMetallicRoughnessBlock",cr);class o4 extends nt{constructor(e){super(e,W.Neutral),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[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.ModBlock",o4);class l4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("row0",M.Vector4),this.registerInput("row1",M.Vector4),this.registerInput("row2",M.Vector4),this.registerInput("row3",M.Vector4),this.registerOutput("output",M.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 Bt("row0");e.value=new Dt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Bt("row1");e.value=new Dt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Bt("row2");e.value=new Dt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Bt("row3");e.value=new Dt(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}}j("BABYLON.MatrixBuilder",l4);var Ea;(function(o){o[o.Equal=0]="Equal",o[o.NotEqual=1]="NotEqual",o[o.LessThan=2]="LessThan",o[o.GreaterThan=3]="GreaterThan",o[o.LessOrEqual=4]="LessOrEqual",o[o.GreaterOrEqual=5]="GreaterOrEqual",o[o.Xor=6]="Xor",o[o.Or=7]="Or",o[o.And=8]="And"})(Ea||(Ea={}));class h4 extends nt{constructor(e){super(e,W.Neutral),this.condition=Ea.LessThan,this.registerInput("a",M.Float),this.registerInput("b",M.Float),this.registerInput("true",M.AutoDetect,!0),this.registerInput("false",M.AutoDetect,!0),this.registerOutput("output",M.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=M.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 Ea.Equal:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s}; +`,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){var s,r;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=(s=e.lightFalloff)!==null&&s!==void 0?s: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=(r=e.realTimeFilteringQuality)!==null&&r!==void 0?r: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()}}A([ft("Direct lights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"directIntensity",void 0);A([ft("Environment lights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"environmentIntensity",void 0);A([ft("Specular highlights",ut.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"specularIntensity",void 0);A([ft("Light falloff",ut.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Ni.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Ni.LIGHTFALLOFF_GLTF},{label:"Standard",value:Ni.LIGHTFALLOFF_STANDARD}]})],cr.prototype,"lightFalloff",void 0);A([ft("Alpha Testing",ut.Boolean,"OPACITY")],cr.prototype,"useAlphaTest",void 0);A([ft("Alpha CutOff",ut.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],cr.prototype,"alphaTestCutoff",void 0);A([ft("Alpha blending",ut.Boolean,"OPACITY")],cr.prototype,"useAlphaBlending",void 0);A([ft("Radiance over alpha",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"useRadianceOverAlpha",void 0);A([ft("Specular over alpha",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"useSpecularOverAlpha",void 0);A([ft("Specular anti-aliasing",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"enableSpecularAntiAliasing",void 0);A([ft("Realtime filtering",ut.Boolean,"RENDERING",{notifiers:{update:!0}})],cr.prototype,"realTimeFiltering",void 0);A([ft("Realtime filtering quality",ut.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],cr.prototype,"realTimeFilteringQuality",void 0);A([ft("Energy Conservation",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useEnergyConservation",void 0);A([ft("Radiance occlusion",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useRadianceOcclusion",void 0);A([ft("Horizon occlusion",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"useHorizonOcclusion",void 0);A([ft("Unlit",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"unlit",void 0);A([ft("Force normal forward",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],cr.prototype,"forceNormalForward",void 0);A([ft("Generate only fragment code",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:cr._OnGenerateOnlyFragmentCodeChanged}})],cr.prototype,"generateOnlyFragmentCode",void 0);A([ft("Debug mode",ut.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}]})],cr.prototype,"debugMode",void 0);A([ft("Split position",ut.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],cr.prototype,"debugLimit",void 0);A([ft("Output factor",ut.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],cr.prototype,"debugFactor",void 0);j("BABYLON.PBRMetallicRoughnessBlock",cr);class c4 extends nt{constructor(e){super(e,W.Neutral),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[1].acceptedConnectionPointTypes.push(M.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}}j("BABYLON.ModBlock",c4);class u4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("row0",M.Vector4),this.registerInput("row1",M.Vector4),this.registerInput("row2",M.Vector4),this.registerInput("row3",M.Vector4),this.registerOutput("output",M.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 Vt("row0");e.value=new Dt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Vt("row1");e.value=new Dt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Vt("row2");e.value=new Dt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Vt("row3");e.value=new Dt(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}}j("BABYLON.MatrixBuilder",u4);var Ea;(function(o){o[o.Equal=0]="Equal",o[o.NotEqual=1]="NotEqual",o[o.LessThan=2]="LessThan",o[o.GreaterThan=3]="GreaterThan",o[o.LessOrEqual=4]="LessOrEqual",o[o.GreaterOrEqual=5]="GreaterOrEqual",o[o.Xor=6]="Xor",o[o.Or=7]="Or",o[o.And=8]="And"})(Ea||(Ea={}));class d4 extends nt{constructor(e){super(e,W.Neutral),this.condition=Ea.LessThan,this.registerInput("a",M.Float),this.registerInput("b",M.Float),this.registerInput("true",M.AutoDetect,!0),this.registerInput("false",M.AutoDetect,!0),this.registerOutput("output",M.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=M.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 Ea.Equal:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s}; `;break}case Ea.NotEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${s}; `;break}case Ea.LessThan:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${s}; `;break}case Ea.LessOrEqual:{e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${s}; @@ -8724,7 +8724,7 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `;break}case Ea.Or:{e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${s}; `;break}case Ea.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.${Ea[this.condition]}; -`}}j("BABYLON.ConditionalBlock",h4);class Py extends nt{constructor(e){super(e,W.Neutral),this.octaves=6,this.registerInput("seed",M.AutoDetect),this.registerInput("chaos",M.AutoDetect,!0),this.registerInput("offsetX",M.Float,!0),this.registerInput("offsetY",M.Float,!0),this.registerInput("offsetZ",M.Float,!0),this.registerOutput("output",M.Float),this._inputs[0].acceptedConnectionPointTypes.push(M.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(M.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 t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const s=` +`}}j("BABYLON.ConditionalBlock",d4);class Dy extends nt{constructor(e){super(e,W.Neutral),this.octaves=6,this.registerInput("seed",M.AutoDetect),this.registerInput("chaos",M.AutoDetect,!0),this.registerInput("offsetX",M.Float,!0),this.registerInput("offsetY",M.Float,!0),this.registerInput("offsetZ",M.Float,!0),this.registerOutput("output",M.Float),this._inputs[0].acceptedConnectionPointTypes.push(M.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(M.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 t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const s=` float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } @@ -8791,7 +8791,7 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `),this.offsetZ.isConnected&&l==="vec3"&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; `);let h="";return this.chaos.isConnected?h=this.chaos.associatedVariableName:h=((i=this.seed.connectedPoint)===null||i===void 0?void 0:i.type)===M.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${h}); `,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}}A([ft("Octaves",ut.Int)],Py.prototype,"octaves",void 0);j("BABYLON.CloudBlock",Py);class c4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("seed",M.Vector2),this.registerInput("offset",M.Float),this.registerInput("density",M.Float),this.registerOutput("output",M.Float),this.registerOutput("cells",M.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){ +`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}A([ft("Octaves",ut.Int)],Dy.prototype,"octaves",void 0);j("BABYLON.CloudBlock",Dy);class f4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("seed",M.Vector2),this.registerInput("offset",M.Float),this.registerInput("density",M.Float),this.registerOutput("output",M.Float),this.registerOutput("cells",M.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); @@ -8823,8 +8823,8 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `,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}}j("BABYLON.VoronoiNoiseBlock",c4);class u4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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!==W.VertexAndFragment)return t.target;if(e.connectedPoint.target!==W.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}}j("BABYLON.ElbowBlock",u4);class nT extends nt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return!((e=this.sourceZ)===null||e===void 0)&&e.isConnected?((t=this.sourceY.connectedPoint)===null||t===void 0?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,t;return(t=(e=this._getImageSourceBlock(this.sourceY))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get samplerZName(){var e,t;return(t=(e=this._getImageSourceBlock(this.sourceZ))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,W.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",M.AutoDetect,!1),this.registerInput("normal",M.AutoDetect,!1),this.registerInput("sharpness",M.Float,!0),this.registerInput("source",M.Object,!0,W.VertexAndFragment,new Ss("source",this,as.Input,bo,"ImageSourceBlock")),this.registerInput("sourceY",M.Object,!0,W.VertexAndFragment,new Ss("sourceY",this,as.Input,bo,"ImageSourceBlock")),t||this.registerInput("sourceZ",M.Object,!0,W.VertexAndFragment,new Ss("sourceZ",this,as.Input,bo,"ImageSourceBlock")),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this.registerOutput("level",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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){var t,i;const s=this.samplerName,r=(t=this.samplerYName)!==null&&t!==void 0?t:s,n=(i=this.samplerZName)!==null&&i!==void 0?i:s,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",l=e._getFreeVariableName("x"),h=e._getFreeVariableName("y"),c=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),d=e._getFreeVariableName("n"),f=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` +`),this}}j("BABYLON.VoronoiNoiseBlock",f4);class p4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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!==W.VertexAndFragment)return t.target;if(e.connectedPoint.target!==W.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}}j("BABYLON.ElbowBlock",p4);class oT extends nt{get texture(){var e;return this.source.isConnected?((e=this.source.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=(t=e==null?void 0:e.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,s=>s.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?((e=this.sourceY.connectedPoint)===null||e===void 0?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return!((e=this.sourceZ)===null||e===void 0)&&e.isConnected?((t=this.sourceY.connectedPoint)===null||t===void 0?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,t;return(t=(e=this._getImageSourceBlock(this.sourceY))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get samplerZName(){var e,t;return(t=(e=this._getImageSourceBlock(this.sourceZ))===null||e===void 0?void 0:e.samplerName)!==null&&t!==void 0?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const i=(t=this.texture.getScene())!==null&&t!==void 0?t:ht.LastCreatedScene;i==null||i.markAllMaterialsAsDirty(1,s=>s.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,W.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",M.AutoDetect,!1),this.registerInput("normal",M.AutoDetect,!1),this.registerInput("sharpness",M.Float,!0),this.registerInput("source",M.Object,!0,W.VertexAndFragment,new Cs("source",this,as.Input,bo,"ImageSourceBlock")),this.registerInput("sourceY",M.Object,!0,W.VertexAndFragment,new Cs("sourceY",this,as.Input,bo,"ImageSourceBlock")),t||this.registerInput("sourceZ",M.Object,!0,W.VertexAndFragment,new Cs("sourceZ",this,as.Input,bo,"ImageSourceBlock")),this.registerOutput("rgba",M.Color4,W.Neutral),this.registerOutput("rgb",M.Color3,W.Neutral),this.registerOutput("r",M.Float,W.Neutral),this.registerOutput("g",M.Float,W.Neutral),this.registerOutput("b",M.Float,W.Neutral),this.registerOutput("a",M.Float,W.Neutral),this.registerOutput("level",M.Float,W.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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){var t,i;const s=this.samplerName,r=(t=this.samplerYName)!==null&&t!==void 0?t:s,n=(i=this.samplerZName)!==null&&i!==void 0?i:s,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",l=e._getFreeVariableName("x"),h=e._getFreeVariableName("y"),c=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),d=e._getFreeVariableName("n"),f=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` vec3 ${d} = ${this.normal.associatedVariableName}.xyz; vec2 ${f} = ${this.position.associatedVariableName}.yz; @@ -8874,7 +8874,7 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); `,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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}A([ft("Project as cube",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],nT.prototype,"projectAsCube",void 0);j("BABYLON.TriPlanarBlock",nT);class d4 extends nT{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,s=(t=this.samplerYName)!==null&&t!==void 0?t:this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),l=e._getFreeVariableName("n"),h=e._getFreeVariableName("ma"),c=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),d=e._getFreeVariableName("x"),f=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` +`),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&&!ys.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=ee.Parse(e.texture,t,i))}}A([ft("Project as cube",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],oT.prototype,"projectAsCube",void 0);j("BABYLON.TriPlanarBlock",oT);class _4 extends oT{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,s=(t=this.samplerYName)!==null&&t!==void 0?t:this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),l=e._getFreeVariableName("n"),h=e._getFreeVariableName("ma"),c=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),d=e._getFreeVariableName("x"),f=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` // grab coord derivatives for texturing vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); @@ -8907,29 +8907,29 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); ${p} = pow( ${p}, vec2(${r}/8.0) ); // blend and return vec4 ${this._tempTextureRead} = (${d}*${p}.x + ${f}*${p}.y) / (${p}.x + ${p}.y); - `}}j("BABYLON.BiPlanarBlock",d4);class f4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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}}j("BABYLON.MatrixDeterminantBlock",f4);class p4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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}}j("BABYLON.MatrixTransposeBlock",p4);var Ki;(function(o){o[o.None=0]="None",o[o.Normal=1]="Normal",o[o.Tangent=2]="Tangent",o[o.VertexColor=3]="VertexColor",o[o.UV1=4]="UV1",o[o.UV2=5]="UV2",o[o.UV3=6]="UV3",o[o.UV4=7]="UV4",o[o.UV5=8]="UV5",o[o.UV6=9]="UV6"})(Ki||(Ki={}));class My extends nt{constructor(e){super(e,W.Neutral),this.attributeType=Ki.None,this.registerInput("input",M.AutoDetect),this.registerInput("fallback",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var i;if(this.attributeType)return;const s=t.ownerBlock;if(s instanceof Bt&&s.isAttribute)switch(s.name){case"color":this.attributeType=Ki.VertexColor;break;case"normal":this.attributeType=Ki.Normal;break;case"tangent":this.attributeType=Ki.Tangent;break;case"uv":this.attributeType=Ki.UV1;break;case"uv2":this.attributeType=Ki.UV2;break;case"uv3":this.attributeType=Ki.UV3;break;case"uv4":this.attributeType=Ki.UV4;break;case"uv5":this.attributeType=Ki.UV5;break;case"uv6":this.attributeType=Ki.UV6;break}else if(s instanceof by)switch((i=this.input.connectedPoint)===null||i===void 0?void 0:i.name){case"normalOutput":this.attributeType=Ki.Normal;break;case"tangentOutput":this.attributeType=Ki.Tangent;break;case"uvOutput":this.attributeType=Ki.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 Ki.VertexColor:t="VERTEXCOLOR_NME";break;case Ki.Normal:t="NORMAL";break;case Ki.Tangent:t="TANGENT";break;case Ki.UV1:t="UV1";break;case Ki.UV2:t="UV2";break;case Ki.UV3:t="UV3";break;case Ki.UV4:t="UV4";break;case Ki.UV5:t="UV5";break;case Ki.UV6:t="UV6";break}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} + `}}j("BABYLON.BiPlanarBlock",_4);class m4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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}}j("BABYLON.MatrixDeterminantBlock",m4);class g4 extends nt{constructor(e){super(e,W.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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}}j("BABYLON.MatrixTransposeBlock",g4);var Ki;(function(o){o[o.None=0]="None",o[o.Normal=1]="Normal",o[o.Tangent=2]="Tangent",o[o.VertexColor=3]="VertexColor",o[o.UV1=4]="UV1",o[o.UV2=5]="UV2",o[o.UV3=6]="UV3",o[o.UV4=7]="UV4",o[o.UV5=8]="UV5",o[o.UV6=9]="UV6"})(Ki||(Ki={}));class Oy extends nt{constructor(e){super(e,W.Neutral),this.attributeType=Ki.None,this.registerInput("input",M.AutoDetect),this.registerInput("fallback",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var i;if(this.attributeType)return;const s=t.ownerBlock;if(s instanceof Vt&&s.isAttribute)switch(s.name){case"color":this.attributeType=Ki.VertexColor;break;case"normal":this.attributeType=Ki.Normal;break;case"tangent":this.attributeType=Ki.Tangent;break;case"uv":this.attributeType=Ki.UV1;break;case"uv2":this.attributeType=Ki.UV2;break;case"uv3":this.attributeType=Ki.UV3;break;case"uv4":this.attributeType=Ki.UV4;break;case"uv5":this.attributeType=Ki.UV5;break;case"uv6":this.attributeType=Ki.UV6;break}else if(s instanceof Ay)switch((i=this.input.connectedPoint)===null||i===void 0?void 0:i.name){case"normalOutput":this.attributeType=Ki.Normal;break;case"tangentOutput":this.attributeType=Ki.Tangent;break;case"uvOutput":this.attributeType=Ki.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 Ki.VertexColor:t="VERTEXCOLOR_NME";break;case Ki.Normal:t="NORMAL";break;case Ki.Tangent:t="TANGENT";break;case Ki.UV1:t="UV1";break;case Ki.UV2:t="UV2";break;case Ki.UV3:t="UV3";break;case Ki.UV4:t="UV4";break;case Ki.UV5:t="UV5";break;case Ki.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){var s;super._deserialize(e,t,i),this.attributeType=(s=e.attributeType)!==null&&s!==void 0?s:Ki.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType}; -`,e}}A([ft("Attribute lookup",ut.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:Ki.None},{label:"Normal",value:Ki.Normal},{label:"Tangent",value:Ki.Tangent},{label:"Vertex Color",value:Ki.VertexColor},{label:"UV1",value:Ki.UV1},{label:"UV2",value:Ki.UV2},{label:"UV3",value:Ki.UV3},{label:"UV4",value:Ki.UV4},{label:"UV5",value:Ki.UV5},{label:"UV6",value:Ki.UV6}]})],My.prototype,"attributeType",void 0);j("BABYLON.MeshAttributeExistsBlock",My);var ss;(function(o){o[o.EaseInSine=0]="EaseInSine",o[o.EaseOutSine=1]="EaseOutSine",o[o.EaseInOutSine=2]="EaseInOutSine",o[o.EaseInQuad=3]="EaseInQuad",o[o.EaseOutQuad=4]="EaseOutQuad",o[o.EaseInOutQuad=5]="EaseInOutQuad",o[o.EaseInCubic=6]="EaseInCubic",o[o.EaseOutCubic=7]="EaseOutCubic",o[o.EaseInOutCubic=8]="EaseInOutCubic",o[o.EaseInQuart=9]="EaseInQuart",o[o.EaseOutQuart=10]="EaseOutQuart",o[o.EaseInOutQuart=11]="EaseInOutQuart",o[o.EaseInQuint=12]="EaseInQuint",o[o.EaseOutQuint=13]="EaseOutQuint",o[o.EaseInOutQuint=14]="EaseInOutQuint",o[o.EaseInExpo=15]="EaseInExpo",o[o.EaseOutExpo=16]="EaseOutExpo",o[o.EaseInOutExpo=17]="EaseInOutExpo",o[o.EaseInCirc=18]="EaseInCirc",o[o.EaseOutCirc=19]="EaseOutCirc",o[o.EaseInOutCirc=20]="EaseInOutCirc",o[o.EaseInBack=21]="EaseInBack",o[o.EaseOutBack=22]="EaseOutBack",o[o.EaseInOutBack=23]="EaseInOutBack",o[o.EaseInElastic=24]="EaseInElastic",o[o.EaseOutElastic=25]="EaseOutElastic",o[o.EaseInOutElastic=26]="EaseInOutElastic"})(ss||(ss={}));class _4 extends nt{constructor(e){super(e,W.Neutral),this.type=ss.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.Object),this._inputs[0].excludedConnectionPointTypes.push(M.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=` +`,e}}A([ft("Attribute lookup",ut.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:Ki.None},{label:"Normal",value:Ki.Normal},{label:"Tangent",value:Ki.Tangent},{label:"Vertex Color",value:Ki.VertexColor},{label:"UV1",value:Ki.UV1},{label:"UV2",value:Ki.UV2},{label:"UV3",value:Ki.UV3},{label:"UV4",value:Ki.UV4},{label:"UV5",value:Ki.UV5},{label:"UV6",value:Ki.UV6}]})],Oy.prototype,"attributeType",void 0);j("BABYLON.MeshAttributeExistsBlock",Oy);var ss;(function(o){o[o.EaseInSine=0]="EaseInSine",o[o.EaseOutSine=1]="EaseOutSine",o[o.EaseInOutSine=2]="EaseInOutSine",o[o.EaseInQuad=3]="EaseInQuad",o[o.EaseOutQuad=4]="EaseOutQuad",o[o.EaseInOutQuad=5]="EaseInOutQuad",o[o.EaseInCubic=6]="EaseInCubic",o[o.EaseOutCubic=7]="EaseOutCubic",o[o.EaseInOutCubic=8]="EaseInOutCubic",o[o.EaseInQuart=9]="EaseInQuart",o[o.EaseOutQuart=10]="EaseOutQuart",o[o.EaseInOutQuart=11]="EaseInOutQuart",o[o.EaseInQuint=12]="EaseInQuint",o[o.EaseOutQuint=13]="EaseOutQuint",o[o.EaseInOutQuint=14]="EaseInOutQuint",o[o.EaseInExpo=15]="EaseInExpo",o[o.EaseOutExpo=16]="EaseOutExpo",o[o.EaseInOutExpo=17]="EaseInOutExpo",o[o.EaseInCirc=18]="EaseInCirc",o[o.EaseOutCirc=19]="EaseOutCirc",o[o.EaseInOutCirc=20]="EaseInOutCirc",o[o.EaseInBack=21]="EaseInBack",o[o.EaseOutBack=22]="EaseOutBack",o[o.EaseInOutBack=23]="EaseInOutBack",o[o.EaseInElastic=24]="EaseInElastic",o[o.EaseOutElastic=25]="EaseOutElastic",o[o.EaseInOutElastic=26]="EaseInOutElastic"})(ss||(ss={}));class v4 extends nt{constructor(e){super(e,W.Neutral),this.type=ss.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.Object),this._inputs[0].excludedConnectionPointTypes.push(M.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 M.Float:r="float";break;case M.Vector2:r="vec2";break;case M.Vector3:case M.Color3:r="vec3";break;case M.Vector4:case M.Color4:r="vec4";break}switch(s=ss[this.type]+"_"+r,this.type){case ss.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case ss.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case ss.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case ss.EaseInQuad:i="return v * v";break;case ss.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case ss.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 ss.EaseInCubic:i="return v * v * v";break;case ss.EaseOutCubic:{const n="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(n,r);break}case ss.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 ss.EaseInQuart:i="return v * v * v * v";break;case ss.EaseOutQuart:{const n="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(n,r);break}case ss.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 ss.EaseInQuint:i="return v * v * v * v * v";break;case ss.EaseOutQuint:{const n="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(n,r);break}case ss.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 ss.EaseInExpo:{const n="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(n,r);break}case ss.EaseOutExpo:{const n="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(n,r);break}case ss.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 ss.EaseInCirc:{const n="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(n,r);break}case ss.EaseOutCirc:{const n="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(n,r);break}case ss.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 ss.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case ss.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 ss.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 ss.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 ss.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 ss.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.${ss[this.type]}; -`}}j("BABYLON.CurveBlock",_4);class m4 extends Wn{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class hp extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new m4,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)||!we.DecalMapEnabled||!t.texturesEnabled?!0:r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;!this._isEnabled||!(s!=null&&s.texture)||!we.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,Me.PrepareDefinesForMergedUV(s.texture,e,"DECAL"))}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!this._isEnabled||!(r!=null&&r.texture)||!we.DecalMapEnabled||!t.texturesEnabled)return;const n=this._material.isFrozen,a=r.texture;(!e.useUbo||!n||!e.isSync)&&(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),Me.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],hp.prototype,"isEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],hp.prototype,"smoothAlpha",void 0);j("BABYLON.DecalMapConfiguration",hp);var hC;(function(o){o[o.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",o[o.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",o[o.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(hC||(hC={}));var Ra;(function(o){o[o.COLOR_MODE_SET=0]="COLOR_MODE_SET",o[o.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",o[o.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(Ra||(Ra={}));var yl;(function(o){o[o.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",o[o.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(yl||(yl={}));class nn{}nn.DEFAULT_COLOR=Te.White();nn.DEFAULT_WIDTH_ATTENUATED=1;nn.DEFAULT_WIDTH=.1;class Li{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 T){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof T){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 Li._SearchInPoints(e,t,s)||r.push([e,t]),Li._SearchInPoints(t,i,s)||r.push([t,i]),Li._SearchInPoints(i,e,s)||r.push([i,e]),r.length===0?null:r}static _SearchInPoints(e,t,i){var s,r,n;for(const a of i)for(let l=0;l{const n=s.getVerticesData(P.PositionKind),a=s.getIndices();if(n&&a)for(let l=0,h=0;l[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=Li.ToVector3Array(e):t=e;const i=K.Vector3[0];let s=0;for(let r=0;r{r.length>t?Li.SegmentizeSegmentByCount(r.point1,r.point2,Math.ceil(r.length/t)).forEach(a=>{s.push(a)}):(s.push(r.point1),s.push(r.point2))}),s}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?Li.ToVector3Array(e):e,s=Li.GetLineLength(i)/t;return Li.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;is.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,a=0;const l=e.length;for(let c=0;c[r.x,r.y,r.z])}static GetArrowCap(e,t,i,s,r,n=0,a=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,a]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const a=[],l=oy(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);a.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);a.push(u)}}return a}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;i{Li.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?` +`}}j("BABYLON.CurveBlock",v4);class x4 extends Wn{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class hp extends ca{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new x4,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)||!we.DecalMapEnabled||!t.texturesEnabled?!0:r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;!this._isEnabled||!(s!=null&&s.texture)||!we.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,Me.PrepareDefinesForMergedUV(s.texture,e,"DECAL"))}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!this._isEnabled||!(r!=null&&r.texture)||!we.DecalMapEnabled||!t.texturesEnabled)return;const n=this._material.isFrozen,a=r.texture;(!e.useUbo||!n||!e.isSync)&&(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),Me.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],hp.prototype,"isEnabled",void 0);A([D(),Ce("_markAllSubMeshesAsTexturesDirty")],hp.prototype,"smoothAlpha",void 0);j("BABYLON.DecalMapConfiguration",hp);var uC;(function(o){o[o.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",o[o.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",o[o.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(uC||(uC={}));var Ra;(function(o){o[o.COLOR_MODE_SET=0]="COLOR_MODE_SET",o[o.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",o[o.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(Ra||(Ra={}));var yl;(function(o){o[o.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",o[o.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(yl||(yl={}));class nn{}nn.DEFAULT_COLOR=Te.White();nn.DEFAULT_WIDTH_ATTENUATED=1;nn.DEFAULT_WIDTH=.1;class Li{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 T){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof T){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 Li._SearchInPoints(e,t,s)||r.push([e,t]),Li._SearchInPoints(t,i,s)||r.push([t,i]),Li._SearchInPoints(i,e,s)||r.push([i,e]),r.length===0?null:r}static _SearchInPoints(e,t,i){var s,r,n;for(const a of i)for(let l=0;l{const n=s.getVerticesData(P.PositionKind),a=s.getIndices();if(n&&a)for(let l=0,h=0;l[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=Li.ToVector3Array(e):t=e;const i=K.Vector3[0];let s=0;for(let r=0;r{r.length>t?Li.SegmentizeSegmentByCount(r.point1,r.point2,Math.ceil(r.length/t)).forEach(a=>{s.push(a)}):(s.push(r.point1),s.push(r.point2))}),s}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?Li.ToVector3Array(e):e,s=Li.GetLineLength(i)/t;return Li.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;is.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,a=0;const l=e.length;for(let c=0;c[r.x,r.y,r.z])}static GetArrowCap(e,t,i,s,r,n=0,a=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,a]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const a=[],l=hy(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);a.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);a.push(u)}}return a}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;i{Li.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){var t;if(this._cameraFacing){const r=this._scene.activeCamera;if(r){const a=r.getProjectionMatrix();e.updateMatrix("grl_projection",a)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const n=K.Vector4[0];n.x=this._aspect,n.y=this._resolution.x,n.z=this._resolution.y,n.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",n)}const i=K.Vector4[0];i.x=Li.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);const s=K.Vector4[1];s.x=this.colorMode,s.y=this.visibility,s.z=this.colorsTexture?this.colorsTexture.getSize().width:0,s.w=Li.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",s),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",(t=this.colorsTexture)!==null&&t!==void 0?t:nn.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===yl.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Qh.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if(e==="vertex"){const t={CUSTOM_VERTEX_DEFINITIONS:` + `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){const r=this._scene.activeCamera;if(r){const a=r.getProjectionMatrix();e.updateMatrix("grl_projection",a)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const n=K.Vector4[0];n.x=this._aspect,n.y=this._resolution.x,n.z=this._resolution.y,n.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",n)}const i=K.Vector4[0];i.x=Li.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);const s=K.Vector4[1];s.x=this.colorMode,s.y=this.visibility,s.z=this.colorsTexture?this.colorsTexture.getSize().width:0,s.w=Li.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",s),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",(t=this.colorsTexture)!==null&&t!==void 0?t:nn.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===yl.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Zh.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; @@ -9060,11 +9060,11 @@ gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); } #endif - `}:null}dispose(){var e;(e=this.colorsTexture)===null||e===void 0||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var s,r,n,a;const l=(r=(s=this._colors)===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0;if(this._colors=e,e===null||e.length===0){(n=this.colorsTexture)===null||n===void 0||n.dispose();return}if(!(t&&!i))if(this.colorsTexture&&l===e.length&&!i){const h=Li.Color3toRGBAUint8(e);this.colorsTexture.update(h)}else(a=this.colorsTexture)===null||a===void 0||a.dispose(),this.colorsTexture=Li.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 s;super.parse(e,t,i);const r=e.greasedLineMaterialOptions;(s=this.colorsTexture)===null||s===void 0||s.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=Li.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Li.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;const i=e;(t=i.colorsTexture)===null||t===void 0||t.dispose(),this._colors&&(i.colorsTexture=Li.CreateColorsTexture(`${i._material.name}-colors-texture`,this._colors,i.colorsSampling,this._scene)),i.setColor(this.color,!0),i.colorsDistributionType=this.colorsDistributionType,i.colorsSampling=this.colorsSampling,i.colorMode=this.colorMode,i.useColors=this.useColors,i.visibility=this.visibility,i.useDash=this.useDash,i.dashCount=this.dashCount,i.dashRatio=this.dashRatio,i.dashOffset=this.dashOffset,i.width=this.width,i.sizeAttenuation=this.sizeAttenuation,i.resolution=this.resolution,i.markAllDefinesAsDirty()}}Qh.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";j(`BABYLON.${Qh.GREASED_LINE_MATERIAL_NAME}`,Qh);const v4="greasedLinePixelShader",x4=`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;} + `}:null}dispose(){var e;(e=this.colorsTexture)===null||e===void 0||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var s,r,n,a;const l=(r=(s=this._colors)===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0;if(this._colors=e,e===null||e.length===0){(n=this.colorsTexture)===null||n===void 0||n.dispose();return}if(!(t&&!i))if(this.colorsTexture&&l===e.length&&!i){const h=Li.Color3toRGBAUint8(e);this.colorsTexture.update(h)}else(a=this.colorsTexture)===null||a===void 0||a.dispose(),this.colorsTexture=Li.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 s;super.parse(e,t,i);const r=e.greasedLineMaterialOptions;(s=this.colorsTexture)===null||s===void 0||s.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=Li.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Li.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;const i=e;(t=i.colorsTexture)===null||t===void 0||t.dispose(),this._colors&&(i.colorsTexture=Li.CreateColorsTexture(`${i._material.name}-colors-texture`,this._colors,i.colorsSampling,this._scene)),i.setColor(this.color,!0),i.colorsDistributionType=this.colorsDistributionType,i.colorsSampling=this.colorsSampling,i.colorMode=this.colorMode,i.useColors=this.useColors,i.visibility=this.visibility,i.useDash=this.useDash,i.dashCount=this.dashCount,i.dashRatio=this.dashRatio,i.dashOffset=this.dashOffset,i.width=this.width,i.sizeAttenuation=this.sizeAttenuation,i.resolution=this.resolution,i.markAllDefinesAsDirty()}}Zh.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";j(`BABYLON.${Zh.GREASED_LINE_MATERIAL_NAME}`,Zh);const E4="greasedLinePixelShader",S4=`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;}}} -`;ne.ShadersStore[v4]=x4;const T4="greasedLineVertexShader",E4=`precision highp float; +`;ne.ShadersStore[E4]=S4;const C4="greasedLineVertexShader",b4=`precision highp float; #include 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 @@ -9089,12 +9089,12 @@ grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; #endif } -`;ne.ShadersStore[T4]=E4;class S4 extends wa{constructor(e,t,i){var s,r,n,a,l,h,c,u,d,f,p,_,g,v;const E=[`COLOR_DISTRIBUTION_TYPE_LINE ${yl.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${yl.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${Ra.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${Ra.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${Ra.COLOR_MODE_MULTIPLY}.`],C=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&E.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(E.push("GREASED_LINE_CAMERA_FACING"),C.push("grl_previousAndSide","grl_nextAndCounters")):(C.push("grl_slopes"),C.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:C,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:E}),this._color=Te.White(),this._colorsDistributionType=yl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:nn.DEFAULT_COLOR};const S=t.getEngine();this.visibility=(s=i.visibility)!==null&&s!==void 0?s:1,this.useDash=(r=i.useDash)!==null&&r!==void 0?r:!1,this.dashRatio=(n=i.dashRatio)!==null&&n!==void 0?n:.5,this.dashOffset=(a=i.dashOffset)!==null&&a!==void 0?a:0,this.dashCount=(l=i.dashCount)!==null&&l!==void 0?l:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?nn.DEFAULT_WIDTH_ATTENUATED:nn.DEFAULT_WIDTH,this.sizeAttenuation=(h=i.sizeAttenuation)!==null&&h!==void 0?h:!1,this.color=(c=i.color)!==null&&c!==void 0?c:Te.White(),this.useColors=(u=i.useColors)!==null&&u!==void 0?u:!1,this.colorsDistributionType=(d=i.colorDistributionType)!==null&&d!==void 0?d:yl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=(f=i.colorsSampling)!==null&&f!==void 0?f:Ws.NEAREST_NEAREST,this.colorMode=(p=i.colorMode)!==null&&p!==void 0?p:Ra.COLOR_MODE_SET,this._colors=(_=i.colors)!==null&&_!==void 0?_:null,this._cameraFacing=(g=i.cameraFacing)!==null&&g!==void 0?g:!0,this.resolution=(v=i.resolution)!==null&&v!==void 0?v:new Re(S.getRenderWidth(),S.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Li.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),S.onDisposeObservable.add(()=>{Li.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)===null||e===void 0||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new Re(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 s,r,n,a;const l=(r=(s=this._colors)===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0;if(this._colors=e,e===null||e.length===0){(n=this._colorsTexture)===null||n===void 0||n.dispose();return}if(!(t&&!i))if(this._colorsTexture&&l===e.length&&!i){const h=Li.Color3toRGBAUint8(e);this._colorsTexture.update(h)}else(a=this._colorsTexture)===null||a===void 0||a.dispose(),this.colorsTexture=Li.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}get colorsTexture(){var e;return(e=this._colorsTexture)!==null&&e!==void 0?e: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",Li.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",Li.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",Li.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??nn.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 s,r;const n=e.greasedLineMaterialOptions;(s=this._colorsTexture)===null||s===void 0||s.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=Li.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Li.PrepareEmptyColorsTexture(t),this._cameraFacing=(r=n.cameraFacing)!==null&&r!==void 0?r:!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const C4=`#if defined(DBG_ENABLED) +`;ne.ShadersStore[C4]=b4;class y4 extends wa{constructor(e,t,i){var s,r,n,a,l,h,c,u,d,f,p,_,g,v;const E=[`COLOR_DISTRIBUTION_TYPE_LINE ${yl.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${yl.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${Ra.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${Ra.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${Ra.COLOR_MODE_MULTIPLY}.`],C=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&E.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(E.push("GREASED_LINE_CAMERA_FACING"),C.push("grl_previousAndSide","grl_nextAndCounters")):(C.push("grl_slopes"),C.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:C,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:E}),this._color=Te.White(),this._colorsDistributionType=yl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:nn.DEFAULT_COLOR};const S=t.getEngine();this.visibility=(s=i.visibility)!==null&&s!==void 0?s:1,this.useDash=(r=i.useDash)!==null&&r!==void 0?r:!1,this.dashRatio=(n=i.dashRatio)!==null&&n!==void 0?n:.5,this.dashOffset=(a=i.dashOffset)!==null&&a!==void 0?a:0,this.dashCount=(l=i.dashCount)!==null&&l!==void 0?l:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?nn.DEFAULT_WIDTH_ATTENUATED:nn.DEFAULT_WIDTH,this.sizeAttenuation=(h=i.sizeAttenuation)!==null&&h!==void 0?h:!1,this.color=(c=i.color)!==null&&c!==void 0?c:Te.White(),this.useColors=(u=i.useColors)!==null&&u!==void 0?u:!1,this.colorsDistributionType=(d=i.colorDistributionType)!==null&&d!==void 0?d:yl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=(f=i.colorsSampling)!==null&&f!==void 0?f:Ws.NEAREST_NEAREST,this.colorMode=(p=i.colorMode)!==null&&p!==void 0?p:Ra.COLOR_MODE_SET,this._colors=(_=i.colors)!==null&&_!==void 0?_:null,this._cameraFacing=(g=i.cameraFacing)!==null&&g!==void 0?g:!0,this.resolution=(v=i.resolution)!==null&&v!==void 0?v:new Re(S.getRenderWidth(),S.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Li.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),S.onDisposeObservable.add(()=>{Li.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)===null||e===void 0||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new Re(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 s,r,n,a;const l=(r=(s=this._colors)===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0;if(this._colors=e,e===null||e.length===0){(n=this._colorsTexture)===null||n===void 0||n.dispose();return}if(!(t&&!i))if(this._colorsTexture&&l===e.length&&!i){const h=Li.Color3toRGBAUint8(e);this._colorsTexture.update(h)}else(a=this._colorsTexture)===null||a===void 0||a.dispose(),this.colorsTexture=Li.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}get colorsTexture(){var e;return(e=this._colorsTexture)!==null&&e!==void 0?e: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",Li.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",Li.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",Li.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??nn.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 s,r;const n=e.greasedLineMaterialOptions;(s=this._colorsTexture)===null||s===void 0||s.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=Li.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Li.PrepareEmptyColorsTexture(t),this._cameraFacing=(r=n.cameraFacing)!==null&&r!==void 0?r:!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const A4=`#if defined(DBG_ENABLED) attribute float dbg_initialPass; varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; -#endif`,b4=`#if defined(DBG_ENABLED) +#endif`,R4=`#if defined(DBG_ENABLED) float dbg_vertexIndex = mod(float(gl_VertexID), 3.); if (dbg_vertexIndex == 0.0) { dbg_vBarycentric = vec3(1.,0.,0.); @@ -9108,7 +9108,7 @@ else { dbg_vVertexWorldPos = vPositionW; dbg_vPass = dbg_initialPass; -#endif`,y4=`#if defined(DBG_ENABLED) +#endif`,I4=`#if defined(DBG_ENABLED) uniform vec3 dbg_shadedDiffuseColor; uniform vec4 dbg_shadedSpecularColorPower; uniform vec3 dbg_thicknessRadiusScale; @@ -9127,7 +9127,7 @@ uniform vec3 dbg_thicknessRadiusScale; #elif DBG_MODE == 7 uniform vec3 dbg_materialColor; #endif -#endif`,A4=`#if defined(DBG_ENABLED) +#endif`,P4=`#if defined(DBG_ENABLED) varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; @@ -9171,7 +9171,7 @@ flat varying float dbg_vPass; return (f.x * f.y) > 0. ? 1. : 0.; } #endif -#endif`,R4=`#if defined(DBG_ENABLED) +#endif`,M4=`#if defined(DBG_ENABLED) vec3 dbg_color = vec3(1.); #if DBG_MODE == 1 dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); @@ -9201,7 +9201,7 @@ vec3 dbg_color = vec3(1.); gl_FragColor = vec4(dbg_color, 1.); #endif #endif -#endif`,Dy=[new Te(.98,.26,.38),new Te(.47,.75,.3),new Te(0,.26,.77),new Te(.97,.6,.76),new Te(.19,.63,.78),new Te(.98,.8,.6),new Te(.65,.43,.15),new Te(.15,.47,.22),new Te(.67,.71,.86),new Te(.09,.46,.56),new Te(.8,.98,.02),new Te(.39,.29,.13),new Te(.53,.63,.06),new Te(.95,.96,.41),new Te(1,.72,.94),new Te(.63,.08,.31),new Te(.66,.96,.95),new Te(.22,.14,.19),new Te(.14,.65,.59),new Te(.93,1,.68),new Te(.93,.14,.44),new Te(.47,.86,.67),new Te(.85,.07,.78),new Te(.53,.64,.98),new Te(.43,.37,.56),new Te(.71,.65,.25),new Te(.66,.19,.01),new Te(.94,.53,.12),new Te(.41,.44,.44),new Te(.24,.71,.96),new Te(.57,.28,.56),new Te(.44,.98,.42)];var Yc;(function(o){o[o.NONE=0]="NONE",o[o.TRIANGLES=1]="TRIANGLES",o[o.VERTICES=2]="VERTICES",o[o.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",o[o.UV0=4]="UV0",o[o.UV1=5]="UV1",o[o.VERTEXCOLORS=6]="VERTEXCOLORS",o[o.MATERIALIDS=7]="MATERIALIDS"})(Yc||(Yc={}));class I4 extends Wn{constructor(){super(...arguments),this.DBG_MODE=Yc.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Er extends ca{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,s,r,n,a,l,h,c,u,d,f,p,_;const g=new I4;g.DBG_MODE=(i=t.mode)!==null&&i!==void 0?i:g.DBG_MODE,g.DBG_MULTIPLY=(s=t.multiply)!==null&&s!==void 0?s:g.DBG_MULTIPLY,super(e,"MeshDebug",200,g,!0,!0),this._mode=g.DBG_MODE,this._multiply=g.DBG_MULTIPLY,this.shadedDiffuseColor=(r=t.shadedDiffuseColor)!==null&&r!==void 0?r:new Te(1,1,1),this.shadedSpecularColor=(n=t.shadedSpecularColor)!==null&&n!==void 0?n:new Te(.8,.8,.8),this.shadedSpecularPower=(a=t.shadedSpecularPower)!==null&&a!==void 0?a:10,this.wireframeThickness=(l=t.wireframeThickness)!==null&&l!==void 0?l:.7,this.wireframeTrianglesColor=(h=t.wireframeTrianglesColor)!==null&&h!==void 0?h:new Te(0,0,0),this.wireframeVerticesColor=(c=t.wireframeVerticesColor)!==null&&c!==void 0?c:new Te(.8,.8,.8),this.vertexColor=(u=t.vertexColor)!==null&&u!==void 0?u:new Te(0,0,0),this.vertexRadius=(d=t.vertexRadius)!==null&&d!==void 0?d:1.2,this.uvScale=(f=t.uvScale)!==null&&f!==void 0?f:20,this.uvPrimaryColor=(p=t.uvPrimaryColor)!==null&&p!==void 0?p:new Te(1,1,1),this.uvSecondaryColor=(_=t.uvSecondaryColor)!==null&&_!==void 0?_:new Te(.5,.5,.5),this._materialColor=Er.MaterialColors[Er._PluginCount++%Er.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){G.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==Yc.VERTICES||this._mode==Yc.TRIANGLES||this._mode==Yc.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&G.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:y4}}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:C4,CUSTOM_VERTEX_MAIN_END:b4}:{CUSTOM_FRAGMENT_DEFINITIONS:A4,CUSTOM_FRAGMENT_MAIN_END:R4}}static Reset(){this._PluginCount=0,this.MaterialColors=Dy}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 p=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,p)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let c=0;ckh.EPSILON?1:0;c|=p,u.push(p)}switch(c){case 0:(T.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=3&&(g=new ou(p,e.shared),g.plane&&s.push(g)),_.length>=3&&(g=new ou(_,e.shared),g.plane&&r.push(g));break}}}}kh.EPSILON=1e-5;class ou{constructor(e,t){this.vertices=e,this.shared=t,this.plane=kh.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new ou(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let ja=class C_{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new C_;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;tt.clone()),e.copyTransformAttributes(this),e}union(e){const t=new ja(this.clone()._polygons),i=new ja(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new ja(this._polygons),i=new ja(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 ja(this.clone()._polygons),i=new ja(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(),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new ja(this._polygons),i=new ja(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 ja(this.clone()._polygons),i=new ja(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new ja(this._polygons),i=new ja(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=[],a=[];let l=null,h=null;const c=T.Zero(),u=T.Zero(),d=Re.Zero(),f=new Ze(0,0,0,0),p=[0,0,0],_={};let g;for(let E=0,C=s.length;Ec.shared.meshId===u.shared.meshId?c.shared.subMeshId-u.shared.subMeshId:c.shared.meshId-u.shared.meshId),this.toVertexData(c=>{a[c.shared.meshId]||(a[c.shared.meshId]={}),a[c.shared.meshId][c.shared.subMeshId]||(a[c.shared.meshId][c.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:c.shared.materialIndex}),l=a[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 a){u=-1;for(const f in a[d])l=a[d][f],on.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 P4="meshUVSpaceRendererVertexShader",M4=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#endif`,Ny=[new Te(.98,.26,.38),new Te(.47,.75,.3),new Te(0,.26,.77),new Te(.97,.6,.76),new Te(.19,.63,.78),new Te(.98,.8,.6),new Te(.65,.43,.15),new Te(.15,.47,.22),new Te(.67,.71,.86),new Te(.09,.46,.56),new Te(.8,.98,.02),new Te(.39,.29,.13),new Te(.53,.63,.06),new Te(.95,.96,.41),new Te(1,.72,.94),new Te(.63,.08,.31),new Te(.66,.96,.95),new Te(.22,.14,.19),new Te(.14,.65,.59),new Te(.93,1,.68),new Te(.93,.14,.44),new Te(.47,.86,.67),new Te(.85,.07,.78),new Te(.53,.64,.98),new Te(.43,.37,.56),new Te(.71,.65,.25),new Te(.66,.19,.01),new Te(.94,.53,.12),new Te(.41,.44,.44),new Te(.24,.71,.96),new Te(.57,.28,.56),new Te(.44,.98,.42)];var Yc;(function(o){o[o.NONE=0]="NONE",o[o.TRIANGLES=1]="TRIANGLES",o[o.VERTICES=2]="VERTICES",o[o.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",o[o.UV0=4]="UV0",o[o.UV1=5]="UV1",o[o.VERTEXCOLORS=6]="VERTEXCOLORS",o[o.MATERIALIDS=7]="MATERIALIDS"})(Yc||(Yc={}));class D4 extends Wn{constructor(){super(...arguments),this.DBG_MODE=Yc.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Er extends ca{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,s,r,n,a,l,h,c,u,d,f,p,_;const g=new D4;g.DBG_MODE=(i=t.mode)!==null&&i!==void 0?i:g.DBG_MODE,g.DBG_MULTIPLY=(s=t.multiply)!==null&&s!==void 0?s:g.DBG_MULTIPLY,super(e,"MeshDebug",200,g,!0,!0),this._mode=g.DBG_MODE,this._multiply=g.DBG_MULTIPLY,this.shadedDiffuseColor=(r=t.shadedDiffuseColor)!==null&&r!==void 0?r:new Te(1,1,1),this.shadedSpecularColor=(n=t.shadedSpecularColor)!==null&&n!==void 0?n:new Te(.8,.8,.8),this.shadedSpecularPower=(a=t.shadedSpecularPower)!==null&&a!==void 0?a:10,this.wireframeThickness=(l=t.wireframeThickness)!==null&&l!==void 0?l:.7,this.wireframeTrianglesColor=(h=t.wireframeTrianglesColor)!==null&&h!==void 0?h:new Te(0,0,0),this.wireframeVerticesColor=(c=t.wireframeVerticesColor)!==null&&c!==void 0?c:new Te(.8,.8,.8),this.vertexColor=(u=t.vertexColor)!==null&&u!==void 0?u:new Te(0,0,0),this.vertexRadius=(d=t.vertexRadius)!==null&&d!==void 0?d:1.2,this.uvScale=(f=t.uvScale)!==null&&f!==void 0?f:20,this.uvPrimaryColor=(p=t.uvPrimaryColor)!==null&&p!==void 0?p:new Te(1,1,1),this.uvSecondaryColor=(_=t.uvSecondaryColor)!==null&&_!==void 0?_:new Te(.5,.5,.5),this._materialColor=Er.MaterialColors[Er._PluginCount++%Er.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){G.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==Yc.VERTICES||this._mode==Yc.TRIANGLES||this._mode==Yc.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&G.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:I4}}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:A4,CUSTOM_VERTEX_MAIN_END:R4}:{CUSTOM_FRAGMENT_DEFINITIONS:P4,CUSTOM_FRAGMENT_MAIN_END:M4}}static Reset(){this._PluginCount=0,this.MaterialColors=Ny}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 p=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,p)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let c=0;cGh.EPSILON?1:0;c|=p,u.push(p)}switch(c){case 0:(T.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=3&&(g=new ou(p,e.shared),g.plane&&s.push(g)),_.length>=3&&(g=new ou(_,e.shared),g.plane&&r.push(g));break}}}}Gh.EPSILON=1e-5;class ou{constructor(e,t){this.vertices=e,this.shared=t,this.plane=Gh.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new ou(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let ja=class C_{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new C_;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;tt.clone()),e.copyTransformAttributes(this),e}union(e){const t=new ja(this.clone()._polygons),i=new ja(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new ja(this._polygons),i=new ja(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 ja(this.clone()._polygons),i=new ja(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(),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new ja(this._polygons),i=new ja(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 ja(this.clone()._polygons),i=new ja(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Vo._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new ja(this._polygons),i=new ja(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=[],a=[];let l=null,h=null;const c=T.Zero(),u=T.Zero(),d=Re.Zero(),f=new Ze(0,0,0,0),p=[0,0,0],_={};let g;for(let E=0,C=s.length;Ec.shared.meshId===u.shared.meshId?c.shared.subMeshId-u.shared.subMeshId:c.shared.meshId-u.shared.meshId),this.toVertexData(c=>{a[c.shared.meshId]||(a[c.shared.meshId]={}),a[c.shared.meshId][c.shared.subMeshId]||(a[c.shared.meshId][c.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:c.shared.materialIndex}),l=a[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 a){u=-1;for(const f in a[d])l=a[d][f],on.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 O4="meshUVSpaceRendererVertexShader",N4=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; #include #include #include @@ -9222,70 +9222,70 @@ 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);}`;ne.ShadersStore[P4]=M4;const D4="meshUVSpaceRendererPixelShader",O4=`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;} +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);}`;ne.ShadersStore[O4]=N4;const w4="meshUVSpaceRendererPixelShader",F4=`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);} -`;ne.ShadersStore[D4]=O4;const N4="meshUVSpaceRendererMaskerVertexShader",w4="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;}";ne.ShadersStore[N4]=w4;const F4="meshUVSpaceRendererMaskerPixelShader",L4=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} -`;ne.ShadersStore[F4]=L4;const B4="meshUVSpaceRendererFinaliserPixelShader",V4=`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;} +`;ne.ShadersStore[w4]=F4;const L4="meshUVSpaceRendererMaskerVertexShader",B4="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;}";ne.ShadersStore[L4]=B4;const V4="meshUVSpaceRendererMaskerPixelShader",U4=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} +`;ne.ShadersStore[V4]=U4;const k4="meshUVSpaceRendererFinaliserPixelShader",G4=`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;}}} -`;ne.ShadersStore[B4]=V4;const U4="meshUVSpaceRendererFinaliserVertexShader",k4=`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;} -`;ne.ShadersStore[U4]=k4;se._TrailMeshParser=(o,e)=>H_.Parse(o,e);class H_ extends se{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 a=0;a{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(P.PositionKind),t=this.getVerticesData(P.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let n=3*this._sectionPolygonPointsCount;n{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()})};eo.Run(e.settings.length,s=>{i(e.settings[s.index],()=>{s.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case X_.QUADRATIC:default:return new X4(e.mesh)}}}var X_;(function(o){o[o.QUADRATIC=0]="QUADRATIC"})(X_||(X_={}));class z4{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class W4{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new $c,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class $c{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,a,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[a]-this.data[i]*this.data[r]*this.data[a]-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 $c;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 $c($c.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 H4{constructor(e,t){this.vertexId=e,this.triangleId=t}}class X4{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=$t}simplify(e,t){this._initDecimatedMesh(),eo.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,a=(l,h)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let d=0;d{const f=~~((this._triangles.length/2+d)%this._triangles.length),p=this._triangles[f];if(p&&!(p.error[3]>c||p.deleted||p.isDirty)){for(let _=0;_<3;++_)if(p.error[_]{R.indexOf(O)===-1&&(O.deletePending=!0,R.push(O))}),R.length%2!==0)continue;E.q=C.q.add(E.q),E.updatePosition(S);const I=this._references.length;r=this._updateTriangles(E,E,g,r),r=this._updateTriangles(E,C,v,r);const N=this._references.length-I;if(N<=E.triangleCount){if(N)for(let O=0;On-r<=s)},0)};eo.Run(this.decimationIterations,l=>{n-r<=s?l.breakLoop():a(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(P.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],a=u=>{if(i){for(let d=0;d{if(!s)return;const d=u+n.verticesStart,f=T.FromArray(s,d*3),p=a(f)||new W4(f,this._vertices.length);p.originalOffsets.push(d),p.id===this._vertices.length&&this._vertices.push(p),l.push(p.id)},c=n.verticesCount;eo.SyncAsyncForLoop(c,this.syncIterations/4>>0,h,()=>{const u=d=>{if(!r)return;const p=(n.indexStart/3+d)*3,_=r[p+0],g=r[p+1],v=r[p+2],E=this._vertices[l[_-n.verticesStart]],C=this._vertices[l[g-n.verticesStart]],S=this._vertices[l[v-n.verticesStart]],b=new z4([E,C,S]);b.originalOffset=p,this._triangles.push(b)};eo.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const s=this._triangles[i];s.normal=T.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($c.DataFromNumbers(s.normal.x,s.normal.y,s.normal.z,-T.Dot(s.normal,s._vertices[0].position)))};eo.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])};eo.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{n.push(S.position.x),n.push(S.position.y),n.push(S.position.z),c&&c.length&&(a.push(c[b*3]),a.push(c[b*3+1]),a.push(c[b*3+2])),u&&u.length&&(l.push(u[b*2]),l.push(u[b*2+1])),d&&d.length&&(h.push(d[b*4]),h.push(d[b*4+1]),h.push(d[b*4+2]),h.push(d[b*4+3])),++f})}const p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const v=this._reconstructedMesh.getIndices(),E=this._mesh.getIndices();for(i=0;i{const b=E[s.originalOffset+S];let R=s._vertices[S].originalOffsets.indexOf(b);R<0&&(R=0),v.push(s._vertices[S].id+R+_)});this._reconstructedMesh.setIndices(v),this._reconstructedMesh.setVerticesData(P.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(P.NormalKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(P.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(P.ColorKind,h);const C=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],g.forEach(S=>{on.AddToMesh(S.materialIndex,S.verticesStart,S.verticesCount,S.indexStart,S.indexCount,S.getMesh())}),on.AddToMesh(C.materialIndex,_,f,p,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new se(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.999)return!0;const f=T.Cross(u,d).normalize();if(s[n]=!1,T.Dot(f,a.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let n=0;nBs.Parse(o,e);class Bs extends Oy{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Li.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{var s;const r=[],n=[],a=[],l=Li.GetLineLength(i);for(let f=0,p=0;p0&&(a=Bs._CopyV3(l,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return Bs._CompareV3(n-1,0,e)?a=Bs._CopyV3(1,e):a=Bs._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:r,side:s}}_createVertexBuffers(){const e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new Br(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const s=new Br(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(s.createVertexBuffer("grl_nextAndCounters",0,4));const r=new Br(t,this._widths,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=r;const n=new Br(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}}Bs._V_START=new T;Bs._V_END=new T;Bs._V_OFFSET_START=new T;Bs._V_OFFSET_END=new T;se._GreasedLineRibbonMeshParser=(o,e)=>$s.Parse(o,e);class $s extends Oy{constructor(e,t,i,s){var r;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=(r=i.widths)!==null&&r!==void 0?r:[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(Li.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{const p=$s._ConvertToRibbonPath(d,h.ribbonOptions,this._scene.useRightHandedSystem,n&&n[f]);r=this._preprocess(p,r,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 i,s,r;const n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const a=[],l=[],h=e[0];for(let f=0;f2)for(let f=0;f0&&(c[0]+=1,c[1]+=1),l.push(c[1]+(p%2!==0?n:0),c[0],c[2]),u&&l.push(c[0],c[1]+(p%2!==0?n:0),c[2])}else for(let f=0;fp.y&&p.x>p.z?i?$s._RightHandedForwardReadOnlyQuaternion:$s._LeftHandedForwardReadOnlyQuaternion:$s._LeftReadOnlyQuaternion),h=p.normalize()}c=h.multiplyByFloats(a,a,a),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)?$s.DIRECTION_YZ:e.y===t.y?$s.DIRECTION_XZ:e.z===t.z?$s.DIRECTION_XY:$s.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Ur.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Ur.DeepCopy(i,s,["instance"],void 0,!0);const n=new $s(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 $s(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=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,o*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[o]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};se.prototype.thinInstanceSetAttributeAt=function(o,e,t,i=!0){return o===P.ColorKind&&(o=P.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[o]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(o,0),this._userThinInstanceBuffersStorage.data[o].set(t,e*this._userThinInstanceBuffersStorage.strides[o]),i&&this.thinInstanceBufferUpdated(o),!0)};Object.defineProperty(se.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(o){var e,t;const i=(e=this._thinInstanceDataStorage.matrixData)!==null&&e!==void 0?e:(t=this.source)===null||t===void 0?void 0:t._thinInstanceDataStorage.matrixData,s=i?i.length/16:0;o<=s&&(this._thinInstanceDataStorage.instancesCount=o)},enumerable:!0,configurable:!0});se.prototype._thinInstanceCreateMatrixBuffer=function(o,e,t=!1){o===P.ColorKind&&(o=P.ColorInstanceKind);const i=new Br(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(o+s,s*4,4));return i};se.prototype.thinInstanceSetBuffer=function(o,e,t=0,i=!1){var s,r,n;t=t||16,o==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)===null||s===void 0||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())):o==="previousMatrix"?((r=this._thinInstanceDataStorage.previousMatrixBuffer)===null||r===void 0||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(o===P.ColorKind&&(o=P.ColorInstanceKind),e===null?!((n=this._userThinInstanceBuffersStorage)===null||n===void 0)&&n.data[o]&&(this.removeVerticesData(o),delete this._userThinInstanceBuffersStorage.data[o],delete this._userThinInstanceBuffersStorage.strides[o],delete this._userThinInstanceBuffersStorage.sizes[o],delete this._userThinInstanceBuffersStorage.vertexBuffers[o]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[o]=e,this._userThinInstanceBuffersStorage.strides[o]=t,this._userThinInstanceBuffersStorage.sizes[o]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[o]=new P(this.getEngine(),e,o,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[o])))};se.prototype.thinInstanceBufferUpdated=function(o){var e,t,i;o==="matrix"?(e=this._thinInstanceDataStorage.matrixBuffer)===null||e===void 0||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):o==="previousMatrix"?(t=this._thinInstanceDataStorage.previousMatrixBuffer)===null||t===void 0||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(o===P.ColorKind&&(o=P.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[o]&&this._userThinInstanceBuffersStorage.vertexBuffers[o].updateDirectly(this._userThinInstanceBuffersStorage.data[o],0))};se.prototype.thinInstancePartialBufferUpdate=function(o,e,t){var i;o==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(o===P.ColorKind&&(o=P.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[o]&&this._userThinInstanceBuffersStorage.vertexBuffers[o].updateDirectly(e,t))};se.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const o=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;ee.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===void 0)&&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=$.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new he,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)===Ql.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==$.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?Ql.Compatible:Ql.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Ql.TypeIncompatible;let s=i,r=t;return this.direction===Ld.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Ql.HierarchyIssue:Ql.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<$.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 Qt{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 he,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Jf.UniqueId}registerInput(e,t,i=!1,s,r,n){const a=new dC(e,this,Ld.Input);return a.type=t,a.isOptional=i,a.defaultValue=s,a.value=s,a.valueMin=r,a.valueMax=n,this._inputs.push(a),this}registerOutput(e,t,i){return i=i??new dC(e,this,Ld.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&&G.Log(`Building ${this.name} [${this.getClassName()}]`);const t=ar.Now;this._buildBlock(e),this._buildExecutionTime=ar.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=Ds(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}; +`;ne.ShadersStore[k4]=G4;const z4="meshUVSpaceRendererFinaliserVertexShader",W4=`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;} +`;ne.ShadersStore[z4]=W4;se._TrailMeshParser=(o,e)=>H_.Parse(o,e);class H_ extends se{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 a=0;a{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(P.PositionKind),t=this.getVerticesData(P.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let n=3*this._sectionPolygonPointsCount;n{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()})};eo.Run(e.settings.length,s=>{i(e.settings[s.index],()=>{s.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case X_.QUADRATIC:default:return new K4(e.mesh)}}}var X_;(function(o){o[o.QUADRATIC=0]="QUADRATIC"})(X_||(X_={}));class X4{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class Y4{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new $c,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class $c{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,a,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[a]-this.data[i]*this.data[r]*this.data[a]-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 $c;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 $c($c.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 $4{constructor(e,t){this.vertexId=e,this.triangleId=t}}class K4{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=$t}simplify(e,t){this._initDecimatedMesh(),eo.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,a=(l,h)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let d=0;d{const f=~~((this._triangles.length/2+d)%this._triangles.length),p=this._triangles[f];if(p&&!(p.error[3]>c||p.deleted||p.isDirty)){for(let _=0;_<3;++_)if(p.error[_]{R.indexOf(O)===-1&&(O.deletePending=!0,R.push(O))}),R.length%2!==0)continue;E.q=C.q.add(E.q),E.updatePosition(S);const I=this._references.length;r=this._updateTriangles(E,E,g,r),r=this._updateTriangles(E,C,v,r);const N=this._references.length-I;if(N<=E.triangleCount){if(N)for(let O=0;On-r<=s)},0)};eo.Run(this.decimationIterations,l=>{n-r<=s?l.breakLoop():a(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(P.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],a=u=>{if(i){for(let d=0;d{if(!s)return;const d=u+n.verticesStart,f=T.FromArray(s,d*3),p=a(f)||new Y4(f,this._vertices.length);p.originalOffsets.push(d),p.id===this._vertices.length&&this._vertices.push(p),l.push(p.id)},c=n.verticesCount;eo.SyncAsyncForLoop(c,this.syncIterations/4>>0,h,()=>{const u=d=>{if(!r)return;const p=(n.indexStart/3+d)*3,_=r[p+0],g=r[p+1],v=r[p+2],E=this._vertices[l[_-n.verticesStart]],C=this._vertices[l[g-n.verticesStart]],S=this._vertices[l[v-n.verticesStart]],b=new X4([E,C,S]);b.originalOffset=p,this._triangles.push(b)};eo.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const s=this._triangles[i];s.normal=T.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($c.DataFromNumbers(s.normal.x,s.normal.y,s.normal.z,-T.Dot(s.normal,s._vertices[0].position)))};eo.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])};eo.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{n.push(S.position.x),n.push(S.position.y),n.push(S.position.z),c&&c.length&&(a.push(c[b*3]),a.push(c[b*3+1]),a.push(c[b*3+2])),u&&u.length&&(l.push(u[b*2]),l.push(u[b*2+1])),d&&d.length&&(h.push(d[b*4]),h.push(d[b*4+1]),h.push(d[b*4+2]),h.push(d[b*4+3])),++f})}const p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const v=this._reconstructedMesh.getIndices(),E=this._mesh.getIndices();for(i=0;i{const b=E[s.originalOffset+S];let R=s._vertices[S].originalOffsets.indexOf(b);R<0&&(R=0),v.push(s._vertices[S].id+R+_)});this._reconstructedMesh.setIndices(v),this._reconstructedMesh.setVerticesData(P.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(P.NormalKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(P.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(P.ColorKind,h);const C=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],g.forEach(S=>{on.AddToMesh(S.materialIndex,S.verticesStart,S.verticesCount,S.indexStart,S.indexCount,S.getMesh())}),on.AddToMesh(C.materialIndex,_,f,p,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new se(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.999)return!0;const f=T.Cross(u,d).normalize();if(s[n]=!1,T.Dot(f,a.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let n=0;nBs.Parse(o,e);class Bs extends wy{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Li.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{var s;const r=[],n=[],a=[],l=Li.GetLineLength(i);for(let f=0,p=0;p0&&(a=Bs._CopyV3(l,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return Bs._CompareV3(n-1,0,e)?a=Bs._CopyV3(1,e):a=Bs._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:r,side:s}}_createVertexBuffers(){const e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new Br(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const s=new Br(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(s.createVertexBuffer("grl_nextAndCounters",0,4));const r=new Br(t,this._widths,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=r;const n=new Br(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}}Bs._V_START=new T;Bs._V_END=new T;Bs._V_OFFSET_START=new T;Bs._V_OFFSET_END=new T;se._GreasedLineRibbonMeshParser=(o,e)=>$s.Parse(o,e);class $s extends wy{constructor(e,t,i,s){var r;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=(r=i.widths)!==null&&r!==void 0?r:[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(Li.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{const p=$s._ConvertToRibbonPath(d,h.ribbonOptions,this._scene.useRightHandedSystem,n&&n[f]);r=this._preprocess(p,r,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 i,s,r;const n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const a=[],l=[],h=e[0];for(let f=0;f2)for(let f=0;f0&&(c[0]+=1,c[1]+=1),l.push(c[1]+(p%2!==0?n:0),c[0],c[2]),u&&l.push(c[0],c[1]+(p%2!==0?n:0),c[2])}else for(let f=0;fp.y&&p.x>p.z?i?$s._RightHandedForwardReadOnlyQuaternion:$s._LeftHandedForwardReadOnlyQuaternion:$s._LeftReadOnlyQuaternion),h=p.normalize()}c=h.multiplyByFloats(a,a,a),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)?$s.DIRECTION_YZ:e.y===t.y?$s.DIRECTION_XZ:e.z===t.z?$s.DIRECTION_XY:$s.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Ur.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Ur.DeepCopy(i,s,["instance"],void 0,!0);const n=new $s(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 $s(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=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,o*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[o]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};se.prototype.thinInstanceSetAttributeAt=function(o,e,t,i=!0){return o===P.ColorKind&&(o=P.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[o]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(o,0),this._userThinInstanceBuffersStorage.data[o].set(t,e*this._userThinInstanceBuffersStorage.strides[o]),i&&this.thinInstanceBufferUpdated(o),!0)};Object.defineProperty(se.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(o){var e,t;const i=(e=this._thinInstanceDataStorage.matrixData)!==null&&e!==void 0?e:(t=this.source)===null||t===void 0?void 0:t._thinInstanceDataStorage.matrixData,s=i?i.length/16:0;o<=s&&(this._thinInstanceDataStorage.instancesCount=o)},enumerable:!0,configurable:!0});se.prototype._thinInstanceCreateMatrixBuffer=function(o,e,t=!1){o===P.ColorKind&&(o=P.ColorInstanceKind);const i=new Br(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(o+s,s*4,4));return i};se.prototype.thinInstanceSetBuffer=function(o,e,t=0,i=!1){var s,r,n;t=t||16,o==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)===null||s===void 0||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())):o==="previousMatrix"?((r=this._thinInstanceDataStorage.previousMatrixBuffer)===null||r===void 0||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(o===P.ColorKind&&(o=P.ColorInstanceKind),e===null?!((n=this._userThinInstanceBuffersStorage)===null||n===void 0)&&n.data[o]&&(this.removeVerticesData(o),delete this._userThinInstanceBuffersStorage.data[o],delete this._userThinInstanceBuffersStorage.strides[o],delete this._userThinInstanceBuffersStorage.sizes[o],delete this._userThinInstanceBuffersStorage.vertexBuffers[o]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[o]=e,this._userThinInstanceBuffersStorage.strides[o]=t,this._userThinInstanceBuffersStorage.sizes[o]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[o]=new P(this.getEngine(),e,o,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[o])))};se.prototype.thinInstanceBufferUpdated=function(o){var e,t,i;o==="matrix"?(e=this._thinInstanceDataStorage.matrixBuffer)===null||e===void 0||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):o==="previousMatrix"?(t=this._thinInstanceDataStorage.previousMatrixBuffer)===null||t===void 0||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(o===P.ColorKind&&(o=P.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[o]&&this._userThinInstanceBuffersStorage.vertexBuffers[o].updateDirectly(this._userThinInstanceBuffersStorage.data[o],0))};se.prototype.thinInstancePartialBufferUpdate=function(o,e,t){var i;o==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(o===P.ColorKind&&(o=P.ColorInstanceKind),!((i=this._userThinInstanceBuffersStorage)===null||i===void 0)&&i.vertexBuffers[o]&&this._userThinInstanceBuffersStorage.vertexBuffers[o].updateDirectly(e,t))};se.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const o=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;ee.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===void 0)&&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=$.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new he,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)===Zl.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==$.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?Zl.Compatible:Zl.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Zl.TypeIncompatible;let s=i,r=t;return this.direction===Bd.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Zl.HierarchyIssue:Zl.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<$.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 Qt{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 he,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Jf.UniqueId}registerInput(e,t,i=!1,s,r,n){const a=new pC(e,this,Bd.Input);return a.type=t,a.isOptional=i,a.defaultValue=s,a.value=s,a.valueMin=r,a.valueMax=n,this._inputs.push(a),this}registerOutput(e,t,i){return i=i??new pC(e,this,Bd.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&&G.Log(`Building ${this.name} [${this.getClassName()}]`);const t=ar.Now;this._buildBlock(e),this._buildExecutionTime=ar.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=Ds(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 a=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${a}); `}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 a of n.endpoints){const l=a.ownerBlock;l&&t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=Ds(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()}}A([D("comment")],Qt.prototype,"comments",void 0);class Ny extends Qt{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",$.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}j("BABYLON.GeometryOutputBlock",Ny);var Ci;(function(o){o[o.None=0]="None",o[o.Positions=1]="Positions",o[o.Normals=2]="Normals",o[o.Tangents=3]="Tangents",o[o.UV=4]="UV",o[o.UV2=5]="UV2",o[o.UV3=6]="UV3",o[o.UV4=7]="UV4",o[o.UV5=8]="UV5",o[o.UV6=9]="UV6",o[o.Colors=10]="Colors",o[o.VertexID=11]="VertexID",o[o.FaceID=12]="FaceID",o[o.GeometryID=13]="GeometryID",o[o.CollectionID=14]="CollectionID",o[o.LoopID=15]="LoopID",o[o.InstanceID=16]="InstanceID"})(Ci||(Ci={}));class $4{constructor(){this._rotationMatrix=new k,this._scalingMatrix=new k,this._positionMatrix=new k,this._scalingRotationMatrix=new k,this._transformMatrix=new k,this._tempVector3=new T,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 Ci.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?T.Zero():T.FromArray(this.geometryContext.positions,i*3);case Ci.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?T.Zero():T.FromArray(this.geometryContext.normals,i*3);case Ci.Colors:return!this.geometryContext||!this.geometryContext.colors?Dt.Zero():Dt.FromArray(this.geometryContext.colors,i*4);case Ci.Tangents:return!this.geometryContext||!this.geometryContext.tangents?Dt.Zero():Dt.FromArray(this.geometryContext.tangents,i*4);case Ci.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?Re.Zero():Re.FromArray(this.geometryContext.uvs,i*2);case Ci.UV2:return!this.geometryContext||!this.geometryContext.uvs2?Re.Zero():Re.FromArray(this.geometryContext.uvs2,i*2);case Ci.UV3:return!this.geometryContext||!this.geometryContext.uvs3?Re.Zero():Re.FromArray(this.geometryContext.uvs3,i*2);case Ci.UV4:return!this.geometryContext||!this.geometryContext.uvs4?Re.Zero():Re.FromArray(this.geometryContext.uvs4,i*2);case Ci.UV5:return!this.geometryContext||!this.geometryContext.uvs5?Re.Zero():Re.FromArray(this.geometryContext.uvs5,i*2);case Ci.UV6:return!this.geometryContext||!this.geometryContext.uvs6?Re.Zero():Re.FromArray(this.geometryContext.uvs6,i*2);case Ci.VertexID:return i;case Ci.FaceID:return this.executionContext.getExecutionFaceIndex();case Ci.LoopID:return this.executionContext.getExecutionLoopIndex();case Ci.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Ci.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Ci.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 $.Vector2:return new Re(i,i);case $.Vector3:return new T(i,i,i);case $.Vector4:return new Dt(i,i,i,i)}return null}adaptInput(e,t,i){var s;if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(((s=e._connectedPoint)===null||s===void 0?void 0:s.type)===t)return r;switch(t){case $.Vector2:return new Re(r,r);case $.Vector3:return new T(r,r,r);case $.Vector4:return new Dt(r,r,r,r)}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. +`;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 a of n.endpoints){const l=a.ownerBlock;l&&t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=Ds(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()}}A([D("comment")],Qt.prototype,"comments",void 0);class Fy extends Qt{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",$.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}j("BABYLON.GeometryOutputBlock",Fy);var Ci;(function(o){o[o.None=0]="None",o[o.Positions=1]="Positions",o[o.Normals=2]="Normals",o[o.Tangents=3]="Tangents",o[o.UV=4]="UV",o[o.UV2=5]="UV2",o[o.UV3=6]="UV3",o[o.UV4=7]="UV4",o[o.UV5=8]="UV5",o[o.UV6=9]="UV6",o[o.Colors=10]="Colors",o[o.VertexID=11]="VertexID",o[o.FaceID=12]="FaceID",o[o.GeometryID=13]="GeometryID",o[o.CollectionID=14]="CollectionID",o[o.LoopID=15]="LoopID",o[o.InstanceID=16]="InstanceID"})(Ci||(Ci={}));class j4{constructor(){this._rotationMatrix=new k,this._scalingMatrix=new k,this._positionMatrix=new k,this._scalingRotationMatrix=new k,this._transformMatrix=new k,this._tempVector3=new T,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 Ci.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?T.Zero():T.FromArray(this.geometryContext.positions,i*3);case Ci.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?T.Zero():T.FromArray(this.geometryContext.normals,i*3);case Ci.Colors:return!this.geometryContext||!this.geometryContext.colors?Dt.Zero():Dt.FromArray(this.geometryContext.colors,i*4);case Ci.Tangents:return!this.geometryContext||!this.geometryContext.tangents?Dt.Zero():Dt.FromArray(this.geometryContext.tangents,i*4);case Ci.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?Re.Zero():Re.FromArray(this.geometryContext.uvs,i*2);case Ci.UV2:return!this.geometryContext||!this.geometryContext.uvs2?Re.Zero():Re.FromArray(this.geometryContext.uvs2,i*2);case Ci.UV3:return!this.geometryContext||!this.geometryContext.uvs3?Re.Zero():Re.FromArray(this.geometryContext.uvs3,i*2);case Ci.UV4:return!this.geometryContext||!this.geometryContext.uvs4?Re.Zero():Re.FromArray(this.geometryContext.uvs4,i*2);case Ci.UV5:return!this.geometryContext||!this.geometryContext.uvs5?Re.Zero():Re.FromArray(this.geometryContext.uvs5,i*2);case Ci.UV6:return!this.geometryContext||!this.geometryContext.uvs6?Re.Zero():Re.FromArray(this.geometryContext.uvs6,i*2);case Ci.VertexID:return i;case Ci.FaceID:return this.executionContext.getExecutionFaceIndex();case Ci.LoopID:return this.executionContext.getExecutionLoopIndex();case Ci.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Ci.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Ci.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 $.Vector2:return new Re(i,i);case $.Vector3:return new T(i,i,i);case $.Vector4:return new Dt(i,i,i,i)}return null}adaptInput(e,t,i){var s;if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(((s=e._connectedPoint)===null||s===void 0?void 0:s.type)===t)return r;switch(t){case $.Vector2:return new Re(r,r);case $.Vector3:return new T(r,r,r);case $.Vector4:return new Dt(r,r,r,r)}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 ${Ci[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){k.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),k.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),k.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;nt.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.${Ci[this._contextualSource]}; `;const t=[];let i="";switch(this.type){case $.Float:case $.Int:i=`${this.value}`;break;case $.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case $.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case $.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===$.Float||this.type===$.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=Ds(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}j("BABYLON.GeometryInputBlock",Xs);class aT extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",$.Float,!0,1),this.registerInput("width",$.Float,!0,0),this.registerInput("height",$.Float,!0,0),this.registerInput("depth",$.Float,!0,0),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("subdivisionsX",$.Int,!0,0),this.registerInput("subdivisionsY",$.Int,!0,0),this.registerInput("subdivisionsZ",$.Int,!0,0),this.registerOutput("geometry",$.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 Xs("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Xs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Xs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Xs("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),a=this.subdivisionsY.getConnectedValue(s),l=this.subdivisionsZ.getConnectedValue(s);return r&&(t.segments=r),n&&(t.widthSegments=n),a&&(t.heightSegments=a),l&&(t.depthSegments=l),PB(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],aT.prototype,"evaluateContext",void 0);j("BABYLON.BoxBlock",aT);class na{_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=na._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new he,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 fe.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:na.EditorURL;fe.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=Object.assign({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=ar.Now;this._initializeBlock(this.outputBlock,i);const r=new $4;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=na._BuildIdGenerator++),this._buildExecutionTime=ar.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 se(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=Ds(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 a=i[n];a&&a.attachToEndpoint(r)}}for(let s=0;sa.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 a of r.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===s.name){const l=n.getInputByName(a.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"}"); +`)}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=Ds(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}j("BABYLON.GeometryInputBlock",Xs);class lT extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",$.Float,!0,1),this.registerInput("width",$.Float,!0,0),this.registerInput("height",$.Float,!0,0),this.registerInput("depth",$.Float,!0,0),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("subdivisionsX",$.Int,!0,0),this.registerInput("subdivisionsY",$.Int,!0,0),this.registerInput("subdivisionsZ",$.Int,!0,0),this.registerOutput("geometry",$.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 Xs("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Xs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Xs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Xs("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),a=this.subdivisionsY.getConnectedValue(s),l=this.subdivisionsZ.getConnectedValue(s);return r&&(t.segments=r),n&&(t.widthSegments=n),a&&(t.heightSegments=a),l&&(t.depthSegments=l),OB(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],lT.prototype,"evaluateContext",void 0);j("BABYLON.BoxBlock",lT);class na{_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=na._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new he,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 fe.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:na.EditorURL;fe.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=Object.assign({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=ar.Now;this._initializeBlock(this.outputBlock,i);const r=new j4;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=na._BuildIdGenerator++),this._buildExecutionTime=ar.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 se(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=Ds(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 a=i[n];a&&a.attachToEndpoint(r)}}for(let s=0;sa.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 a of r.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===s.name){const l=n.getInputByName(a.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 aT("Box");e.autoConfigure();const t=new Ny("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Xe.Clone(()=>new na(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Xe.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 na(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Xe.Parse(()=>new na(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(na.CreateDefault("blank")):new Promise((s,r)=>{const n=new Hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(a.nodeGeometry);t||(t=Xe.Parse(()=>new na(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()})}}na._BuildIdGenerator=0;na.EditorURL=`${fe._DefaultCdnUrl}/v${re.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;na.SnippetUrl="https://snippet.babylonjs.com";A([D()],na.prototype,"name",void 0);A([D("comment")],na.prototype,"comment",void 0);class oT extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=$t,this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.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;ln[l]),a};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"}; +`),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 lT("Box");e.autoConfigure();const t=new Fy("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Xe.Clone(()=>new na(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Xe.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 na(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Xe.Parse(()=>new na(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(na.CreateDefault("blank")):new Promise((s,r)=>{const n=new Hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(a.nodeGeometry);t||(t=Xe.Parse(()=>new na(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()})}}na._BuildIdGenerator=0;na.EditorURL=`${fe._DefaultCdnUrl}/v${re.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;na.SnippetUrl="https://snippet.babylonjs.com";A([D()],na.prototype,"name",void 0);A([D("comment")],na.prototype,"comment",void 0);class hT extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=$t,this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.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;ln[l]),a};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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],oT.prototype,"evaluateContext",void 0);A([ft("Epsilon",ut.Float,"ADVANCED",{notifiers:{rebuild:!0}})],oT.prototype,"epsilon",void 0);j("BABYLON.GeometryOptimizeBlock",oT);class wy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",$.Float,!0,1),this.registerInput("width",$.Float,!0,0),this.registerInput("height",$.Float,!0,0),this.registerOutput("geometry",$.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 Xs("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new Xs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Xs("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),fx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],wy.prototype,"evaluateContext",void 0);j("BABYLON.PlaneBlock",wy);class Fy extends Qt{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",$.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=De.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=De.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=De.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}A([ft("Serialize cached data",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Fy.prototype,"serializedCachedData",void 0);j("BABYLON.MeshBlock",Fy);class Ly extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",$.Float,!0,1),this.registerInput("radiusX",$.Float,!0,0),this.registerInput("radiusY",$.Float,!0,0),this.registerInput("radiusZ",$.Float,!0,0),this.registerInput("subdivisions",$.Int,!0,4),this.registerOutput("geometry",$.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 Xs("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),mx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ly.prototype,"evaluateContext",void 0);j("BABYLON.IcoSphereBlock",Ly);class By extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",$.Int,!0,32),this.registerInput("diameter",$.Float,!0,1),this.registerInput("diameterX",$.Float,!0,0),this.registerInput("diameterY",$.Float,!0,0),this.registerInput("diameterZ",$.Float,!0,0),this.registerInput("arc",$.Float,!0,1),this.registerInput("slice",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("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),Dx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],By.prototype,"evaluateContext",void 0);j("BABYLON.SphereBlock",By);class Vy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",$.Float,!0,1),this.registerInput("height",$.Float,!0,1),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("subdivisionsX",$.Int,!0,0),this.registerInput("subdivisionsY",$.Int,!0,0),this.registerOutput("geometry",$.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 Xs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Xs("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),xl(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Vy.prototype,"evaluateContext",void 0);j("BABYLON.GridBlock",Vy);class Uy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",$.Float,!0,1),this.registerInput("thickness",$.Float,!0,.5),this.registerInput("tessellation",$.Int,!0,16),this.registerOutput("geometry",$.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 Xs("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),Rx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Uy.prototype,"evaluateContext",void 0);j("BABYLON.TorusBlock",Uy);class ky extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",$.Float,!0,25),this.registerInput("diameter",$.Float,!0,1),this.registerInput("diameterTop",$.Float,!0,-1),this.registerInput("diameterBottom",$.Float,!0,-1),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("tessellation",$.Int,!0,24),this.registerInput("arc",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Xs("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),Px(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ky.prototype,"evaluateContext",void 0);j("BABYLON.CylinderBlock",ky);class Gy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",$.Float,!0,1),this.registerInput("radius",$.Float,!0,.25),this.registerInput("tessellation",$.Int,!0,16),this.registerInput("subdivisions",$.Int,!0,2),this.registerOutput("geometry",$.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 Xs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Xs("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),Ox(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Gy.prototype,"evaluateContext",void 0);j("BABYLON.CapsuleBlock",Gy);class zy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",$.Float,!0,.5),this.registerInput("tessellation",$.Int,!0,64),this.registerInput("arc",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("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),Nx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zy.prototype,"evaluateContext",void 0);j("BABYLON.DiscBlock",zy);class K4 extends Qt{constructor(e){super(e),this.registerOutput("geometry",$.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}j("BABYLON.NullBlock",K4);class Wy extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("positions",$.Vector3),this.registerOutput("output",$.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{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{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(t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),_x(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ly.prototype,"evaluateContext",void 0);j("BABYLON.PlaneBlock",Ly);class By extends Qt{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",$.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=Oe.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=Oe.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=Oe.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}A([ft("Serialize cached data",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],By.prototype,"serializedCachedData",void 0);j("BABYLON.MeshBlock",By);class Vy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",$.Float,!0,1),this.registerInput("radiusX",$.Float,!0,0),this.registerInput("radiusY",$.Float,!0,0),this.registerInput("radiusZ",$.Float,!0,0),this.registerInput("subdivisions",$.Int,!0,4),this.registerOutput("geometry",$.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 Xs("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),vx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Vy.prototype,"evaluateContext",void 0);j("BABYLON.IcoSphereBlock",Vy);class Uy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",$.Int,!0,32),this.registerInput("diameter",$.Float,!0,1),this.registerInput("diameterX",$.Float,!0,0),this.registerInput("diameterY",$.Float,!0,0),this.registerInput("diameterZ",$.Float,!0,0),this.registerInput("arc",$.Float,!0,1),this.registerInput("slice",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("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),Nx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Uy.prototype,"evaluateContext",void 0);j("BABYLON.SphereBlock",Uy);class ky extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",$.Float,!0,1),this.registerInput("height",$.Float,!0,1),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("subdivisionsX",$.Int,!0,0),this.registerInput("subdivisionsY",$.Int,!0,0),this.registerOutput("geometry",$.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 Xs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Xs("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),xl(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ky.prototype,"evaluateContext",void 0);j("BABYLON.GridBlock",ky);class Gy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",$.Float,!0,1),this.registerInput("thickness",$.Float,!0,.5),this.registerInput("tessellation",$.Int,!0,16),this.registerOutput("geometry",$.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 Xs("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),Px(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Gy.prototype,"evaluateContext",void 0);j("BABYLON.TorusBlock",Gy);class zy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",$.Float,!0,25),this.registerInput("diameter",$.Float,!0,1),this.registerInput("diameterTop",$.Float,!0,-1),this.registerInput("diameterBottom",$.Float,!0,-1),this.registerInput("subdivisions",$.Int,!0,1),this.registerInput("tessellation",$.Int,!0,24),this.registerInput("arc",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Xs("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),Dx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zy.prototype,"evaluateContext",void 0);j("BABYLON.CylinderBlock",zy);class Wy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",$.Float,!0,1),this.registerInput("radius",$.Float,!0,.25),this.registerInput("tessellation",$.Int,!0,16),this.registerInput("subdivisions",$.Int,!0,2),this.registerOutput("geometry",$.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 Xs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Xs("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),wx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Wy.prototype,"evaluateContext",void 0);j("BABYLON.CapsuleBlock",Wy);class Hy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",$.Float,!0,.5),this.registerInput("tessellation",$.Int,!0,64),this.registerInput("arc",$.Float,!0,1),this.registerOutput("geometry",$.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 Xs("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),Fx(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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Hy.prototype,"evaluateContext",void 0);j("BABYLON.DiscBlock",Hy);class Q4 extends Qt{constructor(e){super(e),this.registerOutput("geometry",$.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}j("BABYLON.NullBlock",Q4);class Xy extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("positions",$.Vector3),this.registerOutput("output",$.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{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{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{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{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._currentIndext.getConnectedValue(r)+i.getConnectedValue(r):e=r=>t.getConnectedValue(r).add(r.adapt(i,t.type));break}case yn.Subtract:{s?e=r=>t.getConnectedValue(r)-i.getConnectedValue(r):e=r=>t.getConnectedValue(r).subtract(r.adapt(i,t.type));break}case yn.Multiply:{s?e=r=>t.getConnectedValue(r)*i.getConnectedValue(r):e=r=>t.getConnectedValue(r).multiply(r.adapt(i,t.type));break}case yn.Divide:{s?e=r=>t.getConnectedValue(r)/i.getConnectedValue(r):e=r=>t.getConnectedValue(r).divide(r.adapt(i,t.type));break}case yn.Min:{if(s)e=r=>Math.min(t.getConnectedValue(r),i.getConnectedValue(r));else switch(t.type){case $.Vector2:{e=r=>Re.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector3:{e=r=>T.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector4:{e=r=>Dt.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}case yn.Max:if(s)e=r=>Math.max(t.getConnectedValue(r),i.getConnectedValue(r));else{switch(t.type){case $.Vector2:{e=r=>Re.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector3:{e=r=>T.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector4:{e=r=>Dt.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}}this.output._storedFunction=r=>t.type===$.Int?e(r)|0:e(r)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${yn[this.operation]}; -`}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:yn.Add},{label:"Subtract",value:yn.Subtract},{label:"Multiply",value:yn.Multiply},{label:"Divide",value:yn.Divide},{label:"Max",value:yn.Max},{label:"Min",value:yn.Min}]})],$y.prototype,"operation",void 0);j("BABYLON.MathBlock",$y);class q4 extends Qt{constructor(e){super(e),this.registerInput("value",$.AutoDetect),this.registerInput("fromMin",$.Float,!0,0),this.registerInput("fromMax",$.Float,!0,1),this.registerInput("toMin",$.Float,!0,0),this.registerInput("toMax",$.Float,!0,1),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Vector2),this._inputs[0].excludedConnectionPointTypes.push($.Vector3),this._inputs[0].excludedConnectionPointTypes.push($.Vector4),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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),a=(t-i)/(s-i)*(n-r)+r;return this.output.type===$.Int?Math.floor(a):a}}}j("BABYLON.MapRangeBlock",q4);var mr;(function(o){o[o.Equal=0]="Equal",o[o.NotEqual=1]="NotEqual",o[o.LessThan=2]="LessThan",o[o.GreaterThan=3]="GreaterThan",o[o.LessOrEqual=4]="LessOrEqual",o[o.GreaterOrEqual=5]="GreaterOrEqual",o[o.Xor=6]="Xor",o[o.Or=7]="Or",o[o.And=8]="And"})(mr||(mr={}));class Ky extends Qt{constructor(e){super(e),this.test=mr.Equal,this.registerInput("left",$.Float),this.registerInput("right",$.Float,!0,0),this.registerInput("ifTrue",$.AutoDetect,!0,1),this.registerInput("ifFalse",$.AutoDetect,!0,0),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=$.Float,this._inputs[0].acceptedConnectionPointTypes.push($.Int),this._inputs[1].acceptedConnectionPointTypes.push($.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 mr.Equal:r=ye.WithinEpsilon(i,s,$t);break;case mr.NotEqual:r=i!==s;break;case mr.LessThan:r=is;break;case mr.LessOrEqual:r=i<=s;break;case mr.GreaterOrEqual:r=i>=s;break;case mr.Xor:r=!!i&&!s||!i&&!!s;break;case mr.Or:r=!!i||!!s;break;case mr.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.${mr[this.test]}; -`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}A([ft("Test",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:mr.Equal},{label:"NotEqual",value:mr.NotEqual},{label:"LessThan",value:mr.LessThan},{label:"GreaterThan",value:mr.GreaterThan},{label:"LessOrEqual",value:mr.LessOrEqual},{label:"GreaterOrEqual",value:mr.GreaterOrEqual},{label:"Xor",value:mr.Xor},{label:"Or",value:mr.Or},{label:"And",value:mr.And}]})],Ky.prototype,"test",void 0);j("BABYLON.ConditionBlock",Ky);var To;(function(o){o[o.None=0]="None",o[o.LoopID=1]="LoopID",o[o.InstanceID=2]="InstanceID"})(To||(To={}));class qy extends Qt{constructor(e){super(e),this._currentLockId=-1,this.lockMode=To.None,this.registerInput("min",$.AutoDetect),this.registerInput("max",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.Texture),this._inputs[1].excludedConnectionPointTypes.push($.Matrix),this._inputs[1].excludedConnectionPointTypes.push($.Geometry),this._inputs[1].excludedConnectionPointTypes.push($.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 Xs("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Xs("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case $.Int:case $.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,s=this.max.getConnectedValue(t)||0;return i+Math.random()*(s-i)};break}case $.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||Re.Zero(),s=this.max.getConnectedValue(t)||Re.Zero();return new Re(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y))};break}case $.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||T.Zero(),s=this.max.getConnectedValue(t)||T.Zero();return new T(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 $.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||Dt.Zero(),s=this.max.getConnectedValue(t)||Dt.Zero();return new Dt(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===To.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case To.InstanceID:i=t.getContextualValue(Ci.InstanceID,!0)||0;break;case To.LoopID:i=t.getContextualValue(Ci.LoopID,!0)||0;break}return(this._currentLockId!==i||this.lockMode===To.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${To[this.lockMode]}; -`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}A([ft("LockMode",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:To.None},{label:"LoopID",value:To.LoopID},{label:"InstanceID",value:To.InstanceID}]})],qy.prototype,"lockMode",void 0);j("BABYLON.RandomBlock",qy);class j4 extends Qt{constructor(e){super(e),this.registerInput("offset",$.Vector3,!0,T.Zero()),this.registerInput("scale",$.Float,!0,1),this.registerInput("octaves",$.Float,!0,2,0,16),this.registerInput("roughness",$.Float,!0,.5,0,1),this.registerOutput("output",$.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,a=r===12||r==14?t:s,l=r<4?i:a;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<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,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,a,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*(a*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,a=e.z-s,l=this._fade(r),h=this._fade(n),c=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,a),this._noiseGrad(this._hash(t+1,i,s),r-1,n,a),this._noiseGrad(this._hash(t,i+1,s),r,n-1,a),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,a),this._noiseGrad(this._hash(t,i,s+1),r,n,a-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,a-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,a-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 T(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let a=1,l=1,h=0,c=0;e=ye.Clamp(e,0,15);const u=e|0;for(let _=0;_<=u;_++){const g=this._perlin(n.scale(a));c+=g*l,h+=l,l*=ye.Clamp(t,0,1),a*=2}const d=e-Math.floor(e);if(d==0)return c/h;const f=this._perlin(n.scale(a));let p=c+f*l;return c/=h,p/=h+l,(1-d)*c+d*p}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Ci.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)}}}j("BABYLON.NoiseBlock",j4);class jy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",$.Geometry),this.registerInput("geometry1",$.Geometry,!0),this.registerInput("geometry2",$.Geometry,!0),this.registerInput("geometry3",$.Geometry,!0),this.registerInput("geometry4",$.Geometry,!0),this.registerOutput("output",$.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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jy.prototype,"evaluateContext",void 0);j("BABYLON.MergeGeometryBlock",jy);class Qy extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",$.Geometry,!0),this.registerInput("geometry1",$.Geometry,!0),this.registerInput("geometry2",$.Geometry,!0),this.registerInput("geometry3",$.Geometry,!0),this.registerInput("geometry4",$.Geometry,!0),this.registerInput("geometry5",$.Geometry,!0),this.registerInput("geometry6",$.Geometry,!0),this.registerInput("geometry7",$.Geometry,!0),this.registerInput("geometry8",$.Geometry,!0),this.registerInput("geometry9",$.Geometry,!0),this.registerOutput("output",$.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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Qy.prototype,"evaluateContext",void 0);j("BABYLON.GeometryCollectionBlock",Qy);class Q4 extends Qt{constructor(e){super(e),this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.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)}}j("BABYLON.GeometryElbowBlock",Q4);class Z4 extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.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=[]),De.ComputeNormals(t.positions,t.indices,t.normals),t}}}j("BABYLON.ComputeNormalsBlock",Z4);class J4 extends Qt{constructor(e){super(e),this.registerInput("xyzw ",$.Vector4,!0),this.registerInput("xyz ",$.Vector3,!0),this.registerInput("xy ",$.Vector2,!0),this.registerInput("zw ",$.Vector2,!0),this.registerInput("x ",$.Float,!0),this.registerInput("y ",$.Float,!0),this.registerInput("z ",$.Float,!0),this.registerInput("w ",$.Float,!0),this.registerOutput("xyzw",$.Vector4),this.registerOutput("xyz",$.Vector3),this.registerOutput("xy",$.Vector2),this.registerOutput("zw",$.Vector2),this.registerOutput("x",$.Float),this.registerOutput("y",$.Float),this.registerOutput("z",$.Float),this.registerOutput("w",$.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,a=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this.xyzwOut,u=this.xyzOut,d=this.xyOut,f=this.zwOut,p=this.xOut,_=this.yOut,g=this.zOut,v=this.wOut,E=C=>{if(h.isConnected)return h.getConnectedValue(C);let S=0,b=0,R=0,I=0;if(t.isConnected&&(S=t.getConnectedValue(C)),i.isConnected&&(b=i.getConnectedValue(C)),s.isConnected&&(R=s.getConnectedValue(C)),r.isConnected&&(I=r.getConnectedValue(C)),n.isConnected){const N=n.getConnectedValue(C);N&&(S=N.x,b=N.y)}if(a.isConnected){const N=a.getConnectedValue(C);N&&(R=N.x,I=N.y)}if(l.isConnected){const N=l.getConnectedValue(C);N&&(S=N.x,b=N.y,R=N.z)}return new Dt(S,b,R,I)};c._storedFunction=C=>E(C),u._storedFunction=C=>{const S=E(C);return new T(S.x,S.y,S.z)},d._storedFunction=C=>{const S=E(C);return new Re(S.x,S.y)},f._storedFunction=C=>{const S=E(C);return new Re(S.z,S.w)},p._storedFunction=C=>E(C).x,_._storedFunction=C=>E(C).y,g._storedFunction=C=>E(C).z,v._storedFunction=C=>E(C).w}}j("BABYLON.VectorConverterBlock",J4);class eW extends Qt{constructor(e){super(e),this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Float),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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()}}j("BABYLON.NormalizeVectorBlock",eW);class Zy extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("id",$.Int,!0,0),this.registerOutput("output",$.Geometry),this.id.acceptedConnectionPointTypes.push($.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 g_;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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zy.prototype,"evaluateContext",void 0);j("BABYLON.SetMaterialIDBlock",Zy);var Si;(function(o){o[o.Cos=0]="Cos",o[o.Sin=1]="Sin",o[o.Abs=2]="Abs",o[o.Exp=3]="Exp",o[o.Round=4]="Round",o[o.Floor=5]="Floor",o[o.Ceiling=6]="Ceiling",o[o.Sqrt=7]="Sqrt",o[o.Log=8]="Log",o[o.Tan=9]="Tan",o[o.ArcTan=10]="ArcTan",o[o.ArcCos=11]="ArcCos",o[o.ArcSin=12]="ArcSin",o[o.Sign=13]="Sign",o[o.Negate=14]="Negate",o[o.OneMinus=15]="OneMinus",o[o.Reciprocal=16]="Reciprocal",o[o.ToDegrees=17]="ToDegrees",o[o.ToRadians=18]="ToRadians"})(Si||(Si={}));class Jy extends Qt{constructor(e){super(e),this.operation=Si.Cos,this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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 Si.Cos:{t=i=>Math.cos(i);break}case Si.Sin:{t=i=>Math.sin(i);break}case Si.Abs:{t=i=>Math.abs(i);break}case Si.Exp:{t=i=>Math.exp(i);break}case Si.Round:{t=i=>Math.round(i);break}case Si.Floor:{t=i=>Math.floor(i);break}case Si.Ceiling:{t=i=>Math.ceil(i);break}case Si.Sqrt:{t=i=>Math.sqrt(i);break}case Si.Log:{t=i=>Math.log(i);break}case Si.Tan:{t=i=>Math.tan(i);break}case Si.ArcTan:{t=i=>Math.atan(i);break}case Si.ArcCos:{t=i=>Math.acos(i);break}case Si.ArcSin:{t=i=>Math.asin(i);break}case Si.Sign:{t=i=>Math.sign(i);break}case Si.Negate:{t=i=>-i;break}case Si.OneMinus:{t=i=>1-i;break}case Si.Reciprocal:{t=i=>1/i;break}case Si.ToRadians:{t=i=>i*Math.PI/180;break}case Si.ToDegrees:{t=i=>i*180/Math.PI;break}}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case $.Int:case $.Float:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return t(s)};break}case $.Vector2:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Re(t(s.x),t(s.y))};break}case $.Vector3:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new T(t(s.x),t(s.y),t(s.z))};break}case $.Vector4:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Dt(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.${Si[this.operation]}; -`}}A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Si.Cos},{label:"Sin",value:Si.Sin},{label:"Abs",value:Si.Abs},{label:"Exp",value:Si.Exp},{label:"Round",value:Si.Round},{label:"Floor",value:Si.Floor},{label:"Ceiling",value:Si.Ceiling},{label:"Sqrt",value:Si.Sqrt},{label:"Log",value:Si.Log},{label:"Tan",value:Si.Tan},{label:"ArcTan",value:Si.ArcTan},{label:"ArcCos",value:Si.ArcCos},{label:"ArcSin",value:Si.ArcSin},{label:"Sign",value:Si.Sign},{label:"Negate",value:Si.Negate},{label:"OneMinus",value:Si.OneMinus},{label:"Reciprocal",value:Si.Reciprocal},{label:"ToDegrees",value:Si.ToDegrees},{label:"ToRadians",value:Si.ToRadians}]})],Jy.prototype,"operation",void 0);j("BABYLON.GeometryTrigonometryBlock",Jy);class eA extends Qt{constructor(e){super(e),this._rotationMatrix=new k,this._scalingMatrix=new k,this._translationMatrix=new k,this._scalingRotationMatrix=new k,this._transformMatrix=new k,this.evaluateContext=!0,this.registerInput("value",$.AutoDetect),this.registerInput("matrix",$.Matrix,!0),this.registerInput("translation",$.Vector3,!0,T.Zero()),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Float),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.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),a=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);k.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),k.RotationYawPitchRollToRef(a.y,a.x,a.z,this._rotationMatrix),k.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 $.Geometry:{const n=s.clone();return n.transform(r),n}case $.Vector2:return Re.Transform(s,r);case $.Vector3:return T.TransformCoordinates(s,r);case $.Vector4:return Dt.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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],eA.prototype,"evaluateContext",void 0);j("BABYLON.GeometryTransformBlock",eA);class tW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationX(this.angle.getConnectedValue(t))}}j("BABYLON.RotationXBlock",tW);class iW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationY(this.angle.getConnectedValue(t))}}j("BABYLON.RotationYBlock",iW);class sW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationZ(this.angle.getConnectedValue(t))}}j("BABYLON.RotationZBlock",sW);class rW extends Qt{constructor(e){super(e),this.registerInput("scale",$.Vector3,!1,T.One()),this.registerOutput("matrix",$.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Xs("Scale");e.value=new T(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return k.Scaling(i.x,i.y,i.z)}}}j("BABYLON.ScalingBlock",rW);class nW extends Qt{constructor(e){super(e),this.registerInput("source",$.Vector3,!0,T.Up()),this.registerInput("target",$.Vector3,!0,T.Left()),this.registerOutput("matrix",$.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 k;return i.normalize(),s.normalize(),k.RotationAlignToRef(i,s,r,!0),r}}}j("BABYLON.AlignBlock",nW);class aW extends Qt{constructor(e){super(e),this.registerInput("translation",$.Vector3,!1,T.Zero()),this.registerOutput("matrix",$.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Xs("Translation");e.value=new T(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return k.Translation(i.x,i.y,i.z)}}}j("BABYLON.TranslationBlock",aW);class hT extends Qt{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("density",$.Float,!0,1,0,1),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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 T,a=[];let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexc)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,$.Vector3,T.OneReadOnly),f=this.rotation.getConnectedValue(i)||T.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"}; +`,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],cT.prototype,"evaluateContext",void 0);A([ft("Texture coordinates index",ut.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}]})],cT.prototype,"textureCoordinateIndex",void 0);j("BABYLON.SetUVsBlock",cT);class $y extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("colors",$.Vector4),this.registerOutput("output",$.Geometry)}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=>{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{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._currentIndext.getConnectedValue(r)+i.getConnectedValue(r):e=r=>t.getConnectedValue(r).add(r.adapt(i,t.type));break}case An.Subtract:{s?e=r=>t.getConnectedValue(r)-i.getConnectedValue(r):e=r=>t.getConnectedValue(r).subtract(r.adapt(i,t.type));break}case An.Multiply:{s?e=r=>t.getConnectedValue(r)*i.getConnectedValue(r):e=r=>t.getConnectedValue(r).multiply(r.adapt(i,t.type));break}case An.Divide:{s?e=r=>t.getConnectedValue(r)/i.getConnectedValue(r):e=r=>t.getConnectedValue(r).divide(r.adapt(i,t.type));break}case An.Min:{if(s)e=r=>Math.min(t.getConnectedValue(r),i.getConnectedValue(r));else switch(t.type){case $.Vector2:{e=r=>Re.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector3:{e=r=>T.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector4:{e=r=>Dt.Minimize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}case An.Max:if(s)e=r=>Math.max(t.getConnectedValue(r),i.getConnectedValue(r));else{switch(t.type){case $.Vector2:{e=r=>Re.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector3:{e=r=>T.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}case $.Vector4:{e=r=>Dt.Maximize(t.getConnectedValue(r),r.adapt(i,t.type));break}}break}}this.output._storedFunction=r=>t.type===$.Int?e(r)|0:e(r)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${An[this.operation]}; +`}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:An.Add},{label:"Subtract",value:An.Subtract},{label:"Multiply",value:An.Multiply},{label:"Divide",value:An.Divide},{label:"Max",value:An.Max},{label:"Min",value:An.Min}]})],qy.prototype,"operation",void 0);j("BABYLON.MathBlock",qy);class Z4 extends Qt{constructor(e){super(e),this.registerInput("value",$.AutoDetect),this.registerInput("fromMin",$.Float,!0,0),this.registerInput("fromMax",$.Float,!0,1),this.registerInput("toMin",$.Float,!0,0),this.registerInput("toMax",$.Float,!0,1),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Vector2),this._inputs[0].excludedConnectionPointTypes.push($.Vector3),this._inputs[0].excludedConnectionPointTypes.push($.Vector4),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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),a=(t-i)/(s-i)*(n-r)+r;return this.output.type===$.Int?Math.floor(a):a}}}j("BABYLON.MapRangeBlock",Z4);var mr;(function(o){o[o.Equal=0]="Equal",o[o.NotEqual=1]="NotEqual",o[o.LessThan=2]="LessThan",o[o.GreaterThan=3]="GreaterThan",o[o.LessOrEqual=4]="LessOrEqual",o[o.GreaterOrEqual=5]="GreaterOrEqual",o[o.Xor=6]="Xor",o[o.Or=7]="Or",o[o.And=8]="And"})(mr||(mr={}));class jy extends Qt{constructor(e){super(e),this.test=mr.Equal,this.registerInput("left",$.Float),this.registerInput("right",$.Float,!0,0),this.registerInput("ifTrue",$.AutoDetect,!0,1),this.registerInput("ifFalse",$.AutoDetect,!0,0),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=$.Float,this._inputs[0].acceptedConnectionPointTypes.push($.Int),this._inputs[1].acceptedConnectionPointTypes.push($.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 mr.Equal:r=ye.WithinEpsilon(i,s,$t);break;case mr.NotEqual:r=i!==s;break;case mr.LessThan:r=is;break;case mr.LessOrEqual:r=i<=s;break;case mr.GreaterOrEqual:r=i>=s;break;case mr.Xor:r=!!i&&!s||!i&&!!s;break;case mr.Or:r=!!i||!!s;break;case mr.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.${mr[this.test]}; +`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}A([ft("Test",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:mr.Equal},{label:"NotEqual",value:mr.NotEqual},{label:"LessThan",value:mr.LessThan},{label:"GreaterThan",value:mr.GreaterThan},{label:"LessOrEqual",value:mr.LessOrEqual},{label:"GreaterOrEqual",value:mr.GreaterOrEqual},{label:"Xor",value:mr.Xor},{label:"Or",value:mr.Or},{label:"And",value:mr.And}]})],jy.prototype,"test",void 0);j("BABYLON.ConditionBlock",jy);var To;(function(o){o[o.None=0]="None",o[o.LoopID=1]="LoopID",o[o.InstanceID=2]="InstanceID"})(To||(To={}));class Qy extends Qt{constructor(e){super(e),this._currentLockId=-1,this.lockMode=To.None,this.registerInput("min",$.AutoDetect),this.registerInput("max",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.Texture),this._inputs[1].excludedConnectionPointTypes.push($.Matrix),this._inputs[1].excludedConnectionPointTypes.push($.Geometry),this._inputs[1].excludedConnectionPointTypes.push($.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 Xs("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Xs("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case $.Int:case $.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,s=this.max.getConnectedValue(t)||0;return i+Math.random()*(s-i)};break}case $.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||Re.Zero(),s=this.max.getConnectedValue(t)||Re.Zero();return new Re(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y))};break}case $.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||T.Zero(),s=this.max.getConnectedValue(t)||T.Zero();return new T(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 $.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||Dt.Zero(),s=this.max.getConnectedValue(t)||Dt.Zero();return new Dt(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===To.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case To.InstanceID:i=t.getContextualValue(Ci.InstanceID,!0)||0;break;case To.LoopID:i=t.getContextualValue(Ci.LoopID,!0)||0;break}return(this._currentLockId!==i||this.lockMode===To.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${To[this.lockMode]}; +`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}A([ft("LockMode",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:To.None},{label:"LoopID",value:To.LoopID},{label:"InstanceID",value:To.InstanceID}]})],Qy.prototype,"lockMode",void 0);j("BABYLON.RandomBlock",Qy);class J4 extends Qt{constructor(e){super(e),this.registerInput("offset",$.Vector3,!0,T.Zero()),this.registerInput("scale",$.Float,!0,1),this.registerInput("octaves",$.Float,!0,2,0,16),this.registerInput("roughness",$.Float,!0,.5,0,1),this.registerOutput("output",$.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,a=r===12||r==14?t:s,l=r<4?i:a;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<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,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,a,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*(a*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,a=e.z-s,l=this._fade(r),h=this._fade(n),c=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,a),this._noiseGrad(this._hash(t+1,i,s),r-1,n,a),this._noiseGrad(this._hash(t,i+1,s),r,n-1,a),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,a),this._noiseGrad(this._hash(t,i,s+1),r,n,a-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,a-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,a-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 T(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let a=1,l=1,h=0,c=0;e=ye.Clamp(e,0,15);const u=e|0;for(let _=0;_<=u;_++){const g=this._perlin(n.scale(a));c+=g*l,h+=l,l*=ye.Clamp(t,0,1),a*=2}const d=e-Math.floor(e);if(d==0)return c/h;const f=this._perlin(n.scale(a));let p=c+f*l;return c/=h,p/=h+l,(1-d)*c+d*p}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Ci.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)}}}j("BABYLON.NoiseBlock",J4);class Zy extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",$.Geometry),this.registerInput("geometry1",$.Geometry,!0),this.registerInput("geometry2",$.Geometry,!0),this.registerInput("geometry3",$.Geometry,!0),this.registerInput("geometry4",$.Geometry,!0),this.registerOutput("output",$.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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zy.prototype,"evaluateContext",void 0);j("BABYLON.MergeGeometryBlock",Zy);class Jy extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",$.Geometry,!0),this.registerInput("geometry1",$.Geometry,!0),this.registerInput("geometry2",$.Geometry,!0),this.registerInput("geometry3",$.Geometry,!0),this.registerInput("geometry4",$.Geometry,!0),this.registerInput("geometry5",$.Geometry,!0),this.registerInput("geometry6",$.Geometry,!0),this.registerInput("geometry7",$.Geometry,!0),this.registerInput("geometry8",$.Geometry,!0),this.registerInput("geometry9",$.Geometry,!0),this.registerOutput("output",$.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}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Jy.prototype,"evaluateContext",void 0);j("BABYLON.GeometryCollectionBlock",Jy);class eW extends Qt{constructor(e){super(e),this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.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)}}j("BABYLON.GeometryElbowBlock",eW);class tW extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.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=[]),Oe.ComputeNormals(t.positions,t.indices,t.normals),t}}}j("BABYLON.ComputeNormalsBlock",tW);class iW extends Qt{constructor(e){super(e),this.registerInput("xyzw ",$.Vector4,!0),this.registerInput("xyz ",$.Vector3,!0),this.registerInput("xy ",$.Vector2,!0),this.registerInput("zw ",$.Vector2,!0),this.registerInput("x ",$.Float,!0),this.registerInput("y ",$.Float,!0),this.registerInput("z ",$.Float,!0),this.registerInput("w ",$.Float,!0),this.registerOutput("xyzw",$.Vector4),this.registerOutput("xyz",$.Vector3),this.registerOutput("xy",$.Vector2),this.registerOutput("zw",$.Vector2),this.registerOutput("x",$.Float),this.registerOutput("y",$.Float),this.registerOutput("z",$.Float),this.registerOutput("w",$.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,a=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this.xyzwOut,u=this.xyzOut,d=this.xyOut,f=this.zwOut,p=this.xOut,_=this.yOut,g=this.zOut,v=this.wOut,E=C=>{if(h.isConnected)return h.getConnectedValue(C);let S=0,b=0,R=0,I=0;if(t.isConnected&&(S=t.getConnectedValue(C)),i.isConnected&&(b=i.getConnectedValue(C)),s.isConnected&&(R=s.getConnectedValue(C)),r.isConnected&&(I=r.getConnectedValue(C)),n.isConnected){const N=n.getConnectedValue(C);N&&(S=N.x,b=N.y)}if(a.isConnected){const N=a.getConnectedValue(C);N&&(R=N.x,I=N.y)}if(l.isConnected){const N=l.getConnectedValue(C);N&&(S=N.x,b=N.y,R=N.z)}return new Dt(S,b,R,I)};c._storedFunction=C=>E(C),u._storedFunction=C=>{const S=E(C);return new T(S.x,S.y,S.z)},d._storedFunction=C=>{const S=E(C);return new Re(S.x,S.y)},f._storedFunction=C=>{const S=E(C);return new Re(S.z,S.w)},p._storedFunction=C=>E(C).x,_._storedFunction=C=>E(C).y,g._storedFunction=C=>E(C).z,v._storedFunction=C=>E(C).w}}j("BABYLON.VectorConverterBlock",iW);class sW extends Qt{constructor(e){super(e),this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push($.Float),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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()}}j("BABYLON.NormalizeVectorBlock",sW);class eA extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("id",$.Int,!0,0),this.registerOutput("output",$.Geometry),this.id.acceptedConnectionPointTypes.push($.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 g_;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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],eA.prototype,"evaluateContext",void 0);j("BABYLON.SetMaterialIDBlock",eA);var Si;(function(o){o[o.Cos=0]="Cos",o[o.Sin=1]="Sin",o[o.Abs=2]="Abs",o[o.Exp=3]="Exp",o[o.Round=4]="Round",o[o.Floor=5]="Floor",o[o.Ceiling=6]="Ceiling",o[o.Sqrt=7]="Sqrt",o[o.Log=8]="Log",o[o.Tan=9]="Tan",o[o.ArcTan=10]="ArcTan",o[o.ArcCos=11]="ArcCos",o[o.ArcSin=12]="ArcSin",o[o.Sign=13]="Sign",o[o.Negate=14]="Negate",o[o.OneMinus=15]="OneMinus",o[o.Reciprocal=16]="Reciprocal",o[o.ToDegrees=17]="ToDegrees",o[o.ToRadians=18]="ToRadians"})(Si||(Si={}));class tA extends Qt{constructor(e){super(e),this.operation=Si.Cos,this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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 Si.Cos:{t=i=>Math.cos(i);break}case Si.Sin:{t=i=>Math.sin(i);break}case Si.Abs:{t=i=>Math.abs(i);break}case Si.Exp:{t=i=>Math.exp(i);break}case Si.Round:{t=i=>Math.round(i);break}case Si.Floor:{t=i=>Math.floor(i);break}case Si.Ceiling:{t=i=>Math.ceil(i);break}case Si.Sqrt:{t=i=>Math.sqrt(i);break}case Si.Log:{t=i=>Math.log(i);break}case Si.Tan:{t=i=>Math.tan(i);break}case Si.ArcTan:{t=i=>Math.atan(i);break}case Si.ArcCos:{t=i=>Math.acos(i);break}case Si.ArcSin:{t=i=>Math.asin(i);break}case Si.Sign:{t=i=>Math.sign(i);break}case Si.Negate:{t=i=>-i;break}case Si.OneMinus:{t=i=>1-i;break}case Si.Reciprocal:{t=i=>1/i;break}case Si.ToRadians:{t=i=>i*Math.PI/180;break}case Si.ToDegrees:{t=i=>i*180/Math.PI;break}}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case $.Int:case $.Float:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return t(s)};break}case $.Vector2:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Re(t(s.x),t(s.y))};break}case $.Vector3:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new T(t(s.x),t(s.y),t(s.z))};break}case $.Vector4:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new Dt(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.${Si[this.operation]}; +`}}A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Si.Cos},{label:"Sin",value:Si.Sin},{label:"Abs",value:Si.Abs},{label:"Exp",value:Si.Exp},{label:"Round",value:Si.Round},{label:"Floor",value:Si.Floor},{label:"Ceiling",value:Si.Ceiling},{label:"Sqrt",value:Si.Sqrt},{label:"Log",value:Si.Log},{label:"Tan",value:Si.Tan},{label:"ArcTan",value:Si.ArcTan},{label:"ArcCos",value:Si.ArcCos},{label:"ArcSin",value:Si.ArcSin},{label:"Sign",value:Si.Sign},{label:"Negate",value:Si.Negate},{label:"OneMinus",value:Si.OneMinus},{label:"Reciprocal",value:Si.Reciprocal},{label:"ToDegrees",value:Si.ToDegrees},{label:"ToRadians",value:Si.ToRadians}]})],tA.prototype,"operation",void 0);j("BABYLON.GeometryTrigonometryBlock",tA);class iA extends Qt{constructor(e){super(e),this._rotationMatrix=new k,this._scalingMatrix=new k,this._translationMatrix=new k,this._scalingRotationMatrix=new k,this._transformMatrix=new k,this.evaluateContext=!0,this.registerInput("value",$.AutoDetect),this.registerInput("matrix",$.Matrix,!0),this.registerInput("translation",$.Vector3,!0,T.Zero()),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Float),this._inputs[0].excludedConnectionPointTypes.push($.Matrix),this._inputs[0].excludedConnectionPointTypes.push($.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),a=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);k.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),k.RotationYawPitchRollToRef(a.y,a.x,a.z,this._rotationMatrix),k.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 $.Geometry:{const n=s.clone();return n.transform(r),n}case $.Vector2:return Re.Transform(s,r);case $.Vector3:return T.TransformCoordinates(s,r);case $.Vector4:return Dt.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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iA.prototype,"evaluateContext",void 0);j("BABYLON.GeometryTransformBlock",iA);class rW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationX(this.angle.getConnectedValue(t))}}j("BABYLON.RotationXBlock",rW);class nW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationY(this.angle.getConnectedValue(t))}}j("BABYLON.RotationYBlock",nW);class aW extends Qt{constructor(e){super(e),this.registerInput("angle",$.Float,!1,0),this.registerOutput("matrix",$.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Xs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>k.RotationZ(this.angle.getConnectedValue(t))}}j("BABYLON.RotationZBlock",aW);class oW extends Qt{constructor(e){super(e),this.registerInput("scale",$.Vector3,!1,T.One()),this.registerOutput("matrix",$.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Xs("Scale");e.value=new T(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return k.Scaling(i.x,i.y,i.z)}}}j("BABYLON.ScalingBlock",oW);class lW extends Qt{constructor(e){super(e),this.registerInput("source",$.Vector3,!0,T.Up()),this.registerInput("target",$.Vector3,!0,T.Left()),this.registerOutput("matrix",$.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 k;return i.normalize(),s.normalize(),k.RotationAlignToRef(i,s,r,!0),r}}}j("BABYLON.AlignBlock",lW);class hW extends Qt{constructor(e){super(e),this.registerInput("translation",$.Vector3,!1,T.Zero()),this.registerOutput("matrix",$.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Xs("Translation");e.value=new T(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return k.Translation(i.x,i.y,i.z)}}}j("BABYLON.TranslationBlock",hW);class uT extends Qt{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("density",$.Float,!0,1,0,1),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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 T,a=[];let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexc)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,$.Vector3,T.OneReadOnly),f=this.rotation.getConnectedValue(i)||T.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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],hT.prototype,"evaluateContext",void 0);A([ft("Remove duplicated positions",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],hT.prototype,"removeDuplicatedPositions",void 0);j("BABYLON.InstantiateOnVerticesBlock",hT);class tA extends Qt{constructor(e){super(e),this._currentPosition=new T,this._currentUV=new Re,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this._tempVector0=new T,this._tempVector1=new T,this._uv0=new Re,this._uv1=new Re,this._uv2=new Re,this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,256),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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(),T.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,a=r/n;let l=0;const h=[];let c=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=r);_++){let g=Math.random(),v=Math.random();if(g>v){const R=g;g=v,v=R}const E=g,C=v-g,S=1-E-C;if(this._currentPosition.set(E*this._vertex0.x+C*this._vertex1.x+S*this._vertex2.x,E*this._vertex0.y+C*this._vertex1.y+S*this._vertex2.y,E*this._vertex0.z+C*this._vertex1.z+S*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(E*this._uv0.x+C*this._uv1.x+S*this._uv2.x,E*this._uv0.y+C*this._uv1.y+S*this._uv2.y),s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0){l-=a;continue}const b=s.clone();if(this.matrix.isConnected){const R=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(b,this._currentPosition,R,h)}else{const R=i.adaptInput(this.scaling,$.Vector3,T.OneReadOnly),I=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(b,this._currentPosition,I,R,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tA.prototype,"evaluateContext",void 0);j("BABYLON.InstantiateOnFacesBlock",tA);class iA extends Qt{constructor(e){super(e),this._currentPosition=new T,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,256),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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=[],a=Ad(this._vertexData.positions,0,this._vertexData.positions.length/3),l=a.minimum,h=a.maximum,c=new T(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let d=0;d0&&p++}if(p%2===0){d--;continue}if(s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0)continue;const _=s.clone();if(this.matrix.isConnected){const g=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,g,n)}else{const g=i.adaptInput(this.scaling,$.Vector3,T.OneReadOnly),v=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(_,this._currentPosition,v,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iA.prototype,"evaluateContext",void 0);j("BABYLON.InstantiateOnVolumeBlock",iA);class km extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,1),this.registerOutput("output",$.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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],km.prototype,"evaluateContext",void 0);class oW extends km{constructor(e){super(e),this.registerInput("matrix",$.Matrix,!0),this.registerInput("position",$.Vector3,!0,T.Zero()),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.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{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=k.Identity(),a=T.Zero(),l=T.Zero(),h=T.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=k.Identity(),a=k.Identity(),l=k.Identity(),h=T.Zero(),c=T.Zero(),u=T.Zero();for(this._currentIndex=0;this._currentIndexthis.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}}j("BABYLON.IntFloatConverterBlock",cW);class uW extends Qt{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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);return s==null?(this.log.push("null"),s):(this.log.push(s.toString()),s)};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}j("BABYLON.DebugBlock",uW);class dW extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.Geometry),this.registerOutput("id",$.Int),this.registerOutput("collectionId",$.Int),this.registerOutput("verticesCount",$.Int),this.registerOutput("facesCount",$.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)}}j("BABYLON.GeometryInfoBlock",dW);var Wo;(function(o){o[o.Spherical=0]="Spherical",o[o.Cylindrical=1]="Cylindrical",o[o.Cubic=2]="Cubic"})(Wo||(Wo={}));class sA extends Qt{constructor(e){super(e),this.mapping=Wo.Spherical,this.registerInput("position",$.Vector3),this.registerInput("normal",$.Vector3),this.registerInput("center",$.Vector3,!0,T.Zero()),this.registerOutput("uv",$.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=T.Zero(),t=i=>{const s=this.position.getConnectedValue(i)||T.Zero(),r=this.normal.getConnectedValue(i)||T.Zero(),n=this.center.getConnectedValue(i),a=Re.Zero();switch(this.mapping){case Wo.Spherical:{s.subtractToRef(n,e);const l=e.length();l>0&&(a.x=Math.acos(e.y/l)/Math.PI,(e.x!==0||e.z!==0)&&(a.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case Wo.Cylindrical:{s.subtractToRef(n,e);const l=e.length();l>0&&(a.x=Math.atan2(e.x/l,e.z/l)/(Math.PI*2),a.y=(e.y+1)/2);break}case Wo.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),a.x=(d+1)/2,a.y=(f+1)/2}}return a};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Wo[this.mapping]}; -`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}A([ft("Mapping",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Wo.Spherical},{label:"Cylindrical",value:Wo.Cylindrical},{label:"Cubic",value:Wo.Cubic}]})],sA.prototype,"mapping",void 0);j("BABYLON.MappingBlock",sA);class fW extends Qt{constructor(e){super(e),this.registerInput("matrix0",$.Matrix),this.registerInput("matrix1",$.Matrix),this.registerOutput("output",$.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)}}}j("BABYLON.MatrixComposeBlock",fW);class pW extends Qt{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",$.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)}}j("BABYLON.TeleportInBlock",pW);class _W extends Qt{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",$.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 e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}j("BABYLON.TeleportOutBlock",_W);class rA extends Qt{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",$.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{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();n2.GetTextureDataAsync(e,s.width,s.height).then(async r=>{const n=new Float32Array(r.length);for(let a=0;a=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),a=Math.floor(r*(i.width-1)),l=Math.floor(n*(i.height-1)),h=a+i.width*l;return Dt.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}}A([ft("Clamp Coordinates",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],nA.prototype,"clampCoordinates",void 0);j("BABYLON.GeometryTextureFetchBlock",nA);class mW extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("min",$.Vector3),this.registerOutput("max",$.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?Ad(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Ad(t.positions,0,t.positions.length/3).maximum:null}}}j("BABYLON.BoundingBlock",mW);var Ho;(function(o){o[o.Intersect=0]="Intersect",o[o.Subtract=1]="Subtract",o[o.Union=2]="Union"})(Ho||(Ho={}));class cT extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.operation=Ho.Intersect,this.registerInput("geometry0",$.Geometry),this.registerInput("geometry1",$.Geometry),this.registerOutput("output",$.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 a=Vo.FromVertexData(s),l=Vo.FromVertexData(r);let h;switch(this.operation){case Ho.Intersect:h=a.intersect(l);break;case Ho.Subtract:h=a.subtract(l);break;case Ho.Union:h=a.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"}; +`,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],uT.prototype,"evaluateContext",void 0);A([ft("Remove duplicated positions",ut.Boolean,"ADVANCED",{notifiers:{update:!0}})],uT.prototype,"removeDuplicatedPositions",void 0);j("BABYLON.InstantiateOnVerticesBlock",uT);class sA extends Qt{constructor(e){super(e),this._currentPosition=new T,this._currentUV=new Re,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this._tempVector0=new T,this._tempVector1=new T,this._uv0=new Re,this._uv1=new Re,this._uv2=new Re,this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,256),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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(),T.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,a=r/n;let l=0;const h=[];let c=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=r);_++){let g=Math.random(),v=Math.random();if(g>v){const R=g;g=v,v=R}const E=g,C=v-g,S=1-E-C;if(this._currentPosition.set(E*this._vertex0.x+C*this._vertex1.x+S*this._vertex2.x,E*this._vertex0.y+C*this._vertex1.y+S*this._vertex2.y,E*this._vertex0.z+C*this._vertex1.z+S*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(E*this._uv0.x+C*this._uv1.x+S*this._uv2.x,E*this._uv0.y+C*this._uv1.y+S*this._uv2.y),s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0){l-=a;continue}const b=s.clone();if(this.matrix.isConnected){const R=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(b,this._currentPosition,R,h)}else{const R=i.adaptInput(this.scaling,$.Vector3,T.OneReadOnly),I=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(b,this._currentPosition,I,R,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],sA.prototype,"evaluateContext",void 0);j("BABYLON.InstantiateOnFacesBlock",sA);class rA extends Qt{constructor(e){super(e),this._currentPosition=new T,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this.evaluateContext=!0,this.registerInput("geometry",$.Geometry),this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,256),this.registerInput("matrix",$.Matrix,!0),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.Float),this.registerOutput("output",$.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=[],a=Rd(this._vertexData.positions,0,this._vertexData.positions.length/3),l=a.minimum,h=a.maximum,c=new T(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let d=0;d0&&p++}if(p%2===0){d--;continue}if(s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0)continue;const _=s.clone();if(this.matrix.isConnected){const g=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,g,n)}else{const g=i.adaptInput(this.scaling,$.Vector3,T.OneReadOnly),v=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(_,this._currentPosition,v,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rA.prototype,"evaluateContext",void 0);j("BABYLON.InstantiateOnVolumeBlock",rA);class km extends Qt{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",$.Geometry,!0),this.registerInput("count",$.Int,!0,1),this.registerOutput("output",$.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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],km.prototype,"evaluateContext",void 0);class cW extends km{constructor(e){super(e),this.registerInput("matrix",$.Matrix,!0),this.registerInput("position",$.Vector3,!0,T.Zero()),this.registerInput("rotation",$.Vector3,!0,T.Zero()),this.registerInput("scaling",$.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push($.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{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=k.Identity(),a=T.Zero(),l=T.Zero(),h=T.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=k.Identity(),a=k.Identity(),l=k.Identity(),h=T.Zero(),c=T.Zero(),u=T.Zero();for(this._currentIndex=0;this._currentIndexthis.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}}j("BABYLON.IntFloatConverterBlock",fW);class pW extends Qt{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",$.AutoDetect),this.registerOutput("output",$.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push($.Geometry),this._inputs[0].excludedConnectionPointTypes.push($.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);return s==null?(this.log.push("null"),s):(this.log.push(s.toString()),s)};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}j("BABYLON.DebugBlock",pW);class _W extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("output",$.Geometry),this.registerOutput("id",$.Int),this.registerOutput("collectionId",$.Int),this.registerOutput("verticesCount",$.Int),this.registerOutput("facesCount",$.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)}}j("BABYLON.GeometryInfoBlock",_W);var Wo;(function(o){o[o.Spherical=0]="Spherical",o[o.Cylindrical=1]="Cylindrical",o[o.Cubic=2]="Cubic"})(Wo||(Wo={}));class nA extends Qt{constructor(e){super(e),this.mapping=Wo.Spherical,this.registerInput("position",$.Vector3),this.registerInput("normal",$.Vector3),this.registerInput("center",$.Vector3,!0,T.Zero()),this.registerOutput("uv",$.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=T.Zero(),t=i=>{const s=this.position.getConnectedValue(i)||T.Zero(),r=this.normal.getConnectedValue(i)||T.Zero(),n=this.center.getConnectedValue(i),a=Re.Zero();switch(this.mapping){case Wo.Spherical:{s.subtractToRef(n,e);const l=e.length();l>0&&(a.x=Math.acos(e.y/l)/Math.PI,(e.x!==0||e.z!==0)&&(a.y=Math.atan2(e.x,e.z)/(Math.PI*2)));break}case Wo.Cylindrical:{s.subtractToRef(n,e);const l=e.length();l>0&&(a.x=Math.atan2(e.x/l,e.z/l)/(Math.PI*2),a.y=(e.y+1)/2);break}case Wo.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),a.x=(d+1)/2,a.y=(f+1)/2}}return a};this.uv._storedFunction=i=>t(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Wo[this.mapping]}; +`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}A([ft("Mapping",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Wo.Spherical},{label:"Cylindrical",value:Wo.Cylindrical},{label:"Cubic",value:Wo.Cubic}]})],nA.prototype,"mapping",void 0);j("BABYLON.MappingBlock",nA);class mW extends Qt{constructor(e){super(e),this.registerInput("matrix0",$.Matrix),this.registerInput("matrix1",$.Matrix),this.registerOutput("output",$.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)}}}j("BABYLON.MatrixComposeBlock",mW);class gW extends Qt{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",$.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)}}j("BABYLON.TeleportInBlock",gW);class vW extends Qt{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",$.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 e,t;const i=super.serialize();return i.entryPoint=(t=(e=this.entryPoint)===null||e===void 0?void 0:e.uniqueId)!==null&&t!==void 0?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}j("BABYLON.TeleportOutBlock",vW);class aA extends Qt{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",$.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{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();l2.GetTextureDataAsync(e,s.width,s.height).then(async r=>{const n=new Float32Array(r.length);for(let a=0;a=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),a=Math.floor(r*(i.width-1)),l=Math.floor(n*(i.height-1)),h=a+i.width*l;return Dt.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}}A([ft("Clamp Coordinates",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],oA.prototype,"clampCoordinates",void 0);j("BABYLON.GeometryTextureFetchBlock",oA);class xW extends Qt{constructor(e){super(e),this.registerInput("geometry",$.Geometry),this.registerOutput("min",$.Vector3),this.registerOutput("max",$.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?Rd(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Rd(t.positions,0,t.positions.length/3).maximum:null}}}j("BABYLON.BoundingBlock",xW);var Ho;(function(o){o[o.Intersect=0]="Intersect",o[o.Subtract=1]="Subtract",o[o.Union=2]="Union"})(Ho||(Ho={}));class dT extends Qt{constructor(e){super(e),this.evaluateContext=!1,this.operation=Ho.Intersect,this.registerInput("geometry0",$.Geometry),this.registerInput("geometry1",$.Geometry),this.registerOutput("output",$.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 a=Vo.FromVertexData(s),l=Vo.FromVertexData(r);let h;switch(this.operation){case Ho.Intersect:h=a.intersect(l);break;case Ho.Subtract:h=a.subtract(l);break;case Ho.Union:h=a.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.${Ho[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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],cT.prototype,"evaluateContext",void 0);A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Ho.Intersect},{label:"Subtract",value:Ho.Subtract},{label:"Union",value:Ho.Union}]})],cT.prototype,"operation",void 0);j("BABYLON.BooleanGeometryBlock",cT);re.OfflineProviderFactory=(o,e,t=!1)=>new bn(o,e,t);class bn{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=bn._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,bn.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,fe.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 a=new URL(this._currentSceneUrl);return a.pathname+=".manifest",a.toString()}}catch{}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Hs;navigator.onLine&&(s=!0,r=r+(r.match(/\?/)==null?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",()=>{if(n.status===200||bn._ValidateXHRData(n,1))try{const a=JSON.parse(n.response);this._enableSceneOffline=a.enableSceneOffline,this._enableTexturesOffline=a.enableTexturesOffline&&bn._IsUASupportingBlobStorage,a.version&&!isNaN(parseInt(a.version))&&(this._manifestVersionFound=a.version),e(!0)}catch{t()}else t()},!1),n.addEventListener("error",()=>{if(s){s=!1;const a=i();n.open("GET",a),n.send()}else t()},!1);try{n.send()}catch{G.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=()=>{G.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){G.Error("Error while creating object stores. Exception: "+n.message),i()}}}}loadImage(e,t){const i=bn._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 a;s&&typeof URL=="function"?(a=URL.createObjectURL(s.data),t.onerror=()=>{G.Error("Error loading image from blob URL: "+a+" switching back to web url: "+e),t.src=e},t.src=a):i()};const n=r.objectStore("textures").get(e);n.onsuccess=a=>{s=a.target.result},n.onerror=()=>{G.Error("Error loading texture "+e+" from DB."),t.src=e}}else G.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(bn._IsUASupportingBlobStorage){const r=new Hs;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 a={textureUrl:e,data:i};try{const l=n.objectStore("textures").put(a);l.onsuccess=()=>{},l.onerror=()=>{s()}}catch(l){l.code===25&&(bn._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{G.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else G.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=a=>{s=a.target.result},n.onerror=()=>{G.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(r){G.Error("Error while accessing 'versions' object store (READ OP). Exception: "+r.message),t(-1)}}else G.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 a=n.target.error;a&&a.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=()=>{G.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){G.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=bn._ReturnFullUrlLocation(e),a=()=>{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,a):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 a=n.objectStore(s).get(e);a.onsuccess=l=>{r=l.target.result},a.onerror=()=>{G.Error("Error loading file "+e+" from DB."),i()}}else G.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 a=new Hs;let l;a.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),s&&(a.responseType="arraybuffer"),i&&(a.onprogress=i),a.addEventListener("load",()=>{if(a.status===200||a.status<400&&bn._ValidateXHRData(a,s?6:1))if(l=s?a.response:a.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=()=>{G.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else a.status>=400&&r?r(a):t()},!1),a.addEventListener("error",()=>{G.Error("error on XHR request."),r&&r()},!1),a.send()}else G.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=Lm(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}}bn._IsUASupportingBlobStorage=!0;bn.IDBStorageEnabled=!1;bn._ParseURL=o=>{const e=document.createElement("a");e.href=o;const t=o.substring(0,o.lastIndexOf("#")),i=o.substring(t.lastIndexOf("/")+1,o.length);return o.substring(0,o.indexOf(i,0))};bn._ReturnFullUrlLocation=o=>o.indexOf("http:/")===-1&&o.indexOf("https:/")===-1&&typeof window<"u"?bn._ParseURL(window.location.href)+o:o;class aA{_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 gW="gpuUpdateParticlesPixelShader",vW=`#version 300 es +`,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)}}A([ft("Evaluate context",ut.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],dT.prototype,"evaluateContext",void 0);A([ft("Operation",ut.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Ho.Intersect},{label:"Subtract",value:Ho.Subtract},{label:"Union",value:Ho.Union}]})],dT.prototype,"operation",void 0);j("BABYLON.BooleanGeometryBlock",dT);re.OfflineProviderFactory=(o,e,t=!1)=>new yn(o,e,t);class yn{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=yn._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,yn.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,fe.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 a=new URL(this._currentSceneUrl);return a.pathname+=".manifest",a.toString()}}catch{}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Hs;navigator.onLine&&(s=!0,r=r+(r.match(/\?/)==null?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",()=>{if(n.status===200||yn._ValidateXHRData(n,1))try{const a=JSON.parse(n.response);this._enableSceneOffline=a.enableSceneOffline,this._enableTexturesOffline=a.enableTexturesOffline&&yn._IsUASupportingBlobStorage,a.version&&!isNaN(parseInt(a.version))&&(this._manifestVersionFound=a.version),e(!0)}catch{t()}else t()},!1),n.addEventListener("error",()=>{if(s){s=!1;const a=i();n.open("GET",a),n.send()}else t()},!1);try{n.send()}catch{G.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=()=>{G.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){G.Error("Error while creating object stores. Exception: "+n.message),i()}}}}loadImage(e,t){const i=yn._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 a;s&&typeof URL=="function"?(a=URL.createObjectURL(s.data),t.onerror=()=>{G.Error("Error loading image from blob URL: "+a+" switching back to web url: "+e),t.src=e},t.src=a):i()};const n=r.objectStore("textures").get(e);n.onsuccess=a=>{s=a.target.result},n.onerror=()=>{G.Error("Error loading texture "+e+" from DB."),t.src=e}}else G.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(yn._IsUASupportingBlobStorage){const r=new Hs;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 a={textureUrl:e,data:i};try{const l=n.objectStore("textures").put(a);l.onsuccess=()=>{},l.onerror=()=>{s()}}catch(l){l.code===25&&(yn._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{G.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else G.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=a=>{s=a.target.result},n.onerror=()=>{G.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(r){G.Error("Error while accessing 'versions' object store (READ OP). Exception: "+r.message),t(-1)}}else G.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 a=n.target.error;a&&a.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=()=>{G.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){G.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=yn._ReturnFullUrlLocation(e),a=()=>{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,a):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 a=n.objectStore(s).get(e);a.onsuccess=l=>{r=l.target.result},a.onerror=()=>{G.Error("Error loading file "+e+" from DB."),i()}}else G.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 a=new Hs;let l;a.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),s&&(a.responseType="arraybuffer"),i&&(a.onprogress=i),a.addEventListener("load",()=>{if(a.status===200||a.status<400&&yn._ValidateXHRData(a,s?6:1))if(l=s?a.response:a.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=()=>{G.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else a.status>=400&&r?r(a):t()},!1),a.addEventListener("error",()=>{G.Error("error on XHR request."),r&&r()},!1),a.send()}else G.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=Lm(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}}yn._IsUASupportingBlobStorage=!0;yn.IDBStorageEnabled=!1;yn._ParseURL=o=>{const e=document.createElement("a");e.href=o;const t=o.substring(0,o.lastIndexOf("#")),i=o.substring(t.lastIndexOf("/")+1,o.length);return o.substring(0,o.indexOf(i,0))};yn._ReturnFullUrlLocation=o=>o.indexOf("http:/")===-1&&o.indexOf("https:/")===-1&&typeof window<"u"?yn._ParseURL(window.location.href)+o:o;class lA{_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 TW="gpuUpdateParticlesPixelShader",EW=`#version 300 es void main() {discard;} -`;ne.ShadersStore[gW]=vW;const xW="gpuUpdateParticlesVertexShader",TW=`#version 300 es +`;ne.ShadersStore[TW]=EW;const SW="gpuUpdateParticlesVertexShader",CW=`#version 300 es #define PI 3.14159 uniform float currentCount;uniform float timeDelta;uniform float stopFactor; #ifndef LOCAL @@ -9533,7 +9533,7 @@ float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos. else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} outCellIndex=float(int(cellInfos.x+ratio*dist)); #endif -}}`;ne.ShadersStore[xW]=TW;class EW{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,t;return(t=(e=this._updateEffect)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!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 Wh&&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 ji("gpuUpdateParticles",this._updateEffectOptions,this._engine),new aA(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, +}}`;ne.ShadersStore[SW]=CW;class bW{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,t;return(t=(e=this._updateEffect)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!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 Hh&&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 ji("gpuUpdateParticles",this._updateEffectOptions,this._engine),new lA(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, age : f32, size : vec3, life : f32, @@ -9801,8 +9801,8 @@ else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); #endif }} -`;ne.ShadersStoreWGSL[SW]=CW;class bW{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,t;return(t=(e=this._updateComputeShader)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!1}createUpdateBuffer(e){var t;const i={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&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new gu("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split(` -`)}),(t=this._simParamsComputeShader)===null||t===void 0||t.dispose(),this._simParamsComputeShader=new it(this._engine),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 aA(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new xF(this._engine,e.length*4,11);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;te){i(t[0],t[0],1);return}for(let r=0;r=n.gradient&&e<=a.gradient){const l=(e-n.gradient)/(a.gradient-n.gradient);i(n,a,l);return}}const s=t.length-1;i(t[s],t[s],1)}}class Bd{constructor(e){this.particleSystem=e,this.position=T.Zero(),this.direction=T.Zero(),this.color=new Ze(0,0,0,0),this.colorStep=new Ze(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Re(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ze(0,0,0,0),this._currentColor2=new Ze(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=Bd._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=ye.Clamp(e*t%this.lifeTime/this.lifeTime):s=ye.Clamp(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=K.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,K.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(K.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Bd._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 Dt(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()))}}Bd._Count=0;var Vd;(function(o){o[o.ATTACHED=0]="ATTACHED",o[o.END=1]="END"})(Vd||(Vd={}));class nh{constructor(e){if(this.particleSystem=e,this.type=Vd.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Ds("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new T;else if(e instanceof T)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Ds("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new nh(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 xt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new nh(nh._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()}}const AW="particlesPixelShader",RW=`#ifdef LOGARITHMICDEPTH +`;ne.ShadersStoreWGSL[yW]=AW;class RW{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,t;return(t=(e=this._updateComputeShader)===null||e===void 0?void 0:e.isReady())!==null&&t!==void 0?t:!1}createUpdateBuffer(e){var t;const i={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&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new gu("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split(` +`)}),(t=this._simParamsComputeShader)===null||t===void 0||t.dispose(),this._simParamsComputeShader=new it(this._engine),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 lA(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new SF(this._engine,e.length*4,11);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;te){i(t[0],t[0],1);return}for(let r=0;r=n.gradient&&e<=a.gradient){const l=(e-n.gradient)/(a.gradient-n.gradient);i(n,a,l);return}}const s=t.length-1;i(t[s],t[s],1)}}let uA=class qv{constructor(e){this.particleSystem=e,this.position=T.Zero(),this.direction=T.Zero(),this.color=new Ze(0,0,0,0),this.colorStep=new Ze(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Re(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ze(0,0,0,0),this._currentColor2=new Ze(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=qv._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=ye.Clamp(e*t%this.lifeTime/this.lifeTime):s=ye.Clamp(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=K.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,K.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(K.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=qv._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 Dt(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()))}};uA._Count=0;var Vd;(function(o){o[o.ATTACHED=0]="ATTACHED",o[o.END=1]="END"})(Vd||(Vd={}));class ah{constructor(e){if(this.particleSystem=e,this.type=Vd.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Ds("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new T;else if(e instanceof T)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Ds("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new ah(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 xt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new ah(ah._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()}}const PW="particlesPixelShader",MW=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; @@ -9835,7 +9835,7 @@ baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseCo #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[AW]=RW;const IW="particlesVertexShader",PW=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +}`;ne.ShadersStore[PW]=MW;const DW="particlesVertexShader",OW=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; #ifdef ANIMATESHEET attribute float cellIndex; #endif @@ -9906,10 +9906,10 @@ vec4 worldPos=vec4(vPositionW,1.0); #include #include #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[IW]=PW;class Xt extends yo{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Or(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 he),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=k.Identity(),this._inheritedVelocityOffset=new T,this.onDisposeObservable=new he,this.onStoppedObservable=new he,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ze(0,0,0,0),this._colorDiff=new Ze(0,0,0,0),this._scaledDirection=T.Zero(),this._scaledGravity=T.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=l=>{const h=this._particles.pop();h!==l&&h.copyTo(l),this._stockParticles.push(h)},this._createParticle=()=>{let l;if(this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new Bd(this),this._subEmitters&&this._subEmitters.length>0){const h=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];l._attachedSubEmitters=[],h.forEach(c=>{if(c.type===Vd.ATTACHED){const u=c.clone();l._attachedSubEmitters.push(u),u.particleSystem.start()}})}return l},this._emitFromParticle=l=>{if(!this._subEmitters||this._subEmitters.length===0)return;const h=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[h].forEach(c=>{if(c.type===Vd.END){const u=c.clone();l._inheritParticleInfoToSubEmitter(u),u.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(u.particleSystem),u.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,!i||i.getClassName()==="Scene"?(this._scene=i||ht.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=k.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Or(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new zh;let a=null;this.updateFunction=l=>{var h;let c=null;this.noiseTexture&&(c=this.noiseTexture.getSize(),(h=this.noiseTexture.getContent())===null||h===void 0||h.then(d=>{a=d}));const u=l===this._particles;for(let d=0;df.lifeTime){const E=f.age-_;p=(f.lifeTime-_)*p/E,f.age=f.lifeTime}const g=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?ta.GetCurrentGradient(g,this._colorGradients,(E,C,S)=>{E!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),C.getColorToRef(f._currentColor2),f._currentColorGradient=E),Ze.LerpToRef(f._currentColor1,f._currentColor2,S,f.color)}):(f.colorStep.scaleToRef(p,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&ta.GetCurrentGradient(g,this._angularSpeedGradients,(E,C,S)=>{E!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=C.getFactor(),f._currentAngularSpeedGradient=E),f.angularSpeed=ye.Lerp(f._currentAngularSpeed1,f._currentAngularSpeed2,S)}),f.angle+=f.angularSpeed*p;let v=p;if(this._velocityGradients&&this._velocityGradients.length>0&&ta.GetCurrentGradient(g,this._velocityGradients,(E,C,S)=>{E!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=C.getFactor(),f._currentVelocityGradient=E),v*=ye.Lerp(f._currentVelocity1,f._currentVelocity2,S)}),f.direction.scaleToRef(v,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&ta.GetCurrentGradient(g,this._limitVelocityGradients,(E,C,S)=>{E!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=C.getFactor(),f._currentLimitVelocityGradient=E);const b=ye.Lerp(f._currentLimitVelocity1,f._currentLimitVelocity2,S);f.direction.length()>b&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&ta.GetCurrentGradient(g,this._dragGradients,(E,C,S)=>{E!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=C.getFactor(),f._currentDragGradient=E);const b=ye.Lerp(f._currentDrag1,f._currentDrag2,S);this._scaledDirection.scaleInPlace(1-b)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),T.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),a&&c&&f._randomNoiseCoordinates1){const E=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,c.width,c.height,a),C=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,c.width,c.height,a),S=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,c.width,c.height,a),b=K.Vector3[0],R=K.Vector3[1];b.copyFromFloats((2*E-1)*this.noiseStrength.x,(2*C-1)*this.noiseStrength.y,(2*S-1)*this.noiseStrength.z),b.scaleToRef(p,R),f.direction.addInPlace(R)}if(this.gravity.scaleToRef(p,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&ta.GetCurrentGradient(g,this._sizeGradients,(E,C,S)=>{E!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=C.getFactor(),f._currentSizeGradient=E),f.size=ye.Lerp(f._currentSize1,f._currentSize2,S)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&ta.GetCurrentGradient(g,this._colorRemapGradients,(E,C,S)=>{const b=ye.Lerp(E.factor1,C.factor1,S),R=ye.Lerp(E.factor2,C.factor2,S);f.remapData.x=b,f.remapData.y=R-b}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&ta.GetCurrentGradient(g,this._alphaRemapGradients,(E,C,S)=>{const b=ye.Lerp(E.factor1,C.factor1,S),R=ye.Lerp(E.factor2,C.factor2,S);f.remapData.z=b,f.remapData.w=R-b})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(E=>{E.particleSystem.disposeOnStop=!0,E.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),u&&d--;continue}}}}_addFactorGradient(e,t,i,s){const r=new lA(t,i,s);e.push(r),e.sort((n,a)=>n.gradienta.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=gi.Color3[0];for(let i=0;i{Te.LerpToRef(r.color,n.color,a,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=Ws.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new yW(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 oA(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort((r,n)=>r.gradientn.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,a=t*s%s|0,l=(n+a*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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Br(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(P.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(P.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const a=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=a,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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL){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 Br(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{e instanceof Xt?this._subEmitters.push([new nh(e)]):e instanceof nh?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=[]),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||t===void 0?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;s0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL)&&(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&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,K.Vector3[0]),n=K.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&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,K.Vector3[0]),n=K.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)}_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}_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=k.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const r=ye.Clamp(this._actualFrame/this.targetStopDuration);ta.GetCurrentGradient(r,this._lifeTimeGradients,(n,a)=>{const l=n,h=a,c=l.getFactor(),u=h.getFactor(),d=(r-l.gradient)/(h.gradient-l.gradient);t.lifeTime=ye.Lerp(c,u,d)})}else t.lifeTime=ye.RandomRange(this.minLifeTime,this.maxLifeTime);const s=ye.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),T.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=ye.RandomRange(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(ye.RandomRange(this.minScaleX,this.maxScaleX),ye.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;ta.GetCurrentGradient(r,this._startSizeGradients,(n,a,l)=>{n!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=a.getFactor(),this._currentStartSizeGradient=n);const h=ye.Lerp(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(h)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=ye.RandomRange(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=ye.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),!this._colorGradients||this._colorGradients.length===0){const r=ye.RandomRange(0,1);Ze.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 Dt(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 T(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new T(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[P.PositionKind,P.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Ao(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&vh(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===Xt.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Xt.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Xt.BILLBOARDMODE_STRETCHED:case Xt.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case Xt.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Xt._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==Xt.BILLBOARDMODE_STRETCHED&&this.billboardMode!==Xt.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...Xt._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(jt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),jt.PrepareSamplers(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 Or(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const a=i.join(` +}`;ne.ShadersStore[DW]=OW;class Xt extends yo{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Or(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 he),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=k.Identity(),this._inheritedVelocityOffset=new T,this.onDisposeObservable=new he,this.onStoppedObservable=new he,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ze(0,0,0,0),this._colorDiff=new Ze(0,0,0,0),this._scaledDirection=T.Zero(),this._scaledGravity=T.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=l=>{const h=this._particles.pop();h!==l&&h.copyTo(l),this._stockParticles.push(h)},this._createParticle=()=>{let l;if(this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new uA(this),this._subEmitters&&this._subEmitters.length>0){const h=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];l._attachedSubEmitters=[],h.forEach(c=>{if(c.type===Vd.ATTACHED){const u=c.clone();l._attachedSubEmitters.push(u),u.particleSystem.start()}})}return l},this._emitFromParticle=l=>{if(!this._subEmitters||this._subEmitters.length===0)return;const h=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[h].forEach(c=>{if(c.type===Vd.END){const u=c.clone();l._inheritParticleInfoToSubEmitter(u),u.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(u.particleSystem),u.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,!i||i.getClassName()==="Scene"?(this._scene=i||ht.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=k.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Or(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Wh;let a=null;this.updateFunction=l=>{var h;let c=null;this.noiseTexture&&(c=this.noiseTexture.getSize(),(h=this.noiseTexture.getContent())===null||h===void 0||h.then(d=>{a=d}));const u=l===this._particles;for(let d=0;df.lifeTime){const E=f.age-_;p=(f.lifeTime-_)*p/E,f.age=f.lifeTime}const g=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?ta.GetCurrentGradient(g,this._colorGradients,(E,C,S)=>{E!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),C.getColorToRef(f._currentColor2),f._currentColorGradient=E),Ze.LerpToRef(f._currentColor1,f._currentColor2,S,f.color)}):(f.colorStep.scaleToRef(p,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&ta.GetCurrentGradient(g,this._angularSpeedGradients,(E,C,S)=>{E!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=C.getFactor(),f._currentAngularSpeedGradient=E),f.angularSpeed=ye.Lerp(f._currentAngularSpeed1,f._currentAngularSpeed2,S)}),f.angle+=f.angularSpeed*p;let v=p;if(this._velocityGradients&&this._velocityGradients.length>0&&ta.GetCurrentGradient(g,this._velocityGradients,(E,C,S)=>{E!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=C.getFactor(),f._currentVelocityGradient=E),v*=ye.Lerp(f._currentVelocity1,f._currentVelocity2,S)}),f.direction.scaleToRef(v,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&ta.GetCurrentGradient(g,this._limitVelocityGradients,(E,C,S)=>{E!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=C.getFactor(),f._currentLimitVelocityGradient=E);const b=ye.Lerp(f._currentLimitVelocity1,f._currentLimitVelocity2,S);f.direction.length()>b&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&ta.GetCurrentGradient(g,this._dragGradients,(E,C,S)=>{E!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=C.getFactor(),f._currentDragGradient=E);const b=ye.Lerp(f._currentDrag1,f._currentDrag2,S);this._scaledDirection.scaleInPlace(1-b)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),T.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),a&&c&&f._randomNoiseCoordinates1){const E=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,c.width,c.height,a),C=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,c.width,c.height,a),S=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,c.width,c.height,a),b=K.Vector3[0],R=K.Vector3[1];b.copyFromFloats((2*E-1)*this.noiseStrength.x,(2*C-1)*this.noiseStrength.y,(2*S-1)*this.noiseStrength.z),b.scaleToRef(p,R),f.direction.addInPlace(R)}if(this.gravity.scaleToRef(p,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&ta.GetCurrentGradient(g,this._sizeGradients,(E,C,S)=>{E!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=C.getFactor(),f._currentSizeGradient=E),f.size=ye.Lerp(f._currentSize1,f._currentSize2,S)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&ta.GetCurrentGradient(g,this._colorRemapGradients,(E,C,S)=>{const b=ye.Lerp(E.factor1,C.factor1,S),R=ye.Lerp(E.factor2,C.factor2,S);f.remapData.x=b,f.remapData.y=R-b}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&ta.GetCurrentGradient(g,this._alphaRemapGradients,(E,C,S)=>{const b=ye.Lerp(E.factor1,C.factor1,S),R=ye.Lerp(E.factor2,C.factor2,S);f.remapData.z=b,f.remapData.w=R-b})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(E=>{E.particleSystem.disposeOnStop=!0,E.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),u&&d--;continue}}}}_addFactorGradient(e,t,i,s){const r=new cA(t,i,s);e.push(r),e.sort((n,a)=>n.gradienta.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=gi.Color3[0];for(let i=0;i{Te.LerpToRef(r.color,n.color,a,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=Ws.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new IW(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 hA(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort((r,n)=>r.gradientn.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,a=t*s%s|0,l=(n+a*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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Br(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(P.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(P.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const a=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=a,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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL){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 Br(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{e instanceof Xt?this._subEmitters.push([new ah(e)]):e instanceof ah?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&this._subEmitters.length!=0&&(this.activeSubSystems=[]),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||t===void 0?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;s0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,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===Xt.BILLBOARDMODE_STRETCHED||this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL)&&(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&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,K.Vector3[0]),n=K.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&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,K.Vector3[0]),n=K.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)}_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}_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=k.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const r=ye.Clamp(this._actualFrame/this.targetStopDuration);ta.GetCurrentGradient(r,this._lifeTimeGradients,(n,a)=>{const l=n,h=a,c=l.getFactor(),u=h.getFactor(),d=(r-l.gradient)/(h.gradient-l.gradient);t.lifeTime=ye.Lerp(c,u,d)})}else t.lifeTime=ye.RandomRange(this.minLifeTime,this.maxLifeTime);const s=ye.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),T.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=ye.RandomRange(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(ye.RandomRange(this.minScaleX,this.maxScaleX),ye.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;ta.GetCurrentGradient(r,this._startSizeGradients,(n,a,l)=>{n!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=a.getFactor(),this._currentStartSizeGradient=n);const h=ye.Lerp(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(h)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=ye.RandomRange(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=ye.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),!this._colorGradients||this._colorGradients.length===0){const r=ye.RandomRange(0,1);Ze.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 Dt(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 T(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new T(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[P.PositionKind,P.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Ao(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&xh(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===Xt.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Xt.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Xt.BILLBOARDMODE_STRETCHED:case Xt.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===Xt.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case Xt.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Xt._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==Xt.BILLBOARDMODE_STRETCHED&&this.billboardMode!==Xt.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...Xt._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(jt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),jt.PrepareSamplers(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 Or(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const a=i.join(` `);if(n.defines!==a){const l=[],h=[],c=[];this.fillUniformsAttributesAndSamplerNames(h,l,c),n.setEffect(this._engine.createEffect("particles",l,h,c,a),a)}return n}animate(e=!1){var t;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:((t=this._scene)===null||t===void 0?void 0:t.getAnimationRatio())||1);let i;if(this.manualEmitCount>-1)i=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;ta.GetCurrentGradient(r,this._emitRateGradients,(n,a,l)=>{n!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=a.getFactor(),this._currentEmitRateGradient=n),s=ye.Lerp(this._currentEmitRate1,this._currentEmitRate2,l)})}i=s*this._scaledUpdateSpeed>>0,this._newPartsExcess+=s*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let s=0;for(let r=0;r=0&&(f.invertToRef(K.Matrix[0]),u.setMatrix("invView",K.Matrix[0])),this._vertexArrayObject!==void 0?!((s=this._scene)===null||s===void 0)&&s.forceWireframe?d.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,!((r=this._scene)===null||r===void 0)&&r.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?d.bindBuffers(this._vertexBuffers,!((a=this._scene)===null||a===void 0)&&a.forceWireframe?this._linesIndexBuffer:this._indexBuffer,u):d.bindBuffers(this._vertexBuffers,!((n=this._scene)===null||n===void 0)&&n.forceWireframe?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&Me.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case Xt.BLENDMODE_ADD:d.setAlphaMode(1);break;case Xt.BLENDMODE_ONEONE:d.setAlphaMode(6);break;case Xt.BLENDMODE_STANDARD:d.setAlphaMode(2);break;case Xt.BLENDMODE_MULTIPLY:d.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?!((l=this._scene)===null||l===void 0)&&l.forceWireframe?d.drawElementsType(6,0,10,this._particles.length):d.drawArraysType(7,0,4,this._particles.length):!((h=this._scene)===null||h===void 0)&&h.forceWireframe?d.drawElementsType(1,0,this._particles.length*10):d.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===Xt.BLENDMODE_MULTIPLYADD?t=this._render(Xt.BLENDMODE_MULTIPLY)+this._render(Xt.BLENDMODE_ADD):t=this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._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._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let t=0;t-1&&this._scene.particleSystems.splice(t,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const s=Object.assign({},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 a=this.serialize(i),l=Xt.Parse(a,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}serialize(e=!1){const t={};if(Xt._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const 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,Xe.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 v={gradient:g.gradient,color1:g.color1.asArray()};g.color2?v.color2=g.color2.asArray():v.color2=g.color1.asArray(),e.colorGradients.push(v)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const g of r){const v={gradient:g.gradient,color:g.color.asArray()};e.rampGradients.push(v)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const g of n){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.colorRemapGradients.push(v)}}const a=t.getAlphaRemapGradients();if(a){e.alphaRemapGradients=[];for(const g of a){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.alphaRemapGradients.push(v)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const g of l){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.sizeGradients.push(v)}}const h=t.getAngularSpeedGradients();if(h){e.angularSpeedGradients=[];for(const g of h){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.angularSpeedGradients.push(v)}}const c=t.getVelocityGradients();if(c){e.velocityGradients=[];for(const g of c){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.velocityGradients.push(v)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const g of u){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.dragGradients.push(v)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const g of d){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.emitRateGradients.push(v)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const g of f){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.startSizeGradients.push(v)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const g of p){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.lifeTimeGradients.push(v)}}const _=t.getLimitVelocityGradients();if(_){e.limitVelocityGradients=[];for(const g of _){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.limitVelocityGradients.push(v)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,s){var r,n,a;let l;i instanceof We?l=null:l=i;const h=Ds("BABYLON.Texture");if(h&&l&&(e.texture?t.particleTexture=h.Parse(e.texture,l,s):e.textureName&&(t.particleTexture=new h(s+e.textureName,l,!1,e.invertY!==void 0?e.invertY:!0),t.particleTexture.name=e.textureName)),!e.emitterId&&e.emitterId!==0&&e.emitter===void 0?t.emitter=T.Zero():e.emitterId&&l?t.emitter=l.getLastMeshById(e.emitterId):t.emitter=T.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 u=0;u0?l.shaderOptions.defines.join(` -`):"";a=h.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const u=new Xt(n,r||e.capacity,t,a,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 p of d)f.push(nh.Parse(p,t,i));u.subEmitters.push(f)}}return Xt._Parse(e,u,t,i),e.textureMask&&(u.textureMask=Ze.FromArray(e.textureMask)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!s&&!u.preventAutoStart&&u.start(),u}}Xt.BILLBOARDMODE_Y=2;Xt.BILLBOARDMODE_ALL=7;Xt.BILLBOARDMODE_STRETCHED=8;Xt.BILLBOARDMODE_STRETCHED_LOCAL=9;nh._ParseParticleSystem=Xt.Parse;const MW="clipPlaneFragmentDeclaration2",DW=`#ifdef CLIPPLANE +`):"",c=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,h);s[0]?s[0].effect=c:this.setCustomEffect(c,0)}const a=this.serialize(i),l=Xt.Parse(a,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}serialize(e=!1){const t={};if(Xt._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const 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,Xe.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 v={gradient:g.gradient,color1:g.color1.asArray()};g.color2?v.color2=g.color2.asArray():v.color2=g.color1.asArray(),e.colorGradients.push(v)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const g of r){const v={gradient:g.gradient,color:g.color.asArray()};e.rampGradients.push(v)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const g of n){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.colorRemapGradients.push(v)}}const a=t.getAlphaRemapGradients();if(a){e.alphaRemapGradients=[];for(const g of a){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.alphaRemapGradients.push(v)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const g of l){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.sizeGradients.push(v)}}const h=t.getAngularSpeedGradients();if(h){e.angularSpeedGradients=[];for(const g of h){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.angularSpeedGradients.push(v)}}const c=t.getVelocityGradients();if(c){e.velocityGradients=[];for(const g of c){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.velocityGradients.push(v)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const g of u){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.dragGradients.push(v)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const g of d){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.emitRateGradients.push(v)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const g of f){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.startSizeGradients.push(v)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const g of p){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.lifeTimeGradients.push(v)}}const _=t.getLimitVelocityGradients();if(_){e.limitVelocityGradients=[];for(const g of _){const v={gradient:g.gradient,factor1:g.factor1};g.factor2!==void 0?v.factor2=g.factor2:v.factor2=g.factor1,e.limitVelocityGradients.push(v)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,s){var r,n,a;let l;i instanceof We?l=null:l=i;const h=Ds("BABYLON.Texture");if(h&&l&&(e.texture?t.particleTexture=h.Parse(e.texture,l,s):e.textureName&&(t.particleTexture=new h(s+e.textureName,l,!1,e.invertY!==void 0?e.invertY:!0),t.particleTexture.name=e.textureName)),!e.emitterId&&e.emitterId!==0&&e.emitter===void 0?t.emitter=T.Zero():e.emitterId&&l?t.emitter=l.getLastMeshById(e.emitterId):t.emitter=T.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 u=0;u0?l.shaderOptions.defines.join(` +`):"";a=h.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const u=new Xt(n,r||e.capacity,t,a,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 p of d)f.push(ah.Parse(p,t,i));u.subEmitters.push(f)}}return Xt._Parse(e,u,t,i),e.textureMask&&(u.textureMask=Ze.FromArray(e.textureMask)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!s&&!u.preventAutoStart&&u.start(),u}}Xt.BILLBOARDMODE_Y=2;Xt.BILLBOARDMODE_ALL=7;Xt.BILLBOARDMODE_STRETCHED=8;Xt.BILLBOARDMODE_STRETCHED_LOCAL=9;ah._ParseParticleSystem=Xt.Parse;const NW="clipPlaneFragmentDeclaration2",wW=`#ifdef CLIPPLANE in float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -9927,7 +9927,7 @@ in float fClipDistance5; #ifdef CLIPPLANE6 in float fClipDistance6; #endif -`;ne.IncludesShadersStore[MW]=DW;const OW="gpuRenderParticlesPixelShader",NW=`precision highp float; +`;ne.IncludesShadersStore[NW]=wW;const FW="gpuRenderParticlesPixelShader",LW=`precision highp float; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif @@ -9952,7 +9952,7 @@ gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessi #endif #endif } -`;ne.ShadersStore[OW]=NW;const wW="clipPlaneVertexDeclaration2",FW=`#ifdef CLIPPLANE +`;ne.ShadersStore[FW]=LW;const BW="clipPlaneVertexDeclaration2",VW=`#ifdef CLIPPLANE uniform vec4 vClipPlane;out float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -9970,7 +9970,7 @@ uniform vec4 vClipPlane5;out float fClipDistance5; #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;out float fClipDistance6; #endif -`;ne.IncludesShadersStore[wW]=FW;const LW="gpuRenderParticlesVertexShader",BW=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +`;ne.IncludesShadersStore[BW]=VW;const UW="gpuRenderParticlesVertexShader",kW=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; #ifdef LOCAL uniform mat4 emitterWM; #endif @@ -10055,7 +10055,7 @@ vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include -}`;ne.ShadersStore[LW]=BW;class Bc extends yo{static get IsSupported(){if(!ht.LastCreatedEngine)return!1;const e=ht.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]))}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}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==Xt.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(Xt.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(Xt.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,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Or(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new he),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 oA(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.gradienti.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===void 0||e.reset()}_addFactorGradient(e,t,i){const s=new lA(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.gradientn.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.onDisposeObservable=new he,this.onStoppedObservable=new he,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||ht.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=k.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Ds("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Ds("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Ds("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Ds("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Or(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Or(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=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new zh;const l=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let h=[];for(let c=0;c0;)i.push(0)}const a=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 Br(t,l,!1,this._attributesStrideSize),this._buffer1=new Br(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new Br(t,a,!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+=` +}`;ne.ShadersStore[UW]=kW;class Bc extends yo{static get IsSupported(){if(!ht.LastCreatedEngine)return!1;const e=ht.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]))}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}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==Xt.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(Xt.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(Xt.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,i;return(i=(t=this._customWrappers[e])===null||t===void 0?void 0:t.effect)!==null&&i!==void 0?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return(t=this._customWrappers[e])!==null&&t!==void 0?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Or(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new he),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 hA(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.gradienti.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===void 0||e.reset()}_addFactorGradient(e,t,i){const s=new cA(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.gradientn.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.onDisposeObservable=new he,this.onStoppedObservable=new he,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||ht.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=k.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Ds("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Ds("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Ds("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Ds("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Or(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Or(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=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new Wh;const l=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let h=[];for(let c=0;c0;)i.push(0)}const a=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 Br(t,l,!1,this._attributesStrideSize),this._buffer1=new Br(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new Br(t,a,!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+=` @@ -10067,31 +10067,31 @@ vec4 worldPos=vec4(vPositionW,1.0); #define ANIMATESHEETRANDOMSTART`)),this.noiseTexture&&(e+=` #define NOISE`),this.isLocal&&(e+=` #define LOCAL`),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e?!0:(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 Or(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join(` -`);if(s.defines!==r){const n=[],a=[],l=[];this.fillUniformsAttributesAndSamplerNames(a,n,l),s.setEffect(this._engine.createEffect("gpuRenderParticles",n,a,l,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[P.PositionKind,"age","life","size","angle"];return e||r.push(P.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",P.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Ao(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&vh(this,this._scene,e),t===Xt.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 Xt.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Xt.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Xt.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(...Bc._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Xt.BILLBOARDMODE_STRETCHED)),e.push(...Bc._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(jt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),jt.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)===null||t===void 0?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{s[r]=ye.Lerp(a.factor1,l.factor1,h)})}this[t]=Ws.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=gi.Color4[0];for(let i=0;i{Ze.LerpToRef(r.color1,n.color1,a,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=Ws.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,s,r,n,a;const l=this._getWrapper(e),h=l.effect;this._engine.enableEffect(l);const c=((i=this._scene)===null||i===void 0?void 0:i.getViewMatrix())||k.IdentityReadOnly;if(h.setMatrix("view",c),h.setMatrix("projection",(s=this.defaultProjectionMatrix)!==null&&s!==void 0?s:this._scene.getProjectionMatrix()),h.setTexture("diffuseSampler",this.particleTexture),h.setVector2("translationPivot",this.translationPivot),h.setVector3("worldOffset",this.worldOffset),this.isLocal&&h.setMatrix("emitterWM",t),this._colorGradientsTexture?h.setTexture("colorGradientSampler",this._colorGradientsTexture):h.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const d=this.particleTexture.getBaseSize();h.setFloat3("sheetInfos",this.spriteCellWidth/d.width,this.spriteCellHeight/d.height,d.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const d=this._scene.activeCamera;h.setVector3("eyePosition",d.globalPosition)}const u=h.defines;if(this._scene&&so(h,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){const d=c.clone();d.invert(),h.setMatrix("invView",d)}switch(this.useLogarithmicDepth&&this._scene&&Me.BindLogDepth(u,h,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(h),e){case Xt.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Xt.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Xt.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Xt.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,h,!((r=this._scene)===null||r===void 0)&&r.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(h),!((n=this._scene)===null||n===void 0)&&n.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),!((a=this._scene)===null||a===void 0)&&a.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=K.Matrix[0],k.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;n1){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=K.Matrix[0],k.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===Xt.BLENDMODE_MULTIPLYADD?r=this._render(Xt.BLENDMODE_MULTIPLY,i)+this._render(Xt.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._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),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;t0?r.shaderOptions.defines.join(` +`);if(s.defines!==r){const n=[],a=[],l=[];this.fillUniformsAttributesAndSamplerNames(a,n,l),s.setEffect(this._engine.createEffect("gpuRenderParticles",n,a,l,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[P.PositionKind,"age","life","size","angle"];return e||r.push(P.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",P.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Ao(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&xh(this,this._scene,e),t===Xt.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 Xt.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Xt.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Xt.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(...Bc._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Xt.BILLBOARDMODE_STRETCHED)),e.push(...Bc._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(jt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),jt.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:((t=this._scene)===null||t===void 0?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{s[r]=ye.Lerp(a.factor1,l.factor1,h)})}this[t]=Ws.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=gi.Color4[0];for(let i=0;i{Ze.LerpToRef(r.color1,n.color1,a,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=Ws.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,s,r,n,a;const l=this._getWrapper(e),h=l.effect;this._engine.enableEffect(l);const c=((i=this._scene)===null||i===void 0?void 0:i.getViewMatrix())||k.IdentityReadOnly;if(h.setMatrix("view",c),h.setMatrix("projection",(s=this.defaultProjectionMatrix)!==null&&s!==void 0?s:this._scene.getProjectionMatrix()),h.setTexture("diffuseSampler",this.particleTexture),h.setVector2("translationPivot",this.translationPivot),h.setVector3("worldOffset",this.worldOffset),this.isLocal&&h.setMatrix("emitterWM",t),this._colorGradientsTexture?h.setTexture("colorGradientSampler",this._colorGradientsTexture):h.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const d=this.particleTexture.getBaseSize();h.setFloat3("sheetInfos",this.spriteCellWidth/d.width,this.spriteCellHeight/d.height,d.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const d=this._scene.activeCamera;h.setVector3("eyePosition",d.globalPosition)}const u=h.defines;if(this._scene&&so(h,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){const d=c.clone();d.invert(),h.setMatrix("invView",d)}switch(this.useLogarithmicDepth&&this._scene&&Me.BindLogDepth(u,h,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(h),e){case Xt.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Xt.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Xt.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Xt.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,h,!((r=this._scene)===null||r===void 0)&&r.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(h),!((n=this._scene)===null||n===void 0)&&n.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),!((a=this._scene)===null||a===void 0)&&a.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const i=this.emitter;e=K.Matrix[0],k.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;n1){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=K.Matrix[0],k.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===Xt.BLENDMODE_MULTIPLYADD?r=this._render(Xt.BLENDMODE_MULTIPLY,i)+this._render(Xt.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._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),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;t0?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 a=this.serialize(i),l=Bc.Parse(a,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 Xt._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 a,l;t instanceof We?a=t:(l=t,a=l.getEngine());const h=new Bc(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(h._rootUrl=i,e.customShader&&a.createEffectForParticles){const c=e.customShader,u=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join(` `):"",d=a.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),Xt._Parse(e,h,t,i),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),!s&&!h.preventAutoStart&&h.start(),h}}ks.AddParser(Fe.NAME_PARTICLESYSTEM,(o,e,t,i)=>{const s=ks.GetIndividualParser(Fe.NAME_PARTICLESYSTEM);if(s&&o.particleSystems!==void 0&&o.particleSystems!==null)for(let r=0,n=o.particleSystems.length;ro.activeParticleCount?Bc.Parse(o,e,t):Xt.Parse(o,e,t));re.prototype.createEffectForParticles=function(o,e=[],t=[],i="",s,r,n,a){var l;let h=[],c=[];const u=[];return a?a.fillUniformsAttributesAndSamplerNames(c,h,u):(h=Xt._GetAttributeNamesOrOptions(),c=Xt._GetEffectCreationOptions()),i.indexOf(" BILLBOARD")===-1&&(i+=` #define BILLBOARD `),a!=null&&a.isAnimationSheetEnabled&&i.indexOf(" ANIMATESHEET")===-1&&(i+=` #define ANIMATESHEET -`),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(l=a==null?void 0:a.vertexShaderName)!==null&&l!==void 0?l:"particles",fragmentElement:o},h,c.concat(e),u.concat(t),i,s,r,n)};se.prototype.getEmittedParticleSystems=function(){const o=[];for(let e=0;e{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});hi.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};hi.prototype.applyImpulse=function(o,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(o,e),this):this};hi.prototype.setPhysicsLinkWith=function(o,e,t,i){return!this.physicsImpostor||!o.physicsImpostor?this:(this.physicsImpostor.createJoint(o.physicsImpostor,ts.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class uT{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("")}constructor(e,t=uT.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new T(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 Fm;return this._physicsPlugin.raycast(e,t,s,i),s}}var pC;(function(o){o[o.FREE=0]="FREE",o[o.LIMITED=1]="LIMITED",o[o.LOCKED=2]="LOCKED"})(pC||(pC={}));var _C;(function(o){o[o.LINEAR_X=0]="LINEAR_X",o[o.LINEAR_Y=1]="LINEAR_Y",o[o.LINEAR_Z=2]="LINEAR_Z",o[o.ANGULAR_X=3]="ANGULAR_X",o[o.ANGULAR_Y=4]="ANGULAR_Y",o[o.ANGULAR_Z=5]="ANGULAR_Z",o[o.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(_C||(_C={}));var mC;(function(o){o[o.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",o[o.DISTANCE=2]="DISTANCE",o[o.HINGE=3]="HINGE",o[o.SLIDER=4]="SLIDER",o[o.LOCK=5]="LOCK",o[o.PRISMATIC=6]="PRISMATIC",o[o.SIX_DOF=7]="SIX_DOF"})(mC||(mC={}));var gC;(function(o){o[o.SPHERE=0]="SPHERE",o[o.CAPSULE=1]="CAPSULE",o[o.CYLINDER=2]="CYLINDER",o[o.BOX=3]="BOX",o[o.CONVEX_HULL=4]="CONVEX_HULL",o[o.CONTAINER=5]="CONTAINER",o[o.MESH=6]="MESH",o[o.HEIGHTFIELD=7]="HEIGHTFIELD"})(gC||(gC={}));var vC;(function(o){o[o.NONE=0]="NONE",o[o.VELOCITY=1]="VELOCITY",o[o.POSITION=2]="POSITION"})(vC||(vC={}));var xC;(function(o){o.COLLISION_STARTED="COLLISION_STARTED",o.COLLISION_CONTINUED="COLLISION_CONTINUED",o.COLLISION_FINISHED="COLLISION_FINISHED",o.TRIGGER_ENTERED="TRIGGER_ENTERED",o.TRIGGER_EXITED="TRIGGER_EXITED"})(xC||(xC={}));var TC;(function(o){o[o.STATIC=0]="STATIC",o[o.ANIMATED=1]="ANIMATED",o[o.DYNAMIC=2]="DYNAMIC"})(TC||(TC={}));var EC;(function(o){o[o.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",o[o.MINIMUM=1]="MINIMUM",o[o.MAXIMUM=2]="MAXIMUM",o[o.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",o[o.MULTIPLY=4]="MULTIPLY"})(EC||(EC={}));Qe.prototype.getPhysicsEngine=function(){return this._physicsEngine};Qe.prototype.enablePhysics=function(o=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(Fe.NAME_PHYSICSENGINE);t||(t=new VW(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new Ty(o,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new uT(o,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return G.Error(i.message),!1}};Qe.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};Qe.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};Qe.prototype.deleteCompoundImpostor=function(o){const e=o.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};Qe.prototype._advancePhysicsEngineStep=function(o){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=o;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(o/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class VW{constructor(e){this.name=Fe.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new he,this.scene.onAfterPhysicsObservable=new he,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(It.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(o){this._physicsBody!==o&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=o,o&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});It.prototype.getPhysicsBody=function(){return this.physicsBody};It.prototype.applyImpulse=function(o,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(o,e),this};T.Zero();var SC;(function(o){o[o.Constant=0]="Constant",o[o.Linear=1]="Linear"})(SC||(SC={}));var CC;(function(o){o[o.Center=0]="Center",o[o.Perpendicular=1]="Perpendicular"})(CC||(CC={}));const UW="blackAndWhitePixelShader",kW=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +`),t.indexOf("diffuseSampler")===-1&&t.push("diffuseSampler"),this.createEffect({vertex:(l=a==null?void 0:a.vertexShaderName)!==null&&l!==void 0?l:"particles",fragmentElement:o},h,c.concat(e),u.concat(t),i,s,r,n)};se.prototype.getEmittedParticleSystems=function(){const o=[];for(let e=0;e{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});hi.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};hi.prototype.applyImpulse=function(o,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(o,e),this):this};hi.prototype.setPhysicsLinkWith=function(o,e,t,i){return!this.physicsImpostor||!o.physicsImpostor?this:(this.physicsImpostor.createJoint(o.physicsImpostor,ts.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class fT{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("")}constructor(e,t=fT.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new T(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 Fm;return this._physicsPlugin.raycast(e,t,s,i),s}}var mC;(function(o){o[o.FREE=0]="FREE",o[o.LIMITED=1]="LIMITED",o[o.LOCKED=2]="LOCKED"})(mC||(mC={}));var gC;(function(o){o[o.LINEAR_X=0]="LINEAR_X",o[o.LINEAR_Y=1]="LINEAR_Y",o[o.LINEAR_Z=2]="LINEAR_Z",o[o.ANGULAR_X=3]="ANGULAR_X",o[o.ANGULAR_Y=4]="ANGULAR_Y",o[o.ANGULAR_Z=5]="ANGULAR_Z",o[o.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(gC||(gC={}));var vC;(function(o){o[o.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",o[o.DISTANCE=2]="DISTANCE",o[o.HINGE=3]="HINGE",o[o.SLIDER=4]="SLIDER",o[o.LOCK=5]="LOCK",o[o.PRISMATIC=6]="PRISMATIC",o[o.SIX_DOF=7]="SIX_DOF"})(vC||(vC={}));var xC;(function(o){o[o.SPHERE=0]="SPHERE",o[o.CAPSULE=1]="CAPSULE",o[o.CYLINDER=2]="CYLINDER",o[o.BOX=3]="BOX",o[o.CONVEX_HULL=4]="CONVEX_HULL",o[o.CONTAINER=5]="CONTAINER",o[o.MESH=6]="MESH",o[o.HEIGHTFIELD=7]="HEIGHTFIELD"})(xC||(xC={}));var TC;(function(o){o[o.NONE=0]="NONE",o[o.VELOCITY=1]="VELOCITY",o[o.POSITION=2]="POSITION"})(TC||(TC={}));var EC;(function(o){o.COLLISION_STARTED="COLLISION_STARTED",o.COLLISION_CONTINUED="COLLISION_CONTINUED",o.COLLISION_FINISHED="COLLISION_FINISHED",o.TRIGGER_ENTERED="TRIGGER_ENTERED",o.TRIGGER_EXITED="TRIGGER_EXITED"})(EC||(EC={}));var SC;(function(o){o[o.STATIC=0]="STATIC",o[o.ANIMATED=1]="ANIMATED",o[o.DYNAMIC=2]="DYNAMIC"})(SC||(SC={}));var CC;(function(o){o[o.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",o[o.MINIMUM=1]="MINIMUM",o[o.MAXIMUM=2]="MAXIMUM",o[o.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",o[o.MULTIPLY=4]="MULTIPLY"})(CC||(CC={}));Qe.prototype.getPhysicsEngine=function(){return this._physicsEngine};Qe.prototype.enablePhysics=function(o=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(Fe.NAME_PHYSICSENGINE);t||(t=new GW(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new Sy(o,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new fT(o,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return G.Error(i.message),!1}};Qe.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};Qe.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};Qe.prototype.deleteCompoundImpostor=function(o){const e=o.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};Qe.prototype._advancePhysicsEngineStep=function(o){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=o;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(o/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class GW{constructor(e){this.name=Fe.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new he,this.scene.onAfterPhysicsObservable=new he,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(It.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(o){this._physicsBody!==o&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=o,o&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});It.prototype.getPhysicsBody=function(){return this.physicsBody};It.prototype.applyImpulse=function(o,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(o,e),this};T.Zero();var bC;(function(o){o[o.Constant=0]="Constant",o[o.Linear=1]="Linear"})(bC||(bC={}));var yC;(function(o){o[o.Center=0]="Center",o[o.Perpendicular=1]="Perpendicular"})(yC||(yC={}));const zW="blackAndWhitePixelShader",WW=`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);}`;ne.ShadersStore[UW]=kW;class Gm extends lt{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(a=>{a.setFloat("degree",this.degree)})}static _Parse(e,t,i,s){return Xe.Parse(()=>new Gm(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],Gm.prototype,"degree",void 0);j("BABYLON.BlackAndWhitePostProcess",Gm);class Pi{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{const l=r.attachPostProcess(a);this._indicesForCamera[n].push(l)}),this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(a)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(n)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const GW="extractHighlightsPixelShader",zW=`#include +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;ne.ShadersStore[zW]=WW;class Gm extends lt{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(a=>{a.setFloat("degree",this.degree)})}static _Parse(e,t,i,s){return Xe.Parse(()=>new Gm(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],Gm.prototype,"degree",void 0);j("BABYLON.BlackAndWhitePostProcess",Gm);class Pi{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{const l=r.attachPostProcess(a);this._indicesForCamera[n].push(l)}),this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(a)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=fe.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(n)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const HW="extractHighlightsPixelShader",XW=`#include 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;}`;ne.ShadersStore[GW]=zW;class dT extends lt{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,a,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,Qu)),h.setFloat("exposure",this._exposure)})}}A([D()],dT.prototype,"threshold",void 0);j("BABYLON.ExtractHighlightsPostProcess",dT);const WW="bloomMergePixelShader",HW=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;ne.ShadersStore[HW]=XW;class pT extends lt{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,a,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,Qu)),h.setFloat("exposure",this._exposure)})}}A([D()],pT.prototype,"threshold",void 0);j("BABYLON.ExtractHighlightsPostProcess",pT);const YW="bloomMergePixelShader",$W=`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); } -`;ne.ShadersStore[WW]=HW;class fT extends lt{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,a,l,h,c=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,a,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()}}A([D()],fT.prototype,"weight",void 0);j("BABYLON.BloomMergePostProcess",fT);class bC extends Pi{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 dT("highlights",1,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new or("horizontal blur",new Re(1,0),10,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new or("vertical blur",new Re(0,1),10,t,null,ee.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 fT("bloomMerge",this._downscale,this._blurY,i,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("bloomBlur",i),d.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}A([D()],_T.prototype,"weight",void 0);j("BABYLON.BloomMergePostProcess",_T);class AC extends Pi{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 pT("highlights",1,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new or("horizontal blur",new Re(1,0),10,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new or("vertical blur",new Re(0,1),10,t,null,ee.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 _T("bloomMerge",this._downscale,this._blurY,i,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{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 Xe.Parse(()=>new il(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}A([D()],il.prototype,"aberrationAmount",void 0);A([D()],il.prototype,"radialIntensity",void 0);A([D()],il.prototype,"direction",void 0);A([D()],il.prototype,"centerPosition",void 0);A([D()],il.prototype,"screenWidth",void 0);A([D()],il.prototype,"screenHeight",void 0);j("BABYLON.ChromaticAberrationPostProcess",il);const $W="circleOfConfusionPixelShader",KW=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; ++ 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;}`;ne.ShadersStore[KW]=qW;class il extends lt{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,s,r,n,a,l,h=0,c=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],s,r,n,a,l,null,h,void 0,null,c),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new Re(.707,.707),this.centerPosition=new Re(.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 Xe.Parse(()=>new il(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}A([D()],il.prototype,"aberrationAmount",void 0);A([D()],il.prototype,"radialIntensity",void 0);A([D()],il.prototype,"direction",void 0);A([D()],il.prototype,"centerPosition",void 0);A([D()],il.prototype,"screenWidth",void 0);A([D()],il.prototype,"screenHeight",void 0);j("BABYLON.ChromaticAberrationPostProcess",il);const jW="circleOfConfusionPixelShader",QW=`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; @@ -10099,7 +10099,7 @@ void main(void) 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);} -`;ne.ShadersStore[$W]=KW;class bu extends lt{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,a,l=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,a,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){G.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}}A([D()],bu.prototype,"lensSize",void 0);A([D()],bu.prototype,"fStop",void 0);A([D()],bu.prototype,"focusDistance",void 0);A([D()],bu.prototype,"focalLength",void 0);j("BABYLON.CircleOfConfusionPostProcess",bu);const qW="colorCorrectionPixelShader",jW=`uniform sampler2D textureSampler; +`;ne.ShadersStore[jW]=QW;class bu extends lt{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,a,l=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,a,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){G.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}}A([D()],bu.prototype,"lensSize",void 0);A([D()],bu.prototype,"fStop",void 0);A([D()],bu.prototype,"focusDistance",void 0);A([D()],bu.prototype,"focalLength",void 0);j("BABYLON.CircleOfConfusionPostProcess",bu);const ZW="colorCorrectionPixelShader",JW=`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; @@ -10108,7 +10108,7 @@ 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);}`;ne.ShadersStore[qW]=jW;class zm extends lt{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,a){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,a);const l=(s==null?void 0:s.getScene())||null;this._colorTableTexture=new ee(t,l,!0,!1,ee.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=ee.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=ee.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=h=>{h.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Xe.Parse(()=>new zm(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],zm.prototype,"colorTableUrl",void 0);j("BABYLON.ColorCorrectionPostProcess",zm);const QW="convolutionPixelShader",ZW=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;ne.ShadersStore[ZW]=JW;class zm extends lt{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,a){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,a);const l=(s==null?void 0:s.getScene())||null;this._colorTableTexture=new ee(t,l,!0,!1,ee.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=ee.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=ee.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=h=>{h.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Xe.Parse(()=>new zm(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],zm.prototype,"colorTableUrl",void 0);j("BABYLON.ColorCorrectionPostProcess",zm);const eH="convolutionPixelShader",tH=`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 = @@ -10130,8 +10130,8 @@ kernel[5] + kernel[6] + kernel[7] + kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} -gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;ne.ShadersStore[QW]=ZW;class sl extends lt{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,a,l=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,a,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 Xe.Parse(()=>new sl(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,s)}}sl.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];sl.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];sl.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];sl.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];sl.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];sl.GaussianKernel=[0,1,0,1,1,1,0,1,0];A([D()],sl.prototype,"kernel",void 0);j("BABYLON.ConvolutionPostProcess",sl);class Y_ extends or{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,a,l=null,h=ee.BILINEAR_SAMPLINGMODE,c,u,d=0,f=!1,p=5){super(e,i,s,r,n,h=2,c,u,d,`#define DOF 1 -`,f,p),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(_=>{l!=null&&_.setTextureFromPostProcess("textureSampler",l),_.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}A([D()],Y_.prototype,"direction",void 0);j("BABYLON.DepthOfFieldBlurPostProcess",Y_);const JW="depthOfFieldMergePixelShader",eH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;ne.ShadersStore[eH]=tH;class sl extends lt{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,a,l=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,a,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 Xe.Parse(()=>new sl(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,s)}}sl.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];sl.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];sl.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];sl.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];sl.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];sl.GaussianKernel=[0,1,0,1,1,1,0,1,0];A([D()],sl.prototype,"kernel",void 0);j("BABYLON.ConvolutionPostProcess",sl);class Y_ extends or{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,a,l=null,h=ee.BILINEAR_SAMPLINGMODE,c,u,d=0,f=!1,p=5){super(e,i,s,r,n,h=2,c,u,d,`#define DOF 1 +`,f,p),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(_=>{l!=null&&_.setTextureFromPostProcess("textureSampler",l),_.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}A([D()],Y_.prototype,"direction",void 0);j("BABYLON.DepthOfFieldBlurPostProcess",Y_);const iH="depthOfFieldMergePixelShader",sH=`#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) @@ -10156,14 +10156,14 @@ if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXT 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 } -`;ne.ShadersStore[JW]=eH;class tH extends lt{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,a,l,h,c=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,a,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,p)=>{d.setTextureFromPostProcessOutput("blurStep"+(s.length-p-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 Kc;(function(o){o[o.Low=0]="Low",o[o.Medium=1]="Medium",o[o.High=2]="High"})(Kc||(Kc={}));class yC extends Pi{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=Kc.Low,s=0,r=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new bu("circleOfConfusion",t,1,null,ee.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case Kc.High:{l=3,h=51;break}case Kc.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{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach((f,p)=>{d.setTextureFromPostProcessOutput("blurStep"+(s.length-p-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 Kc;(function(o){o[o.Low=0]="Low",o[o.Medium=1]="Medium",o[o.High=2]="High"})(Kc||(Kc={}));class RC extends Pi{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=Kc.Low,s=0,r=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new bu("circleOfConfusion",t,1,null,ee.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case Kc.High:{l=3,h=51;break}case Kc.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;dnew pT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}j("BABYLON.DisplayPassPostProcess",pT);const rH="filterPixelShader",nH=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +{gl_FragColor=texture2D(passSampler,vUV);}`;ne.ShadersStore[nH]=aH;class mT extends lt{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 Xe.Parse(()=>new mT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}j("BABYLON.DisplayPassPostProcess",mT);const oH="filterPixelShader",lH=`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);}`;ne.ShadersStore[rH]=nH;class Wm extends lt{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,a){super(e,"filter",["kernelMatrix"],null,i,s,r,n,a),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Xe.Parse(()=>new Wm(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([rx()],Wm.prototype,"kernelMatrix",void 0);j("BABYLON.FilterPostProcess",Wm);const aH="fxaaPixelShader",oH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;ne.ShadersStore[oH]=lH;class Wm extends lt{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,a){super(e,"filter",["kernelMatrix"],null,i,s,r,n,a),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Xe.Parse(()=>new Wm(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([ax()],Wm.prototype,"kernelMatrix",void 0);j("BABYLON.FilterPostProcess",Wm);const hH="fxaaPixelShader",cH=`#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) @@ -10215,22 +10215,22 @@ else #else gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0); #endif -}`;ne.ShadersStore[aH]=oH;const lH="fxaaVertexShader",hH=`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); +}`;ne.ShadersStore[hH]=cH;const uH="fxaaVertexShader",dH=`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 -}`;ne.ShadersStore[lH]=hH;class yu extends lt{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,s,r,n,a=0){super(e,"fxaa",["texelSize"],null,t,i,s||ee.BILINEAR_SAMPLINGMODE,r,n,null,a,"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 Xe.Parse(()=>new yu(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}j("BABYLON.FxaaPostProcess",yu);const cH="grainPixelShader",uH=`#include +}`;ne.ShadersStore[uH]=dH;class yu extends lt{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,s,r,n,a=0){super(e,"fxaa",["texelSize"],null,t,i,s||ee.BILINEAR_SAMPLINGMODE,r,n,null,a,"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 Xe.Parse(()=>new yu(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}j("BABYLON.FxaaPostProcess",yu);const fH="grainPixelShader",pH=`#include 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);}`;ne.ShadersStore[cH]=uH;class Au extends lt{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,a,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 Xe.Parse(()=>new Au(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],Au.prototype,"intensity",void 0);A([D()],Au.prototype,"animated",void 0);j("BABYLON.GrainPostProcess",Au);const dH="highlightsPixelShader",fH=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +{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);}`;ne.ShadersStore[fH]=pH;class Au extends lt{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,a,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 Xe.Parse(()=>new Au(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],Au.prototype,"intensity",void 0);A([D()],Au.prototype,"animated",void 0);j("BABYLON.GrainPostProcess",Au);const _H="highlightsPixelShader",mH=`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); }`;ne.ShadersStore[dH]=fH;const pH="imageProcessingPixelShader",_H=`varying vec2 vUV;uniform sampler2D textureSampler; +{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); }`;ne.ShadersStore[_H]=mH;const gH="imageProcessingPixelShader",vH=`varying vec2 vUV;uniform sampler2D textureSampler; #include #include #include @@ -10247,11 +10247,11 @@ result=applyImageProcessing(result); result=applyImageProcessing(result); #endif #endif -gl_FragColor=result;}`;ne.ShadersStore[pH]=_H;class _T extends lt{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=ht.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new jt}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,a=0,l){super(e,"imageProcessing",[],[],t,i,s,r,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},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"];jt&&(jt.PrepareSamplers(t,this._defines),jt.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)}}A([D()],_T.prototype,"_fromLinearSpace",void 0);const mH="mrtFragmentDeclaration",gH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +gl_FragColor=result;}`;ne.ShadersStore[gH]=vH;class gT extends lt{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=ht.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new jt}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,a=0,l){super(e,"imageProcessing",[],[],t,i,s,r,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},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"];jt&&(jt.PrepareSamplers(t,this._defines),jt.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)}}A([D()],gT.prototype,"_fromLinearSpace",void 0);const xH="mrtFragmentDeclaration",TH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif -`;ne.IncludesShadersStore[mH]=gH;const vH="geometryPixelShader",xH=`#extension GL_EXT_draw_buffers : require +`;ne.IncludesShadersStore[xH]=TH;const EH="geometryPixelShader",SH=`#extension GL_EXT_draw_buffers : require #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif @@ -10378,8 +10378,8 @@ reflectivity.a*=glossiness; gl_FragData[REFLECTIVITY_INDEX]=reflectivity; #endif } -`;ne.ShadersStore[vH]=xH;const TH="geometryVertexDeclaration",EH="uniform mat4 viewProjection;uniform mat4 view;";ne.IncludesShadersStore[TH]=EH;const SH="geometryUboDeclaration",CH=`#include -`;ne.IncludesShadersStore[SH]=CH;const bH="geometryVertexShader",yH=`precision highp float; +`;ne.ShadersStore[EH]=SH;const CH="geometryVertexDeclaration",bH="uniform mat4 viewProjection;uniform mat4 view;";ne.IncludesShadersStore[CH]=bH;const yH="geometryUboDeclaration",AH=`#include +`;ne.IncludesShadersStore[yH]=AH;const RH="geometryVertexShader",IH=`precision highp float; #include #include #include @@ -10517,8 +10517,8 @@ vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); #endif #include } -`;ne.ShadersStore[bH]=yH;const hA=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Ao(hA);class cs{_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===cs.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===cs.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===cs.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===cs.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===cs.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 cs.POSITION_TEXTURE_TYPE:return this._positionIndex;case cs.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case cs.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case cs.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case cs.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){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ze(0,0,0,0),this._clearDepthColor=new Ze(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,cs._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[P.PositionKind,P.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&&we.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let p=!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,p=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),p=!0),p&&(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,p=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),p=!0),p?(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(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.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"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.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 a=n.morphTargetManager;let l=0;a&&a.numInfluencers>0&&(l=a.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+l),a.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(r,n,l)),t&&(s.push("#define INSTANCES"),Me.PushAttributesForInstances(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),vh(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:hA,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=[];let t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const r=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};if(this._multiRenderTarget=new Bh("gBuffer",r,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:s,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=ee.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=ee.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const n=[!0],a=[!1],l=[!0];for(let f=1;f{f.bindAttachments(this.useSpecificClearForDepthTexture?c:h),f.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(f.bindAttachments(u),f.clear(this._clearDepthColor,!0,!0,!0)),f.bindAttachments(h)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const f=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(f)}});const d=f=>{const p=f.getRenderingMesh(),_=f.getEffectiveMesh(),g=this._scene,v=g.getEngine(),E=f.getMaterial();if(!E)return;if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[_.uniqueId]&&(this._previousTransformationMatrices[_.uniqueId]={world:k.Identity(),viewProjection:g.getTransformMatrix()},p.skeleton)){const R=p.skeleton.getTransformMatrices(p);this._previousBonesTransformationMatrices[p.uniqueId]=this._copyBonesTransformationMatrices(R,new Float32Array(R.length))}const C=p._getInstancesRenderList(f._id,!!f.getReplacementMesh());if(C.mustReturn)return;const S=v.getCaps().instancedArrays&&(C.visibleInstances[f._id]!==null||p.hasThinInstances),b=_.getWorldMatrix();if(this.isReady(f,S)){const R=f._getDrawWrapper();if(!R)return;const I=R.effect;v.enableEffect(R),S||p._bind(f,I,E.fillMode),this._useUbo?(Me.BindSceneUniformBuffer(I,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(I.setMatrix("viewProjection",g.getTransformMatrix()),I.setMatrix("view",g.getViewMatrix()));let N;const O=p._instanceDataStorage;if(!O.isFrozen&&(E.backFaceCulling||p.overrideMaterialSideOrientation!==null)){const L=_._getWorldMatrixDeterminant();N=p.overrideMaterialSideOrientation,N===null&&(N=E.sideOrientation),L<0&&(N=N===Ie.ClockWiseSideOrientation?Ie.CounterClockWiseSideOrientation:Ie.ClockWiseSideOrientation)}else N=O.sideOrientation;if(E._preBind(R,N),E.needAlphaTesting()){const L=E.getAlphaTestTexture();L&&(I.setTexture("diffuseSampler",L),I.setMatrix("diffuseMatrix",L.getTextureMatrix()))}if(E.bumpTexture&&g.getEngine().getCaps().standardDerivatives&&we.BumpTextureEnabled&&(I.setFloat3("vBumpInfos",E.bumpTexture.coordinatesIndex,1/E.bumpTexture.level,E.parallaxScaleBias),I.setMatrix("bumpMatrix",E.bumpTexture.getTextureMatrix()),I.setTexture("bumpSampler",E.bumpTexture),I.setFloat2("vTangentSpaceParams",E.invertNormalMapX?-1:1,E.invertNormalMapY?-1:1)),this._enableReflectivity&&(E.getClassName()==="PBRMetallicRoughnessMaterial"?(E.metallicRoughnessTexture!==null&&(I.setTexture("reflectivitySampler",E.metallicRoughnessTexture),I.setMatrix("reflectivityMatrix",E.metallicRoughnessTexture.getTextureMatrix())),E.metallic!==null&&I.setFloat("metallic",E.metallic),E.roughness!==null&&I.setFloat("glossiness",1-E.roughness),E.baseTexture!==null&&(I.setTexture("albedoSampler",E.baseTexture),I.setMatrix("albedoMatrix",E.baseTexture.getTextureMatrix())),E.baseColor!==null&&I.setColor3("albedoColor",E.baseColor)):E.getClassName()==="PBRSpecularGlossinessMaterial"?(E.specularGlossinessTexture!==null?(I.setTexture("reflectivitySampler",E.specularGlossinessTexture),I.setMatrix("reflectivityMatrix",E.specularGlossinessTexture.getTextureMatrix())):E.specularColor!==null&&I.setColor3("reflectivityColor",E.specularColor),E.glossiness!==null&&I.setFloat("glossiness",E.glossiness)):E.getClassName()==="PBRMaterial"?(E.metallicTexture!==null&&(I.setTexture("reflectivitySampler",E.metallicTexture),I.setMatrix("reflectivityMatrix",E.metallicTexture.getTextureMatrix())),E.metallic!==null&&I.setFloat("metallic",E.metallic),E.roughness!==null&&I.setFloat("glossiness",1-E.roughness),E.roughness!==null||E.metallic!==null||E.metallicTexture!==null?(E.albedoTexture!==null&&(I.setTexture("albedoSampler",E.albedoTexture),I.setMatrix("albedoMatrix",E.albedoTexture.getTextureMatrix())),E.albedoColor!==null&&I.setColor3("albedoColor",E.albedoColor)):(E.reflectivityTexture!==null?(I.setTexture("reflectivitySampler",E.reflectivityTexture),I.setMatrix("reflectivityMatrix",E.reflectivityTexture.getTextureMatrix())):E.reflectivityColor!==null&&I.setColor3("reflectivityColor",E.reflectivityColor),E.microSurface!==null&&I.setFloat("glossiness",E.microSurface))):E.getClassName()==="StandardMaterial"&&(E.specularTexture!==null&&(I.setTexture("reflectivitySampler",E.specularTexture),I.setMatrix("reflectivityMatrix",E.specularTexture.getTextureMatrix())),E.specularColor!==null&&I.setColor3("reflectivityColor",E.specularColor))),so(I,E,this._scene),p.useBones&&p.computeBonesUsingShaders&&p.skeleton){const L=p.skeleton;if(L.isUsingTextureForMatrices&&I.getUniformIndex("boneTextureWidth")>-1){const B=L.getTransformMatrixTexture(p);I.setTexture("boneSampler",B),I.setFloat("boneTextureWidth",4*(L.bones.length+1))}else I.setMatrices("mBones",p.skeleton.getTransformMatrices(p));this._enableVelocity&&I.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[p.uniqueId])}Me.BindMorphTargetParameters(p,I),p.morphTargetManager&&p.morphTargetManager.isUsingTextureForTargets&&p.morphTargetManager._bind(I),this._enableVelocity&&(I.setMatrix("previousWorld",this._previousTransformationMatrices[_.uniqueId].world),I.setMatrix("previousViewProjection",this._previousTransformationMatrices[_.uniqueId].viewProjection)),S&&p.hasThinInstances&&I.setMatrix("world",b),p._processRendering(_,f,I,E.fillMode,C,S,(L,B)=>{L||I.setMatrix("world",B)})}this._enableVelocity&&(this._previousTransformationMatrices[_.uniqueId].world=b.clone(),this._previousTransformationMatrices[_.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),p.skeleton&&this._copyBonesTransformationMatrices(p.skeleton.getTransformMatrices(p),this._previousBonesTransformationMatrices[_.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(f,p,_)=>{if((_||p===0)&&f.subMeshes)for(let g=0;g{let v;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(g.length){for(e.setColorWrite(!1),v=0;v{throw xt("GeometryBufferRendererSceneComponent")};class AH{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Qe.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(o){o&&o.isSupported&&(this._geometryBufferRenderer=o)},enumerable:!0,configurable:!0});Qe.prototype.enableGeometryBufferRenderer=function(o=1,e=15){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new cs(this,o,e),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};Qe.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class RH{constructor(e){this.name=Fe.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Fe.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}cs._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_GEOMETRYBUFFERRENDERER);e||(e=new RH(o),o._addComponent(e))};const IH="motionBlurPixelShader",PH=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +`;ne.ShadersStore[RH]=IH;const dA=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Ao(dA);class cs{_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===cs.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===cs.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===cs.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===cs.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===cs.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 cs.POSITION_TEXTURE_TYPE:return this._positionIndex;case cs.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case cs.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case cs.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case cs.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){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ze(0,0,0,0),this._clearDepthColor=new Ze(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,cs._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[P.PositionKind,P.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&&we.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let p=!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,p=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),p=!0),p&&(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,p=!0),i.metallic!==null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),p=!0),i.roughness!==null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),p=!0),p?(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(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.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"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.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 a=n.morphTargetManager;let l=0;a&&a.numInfluencers>0&&(l=a.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+l),a.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(r,n,l)),t&&(s.push("#define INSTANCES"),Me.PushAttributesForInstances(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),xh(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:dA,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=[];let t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const r=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};if(this._multiRenderTarget=new Vh("gBuffer",r,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:s,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=ee.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=ee.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const n=[!0],a=[!1],l=[!0];for(let f=1;f{f.bindAttachments(this.useSpecificClearForDepthTexture?c:h),f.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(f.bindAttachments(u),f.clear(this._clearDepthColor,!0,!0,!0)),f.bindAttachments(h)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const f=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(f)}});const d=f=>{const p=f.getRenderingMesh(),_=f.getEffectiveMesh(),g=this._scene,v=g.getEngine(),E=f.getMaterial();if(!E)return;if(_._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[_.uniqueId]&&(this._previousTransformationMatrices[_.uniqueId]={world:k.Identity(),viewProjection:g.getTransformMatrix()},p.skeleton)){const R=p.skeleton.getTransformMatrices(p);this._previousBonesTransformationMatrices[p.uniqueId]=this._copyBonesTransformationMatrices(R,new Float32Array(R.length))}const C=p._getInstancesRenderList(f._id,!!f.getReplacementMesh());if(C.mustReturn)return;const S=v.getCaps().instancedArrays&&(C.visibleInstances[f._id]!==null||p.hasThinInstances),b=_.getWorldMatrix();if(this.isReady(f,S)){const R=f._getDrawWrapper();if(!R)return;const I=R.effect;v.enableEffect(R),S||p._bind(f,I,E.fillMode),this._useUbo?(Me.BindSceneUniformBuffer(I,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(I.setMatrix("viewProjection",g.getTransformMatrix()),I.setMatrix("view",g.getViewMatrix()));let N;const O=p._instanceDataStorage;if(!O.isFrozen&&(E.backFaceCulling||p.overrideMaterialSideOrientation!==null)){const L=_._getWorldMatrixDeterminant();N=p.overrideMaterialSideOrientation,N===null&&(N=E.sideOrientation),L<0&&(N=N===Ie.ClockWiseSideOrientation?Ie.CounterClockWiseSideOrientation:Ie.ClockWiseSideOrientation)}else N=O.sideOrientation;if(E._preBind(R,N),E.needAlphaTesting()){const L=E.getAlphaTestTexture();L&&(I.setTexture("diffuseSampler",L),I.setMatrix("diffuseMatrix",L.getTextureMatrix()))}if(E.bumpTexture&&g.getEngine().getCaps().standardDerivatives&&we.BumpTextureEnabled&&(I.setFloat3("vBumpInfos",E.bumpTexture.coordinatesIndex,1/E.bumpTexture.level,E.parallaxScaleBias),I.setMatrix("bumpMatrix",E.bumpTexture.getTextureMatrix()),I.setTexture("bumpSampler",E.bumpTexture),I.setFloat2("vTangentSpaceParams",E.invertNormalMapX?-1:1,E.invertNormalMapY?-1:1)),this._enableReflectivity&&(E.getClassName()==="PBRMetallicRoughnessMaterial"?(E.metallicRoughnessTexture!==null&&(I.setTexture("reflectivitySampler",E.metallicRoughnessTexture),I.setMatrix("reflectivityMatrix",E.metallicRoughnessTexture.getTextureMatrix())),E.metallic!==null&&I.setFloat("metallic",E.metallic),E.roughness!==null&&I.setFloat("glossiness",1-E.roughness),E.baseTexture!==null&&(I.setTexture("albedoSampler",E.baseTexture),I.setMatrix("albedoMatrix",E.baseTexture.getTextureMatrix())),E.baseColor!==null&&I.setColor3("albedoColor",E.baseColor)):E.getClassName()==="PBRSpecularGlossinessMaterial"?(E.specularGlossinessTexture!==null?(I.setTexture("reflectivitySampler",E.specularGlossinessTexture),I.setMatrix("reflectivityMatrix",E.specularGlossinessTexture.getTextureMatrix())):E.specularColor!==null&&I.setColor3("reflectivityColor",E.specularColor),E.glossiness!==null&&I.setFloat("glossiness",E.glossiness)):E.getClassName()==="PBRMaterial"?(E.metallicTexture!==null&&(I.setTexture("reflectivitySampler",E.metallicTexture),I.setMatrix("reflectivityMatrix",E.metallicTexture.getTextureMatrix())),E.metallic!==null&&I.setFloat("metallic",E.metallic),E.roughness!==null&&I.setFloat("glossiness",1-E.roughness),E.roughness!==null||E.metallic!==null||E.metallicTexture!==null?(E.albedoTexture!==null&&(I.setTexture("albedoSampler",E.albedoTexture),I.setMatrix("albedoMatrix",E.albedoTexture.getTextureMatrix())),E.albedoColor!==null&&I.setColor3("albedoColor",E.albedoColor)):(E.reflectivityTexture!==null?(I.setTexture("reflectivitySampler",E.reflectivityTexture),I.setMatrix("reflectivityMatrix",E.reflectivityTexture.getTextureMatrix())):E.reflectivityColor!==null&&I.setColor3("reflectivityColor",E.reflectivityColor),E.microSurface!==null&&I.setFloat("glossiness",E.microSurface))):E.getClassName()==="StandardMaterial"&&(E.specularTexture!==null&&(I.setTexture("reflectivitySampler",E.specularTexture),I.setMatrix("reflectivityMatrix",E.specularTexture.getTextureMatrix())),E.specularColor!==null&&I.setColor3("reflectivityColor",E.specularColor))),so(I,E,this._scene),p.useBones&&p.computeBonesUsingShaders&&p.skeleton){const L=p.skeleton;if(L.isUsingTextureForMatrices&&I.getUniformIndex("boneTextureWidth")>-1){const B=L.getTransformMatrixTexture(p);I.setTexture("boneSampler",B),I.setFloat("boneTextureWidth",4*(L.bones.length+1))}else I.setMatrices("mBones",p.skeleton.getTransformMatrices(p));this._enableVelocity&&I.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[p.uniqueId])}Me.BindMorphTargetParameters(p,I),p.morphTargetManager&&p.morphTargetManager.isUsingTextureForTargets&&p.morphTargetManager._bind(I),this._enableVelocity&&(I.setMatrix("previousWorld",this._previousTransformationMatrices[_.uniqueId].world),I.setMatrix("previousViewProjection",this._previousTransformationMatrices[_.uniqueId].viewProjection)),S&&p.hasThinInstances&&I.setMatrix("world",b),p._processRendering(_,f,I,E.fillMode,C,S,(L,B)=>{L||I.setMatrix("world",B)})}this._enableVelocity&&(this._previousTransformationMatrices[_.uniqueId].world=b.clone(),this._previousTransformationMatrices[_.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),p.skeleton&&this._copyBonesTransformationMatrices(p.skeleton.getTransformMatrices(p),this._previousBonesTransformationMatrices[_.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(f,p,_)=>{if((_||p===0)&&f.subMeshes)for(let g=0;g{let v;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(g.length){for(e.setColorWrite(!1),v=0;v{throw xt("GeometryBufferRendererSceneComponent")};class PH{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Qe.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(o){o&&o.isSupported&&(this._geometryBufferRenderer=o)},enumerable:!0,configurable:!0});Qe.prototype.enableGeometryBufferRenderer=function(o=1,e=15){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new cs(this,o,e),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};Qe.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class MH{constructor(e){this.name=Fe.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Fe.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}cs._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_GEOMETRYBUFFERRENDERER);e||(e=new MH(o),o._addComponent(e))};const DH="motionBlurPixelShader",OH=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; #ifdef OBJECT_BASED uniform sampler2D velocitySampler; #else @@ -10555,17 +10555,17 @@ gl_FragColor=result/float(nSamples); gl_FragColor=texture2D(textureSampler,vUV); #endif } -`;ne.ShadersStore[IH]=PH;class rc extends lt{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,a,l=0,h=!1,c=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,a,`#define GEOMETRY_SUPPORTED +`;ne.ShadersStore[DH]=OH;class nc extends lt{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,a,l=0,h=!1,c=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,a,`#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 AH)),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 G.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=k.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 Re(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(cs.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=K.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 Re(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(cs.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 Xe.Parse(()=>new rc(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}A([D()],rc.prototype,"motionStrength",void 0);A([D()],rc.prototype,"motionBlurSamples",null);A([D()],rc.prototype,"isObjectBased",null);j("BABYLON.MotionBlurPostProcess",rc);const MH="refractionPixelShader",DH="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);}";ne.ShadersStore[MH]=DH;class nc extends lt{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,a,l,h,c){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,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 ee(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 Xe.Parse(()=>new nc(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],nc.prototype,"color",void 0);A([D()],nc.prototype,"depth",void 0);A([D()],nc.prototype,"colorLevel",void 0);A([D()],nc.prototype,"refractionTextureUrl",void 0);j("BABYLON.RefractionPostProcess",nc);const OH="sharpenPixelShader",NH=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#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 PH)),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 G.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=k.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 Re(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(cs.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=K.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 Re(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(cs.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 Xe.Parse(()=>new nc(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}A([D()],nc.prototype,"motionStrength",void 0);A([D()],nc.prototype,"motionBlurSamples",null);A([D()],nc.prototype,"isObjectBased",null);j("BABYLON.MotionBlurPostProcess",nc);const NH="refractionPixelShader",wH="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);}";ne.ShadersStore[NH]=wH;class ac extends lt{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,a,l,h,c){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,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 ee(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 Xe.Parse(()=>new ac(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}A([D()],ac.prototype,"color",void 0);A([D()],ac.prototype,"depth",void 0);A([D()],ac.prototype,"colorLevel",void 0);A([D()],ac.prototype,"refractionTextureUrl",void 0);j("BABYLON.RefractionPostProcess",ac);const FH="sharpenPixelShader",LH=`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.);}`;ne.ShadersStore[OH]=NH;class Ru extends lt{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,a,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 Xe.Parse(()=>new Ru(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],Ru.prototype,"colorAmount",void 0);A([D()],Ru.prototype,"edgeAmount",void 0);j("BABYLON.SharpenPostProcess",Ru);class Iu{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(fe.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(fe.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=fe.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){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(){}}A([D()],Iu.prototype,"_name",void 0);class wH{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(Qe.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let o=this._getComponent(Fe.NAME_POSTPROCESSRENDERPIPELINEMANAGER);o||(o=new FH(this),this._addComponent(o)),this._postProcessRenderPipelineManager=new wH}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class FH{constructor(e){this.name=Fe.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Fe.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 zr extends Iu{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 bC(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new yC(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new bC(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new il("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,ee.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Pi(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new Au("Grain",1,null,ee.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Pi(a,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?fe.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 _T("imageProcessing",1,null,ee.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Pi(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 yu("fxaa",1,null,ee.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Pi(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&&G.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;tnew zr(e._name,e._name._hdr,t),e,t,i)}}A([D()],zr.prototype,"sharpenEnabled",null);A([D()],zr.prototype,"bloomKernel",null);A([D()],zr.prototype,"_bloomWeight",void 0);A([D()],zr.prototype,"_bloomThreshold",void 0);A([D()],zr.prototype,"_hdr",void 0);A([D()],zr.prototype,"bloomWeight",null);A([D()],zr.prototype,"bloomThreshold",null);A([D()],zr.prototype,"bloomScale",null);A([D()],zr.prototype,"bloomEnabled",null);A([D()],zr.prototype,"depthOfFieldEnabled",null);A([D()],zr.prototype,"depthOfFieldBlurLevel",null);A([D()],zr.prototype,"fxaaEnabled",null);A([D()],zr.prototype,"samples",null);A([D()],zr.prototype,"imageProcessingEnabled",null);A([D()],zr.prototype,"glowLayerEnabled",null);A([D()],zr.prototype,"chromaticAberrationEnabled",null);A([D()],zr.prototype,"grainEnabled",null);j("BABYLON.DefaultRenderingPipeline",zr);const LH="lensHighlightsPixelShader",BH=`uniform sampler2D textureSampler; +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;ne.ShadersStore[FH]=LH;class Ru extends lt{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,a=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,a,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 Xe.Parse(()=>new Ru(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],Ru.prototype,"colorAmount",void 0);A([D()],Ru.prototype,"edgeAmount",void 0);j("BABYLON.SharpenPostProcess",Ru);class Iu{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(fe.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(fe.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=fe.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){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(){}}A([D()],Iu.prototype,"_name",void 0);class BH{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(Qe.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let o=this._getComponent(Fe.NAME_POSTPROCESSRENDERPIPELINEMANAGER);o||(o=new VH(this),this._addComponent(o)),this._postProcessRenderPipelineManager=new BH}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class VH{constructor(e){this.name=Fe.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Fe.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 zr extends Iu{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 AC(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new RC(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new AC(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new il("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,ee.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Pi(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new Au("Grain",1,null,ee.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Pi(a,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?fe.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 gT("imageProcessing",1,null,ee.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Pi(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 yu("fxaa",1,null,ee.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Pi(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&&G.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;tnew zr(e._name,e._name._hdr,t),e,t,i)}}A([D()],zr.prototype,"sharpenEnabled",null);A([D()],zr.prototype,"bloomKernel",null);A([D()],zr.prototype,"_bloomWeight",void 0);A([D()],zr.prototype,"_bloomThreshold",void 0);A([D()],zr.prototype,"_hdr",void 0);A([D()],zr.prototype,"bloomWeight",null);A([D()],zr.prototype,"bloomThreshold",null);A([D()],zr.prototype,"bloomScale",null);A([D()],zr.prototype,"bloomEnabled",null);A([D()],zr.prototype,"depthOfFieldEnabled",null);A([D()],zr.prototype,"depthOfFieldBlurLevel",null);A([D()],zr.prototype,"fxaaEnabled",null);A([D()],zr.prototype,"samples",null);A([D()],zr.prototype,"imageProcessingEnabled",null);A([D()],zr.prototype,"glowLayerEnabled",null);A([D()],zr.prototype,"chromaticAberrationEnabled",null);A([D()],zr.prototype,"grainEnabled",null);j("BABYLON.DefaultRenderingPipeline",zr);const UH="lensHighlightsPixelShader",kH=`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;} @@ -10578,7 +10578,7 @@ blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blur #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;}`;ne.ShadersStore[LH]=BH;const VH="depthOfFieldPixelShader",UH=`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; +blurred/=39.0;gl_FragColor=blurred;}`;ne.ShadersStore[UH]=kH;const GH="depthOfFieldPixelShader",zH=`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 @@ -10607,7 +10607,7 @@ float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor= 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;}} -`;ne.ShadersStore[VH]=UH;class kH{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const GH="ssao2PixelShader",zH=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +`;ne.ShadersStore[GH]=zH;class WH{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const HH="ssao2PixelShader",XH=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSAO float scales[16]=float[16]( 0.1, @@ -10662,20 +10662,20 @@ result/=weightSum; #endif gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;} #endif -`;ne.ShadersStore[GH]=zH;const WH="ssaoCombinePixelShader",HH=`uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; +`;ne.ShadersStore[HH]=XH;const YH="ssaoCombinePixelShader",$H=`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 } -`;ne.ShadersStore[WH]=HH;class hr extends Iu{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=ht.LastCreatedEngine;return e?e._features.supportSSAO2:!1}get scene(){return this._scene}constructor(e,t,i,s,r=!1,n=0){var a,l;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){G.Error("The current engine does not support SSAO 2.");return}const h=this._ratio.ssaoRatio||i,c=this._ratio.blurRatio||i;this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),!((a=t.geometryBufferRenderer)===null||a===void 0)&&a.generateNormalsInWorldSpace&&G.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!")):(t.enablePrePassRenderer(),!((l=t.prePassRenderer)===null||l===void 0)&&l.generateNormalsInWorldSpace&&G.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!")),this._createRandomTexture(),this._originalColorPostProcess=new el("SSAOOriginalSceneColor",1,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,n),this._createBlurPostProcess(h,c,this._textureType),this._createSSAOCombinePostProcess(c,this._textureType),this.addEffect(new Pi(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Pi(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;tthis._originalColorPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Pi(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{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)])},a.samples=this.textureSamples,a}_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 T(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{var n,a,l,h;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===et.PERSPECTIVE_CAMERA)r.setMatrix3x3("depthProjection",hr.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 c=this._scene.getEngine().getRenderWidth()/2,u=this._scene.getEngine().getRenderHeight()/2,d=(n=this._scene.activeCamera.orthoLeft)!==null&&n!==void 0?n:-c,f=(a=this._scene.activeCamera.orthoRight)!==null&&a!==void 0?a:c,p=(l=this._scene.activeCamera.orthoBottom)!==null&&l!==void 0?l:-u,_=(h=this._scene.activeCamera.orthoTop)!==null&&h!==void 0?h:u;r.setMatrix3x3("depthProjection",hr.ORTHO_DEPTH_PROJECTION),r.setFloat("xViewport",(f-d)*.5),r.setFloat("yViewport",(_-p)*.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 kH)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new lt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const s=this._scene.activeCamera.viewport;i.setVector4("viewport",K.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=Re.Zero();for(let r=0;rnew hr(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}hr.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];hr.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];A([D()],hr.prototype,"totalStrength",void 0);A([D()],hr.prototype,"maxZ",void 0);A([D()],hr.prototype,"minZAspect",void 0);A([D("epsilon")],hr.prototype,"_epsilon",void 0);A([D("samples")],hr.prototype,"_samples",void 0);A([D("textureSamples")],hr.prototype,"_textureSamples",void 0);A([D()],hr.prototype,"_forceGeometryBuffer",void 0);A([D()],hr.prototype,"_ratio",void 0);A([D()],hr.prototype,"_textureType",void 0);A([D()],hr.prototype,"radius",void 0);A([D()],hr.prototype,"base",void 0);A([D("bypassBlur")],hr.prototype,"_bypassBlur",void 0);A([D("expensiveBlur")],hr.prototype,"_expensiveBlur",void 0);A([D()],hr.prototype,"bilateralSamples",void 0);A([D()],hr.prototype,"bilateralSoften",void 0);A([D()],hr.prototype,"bilateralTolerance",void 0);j("BABYLON.SSAO2RenderingPipeline",hr);const XH="ssaoPixelShader",YH=`uniform sampler2D textureSampler;varying vec2 vUV; +#define EPSILON ${this.epsilon.toFixed(4)}`}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();const i=this._getDefinesForSSAO(),s=["randomSampler","depthSampler","normalSampler"];this._ssaoPostProcess=new lt("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],s,e,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=r=>{var n,a,l,h;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===et.PERSPECTIVE_CAMERA)r.setMatrix3x3("depthProjection",hr.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 c=this._scene.getEngine().getRenderWidth()/2,u=this._scene.getEngine().getRenderHeight()/2,d=(n=this._scene.activeCamera.orthoLeft)!==null&&n!==void 0?n:-c,f=(a=this._scene.activeCamera.orthoRight)!==null&&a!==void 0?a:c,p=(l=this._scene.activeCamera.orthoBottom)!==null&&l!==void 0?l:-u,_=(h=this._scene.activeCamera.orthoTop)!==null&&h!==void 0?h:u;r.setMatrix3x3("depthProjection",hr.ORTHO_DEPTH_PROJECTION),r.setFloat("xViewport",(f-d)*.5),r.setFloat("yViewport",(_-p)*.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 WH)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new lt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const s=this._scene.activeCamera.viewport;i.setVector4("viewport",K.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=Re.Zero();for(let r=0;rnew hr(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}hr.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];hr.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];A([D()],hr.prototype,"totalStrength",void 0);A([D()],hr.prototype,"maxZ",void 0);A([D()],hr.prototype,"minZAspect",void 0);A([D("epsilon")],hr.prototype,"_epsilon",void 0);A([D("samples")],hr.prototype,"_samples",void 0);A([D("textureSamples")],hr.prototype,"_textureSamples",void 0);A([D()],hr.prototype,"_forceGeometryBuffer",void 0);A([D()],hr.prototype,"_ratio",void 0);A([D()],hr.prototype,"_textureType",void 0);A([D()],hr.prototype,"radius",void 0);A([D()],hr.prototype,"base",void 0);A([D("bypassBlur")],hr.prototype,"_bypassBlur",void 0);A([D("expensiveBlur")],hr.prototype,"_expensiveBlur",void 0);A([D()],hr.prototype,"bilateralSamples",void 0);A([D()],hr.prototype,"bilateralSoften",void 0);A([D()],hr.prototype,"bilateralTolerance",void 0);j("BABYLON.SSAO2RenderingPipeline",hr);const KH="ssaoPixelShader",qH=`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);} @@ -10684,8 +10684,8 @@ void main() {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 -`;ne.ShadersStore[XH]=YH;class cp extends Iu{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 el("SSAOOriginalSceneColor",n,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(r),this._createBlurPostProcess(r),this._createSSAOCombinePostProcess(n),this.addEffect(new Pi(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Pi(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{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 lt("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,ee.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 lt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",K.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let s=0;sthis._originalColorPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new Pi(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new Pi(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{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 lt("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,ee.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 lt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,ee.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",K.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let s=0;s{const d=this._geometryBufferRenderer,f=this._prePassRenderer;if(!f&&!d)return;if(d){const v=d.getTextureIndex(cs.POSITION_TEXTURE_TYPE),E=d.getTextureIndex(cs.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",d.getGBuffer().textures[1]),u.setTexture("positionSampler",d.getGBuffer().textures[v]),u.setTexture("reflectivitySampler",d.getGBuffer().textures[E])}else if(f){const v=f.getIndex(1),E=f.getIndex(3),C=f.getIndex(6);u.setTexture("normalSampler",f.getRenderTarget().textures[C]),u.setTexture("positionSampler",f.getRenderTarget().textures[v]),u.setTexture("reflectivitySampler",f.getRenderTarget().textures[E])}const p=t.activeCamera;if(!p)return;const _=p.getViewMatrix(!0),g=p.getProjectionMatrix(!0);u.setMatrix("projection",g),u.setMatrix("view",_),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 Xe.Parse(()=>new no(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],no.prototype,"threshold",void 0);A([D()],no.prototype,"strength",void 0);A([D()],no.prototype,"reflectionSpecularFalloffExponent",void 0);A([D()],no.prototype,"step",void 0);A([D()],no.prototype,"roughnessFactor",void 0);A([D()],no.prototype,"enableSmoothReflections",null);A([D()],no.prototype,"reflectionSamples",null);A([D()],no.prototype,"smoothSteps",null);j("BABYLON.ScreenSpaceReflectionPostProcess",no);const jH="standardPixelShader",QH=`uniform sampler2D textureSampler;varying vec2 vUV; +`,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&&G.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&&G.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!"),this._prePassEffectConfiguration=new jH}this._updateEffectDefines(),this.onApply=u=>{const d=this._geometryBufferRenderer,f=this._prePassRenderer;if(!f&&!d)return;if(d){const v=d.getTextureIndex(cs.POSITION_TEXTURE_TYPE),E=d.getTextureIndex(cs.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",d.getGBuffer().textures[1]),u.setTexture("positionSampler",d.getGBuffer().textures[v]),u.setTexture("reflectivitySampler",d.getGBuffer().textures[E])}else if(f){const v=f.getIndex(1),E=f.getIndex(3),C=f.getIndex(6);u.setTexture("normalSampler",f.getRenderTarget().textures[C]),u.setTexture("positionSampler",f.getRenderTarget().textures[v]),u.setTexture("reflectivitySampler",f.getRenderTarget().textures[E])}const p=t.activeCamera;if(!p)return;const _=p.getViewMatrix(!0),g=p.getProjectionMatrix(!0);u.setMatrix("projection",g),u.setMatrix("view",_),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 Xe.Parse(()=>new no(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],no.prototype,"threshold",void 0);A([D()],no.prototype,"strength",void 0);A([D()],no.prototype,"reflectionSpecularFalloffExponent",void 0);A([D()],no.prototype,"step",void 0);A([D()],no.prototype,"roughnessFactor",void 0);A([D()],no.prototype,"enableSmoothReflections",null);A([D()],no.prototype,"reflectionSamples",null);A([D()],no.prototype,"smoothSteps",null);j("BABYLON.ScreenSpaceReflectionPostProcess",no);const JH="standardPixelShader",eX=`uniform sampler2D textureSampler;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS #if defined(PASS_POST_PROCESS) void main(void) @@ -10866,14 +10866,14 @@ uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} gl_FragColor=result/float(nSamples);} #endif -`;ne.ShadersStore[jH]=QH;class bi extends Iu{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(` +`;ne.ShadersStore[JH]=eX;class bi extends Iu{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()){G.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 no("HDRPass",t,e,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new Pi(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new lt("HDRPass","standard",[],[],e,null,ee.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 Pi(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 lt("HDRDepthOfFieldSource","standard",[],[],e,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Pi(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new lt("HDRVLSFinal","standard",[],[],e,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Pi(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new lt("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Pi(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new lt("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new Pi(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 yu("fxaa",1,null,ee.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new Pi(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&G.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 lt("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=s=>{let r=0;const n=this.downSampleX4PostProcess.width,a=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/a),r+=2;s.setArray2("dsOffsets",i)},this.addEffect(new Pi(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new lt("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,ee.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 Pi(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new or("HDRBlurH_"+i,new Re(1,0),this[s],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new or("HDRBlurV_"+i,new Re(0,1),this[s],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{const l=n.width/r.getRenderWidth();n.kernel=this[s]*l}),a.onActivateObservable.add(()=>{const l=a.height/r.getRenderHeight();a.kernel=this.horizontalBlur?64*l:this[s]*l}),this.addEffect(new Pi(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new Pi(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new lt("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,ee.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 Pi(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new lt("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS #define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const r=Re.Zero();this.volumetricLightPostProcess.onApply=n=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const a=this.sourceLight.getShadowGenerator();n.setTexture("shadowMapSampler",a.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",a.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 Pi(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new lt("HDRVLSMerge","standard",[],["originalSampler"],t,null,ee.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 Pi(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,bi.LuminanceSteps);this.luminancePostProcess=new lt("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=n=>{const a=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;s[0]=-.5*a,s[1]=.5*l,s[2]=.5*a,s[3]=.5*l,s[4]=-.5*a,s[5]=-.5*l,s[6]=.5*a,s[7]=-.5*l,n.setArray2("lumOffsets",s)},this.addEffect(new Pi(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let n=bi.LuminanceSteps-1;n>=0;n--){i=Math.pow(3,n);let a=`#define LUMINANCE_DOWN_SAMPLE `;n===0&&(a+="#define FINAL_DOWN_SAMPLER");const l=new lt("HDRLuminanceDownSample"+n,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,a,t);this.luminanceDownSamplePostProcesses.push(l)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((n,a)=>{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),a===this.luminanceDownSamplePostProcesses.length-1?r=this.luminancePostProcess:r=n},a===this.luminanceDownSamplePostProcesses.length-1&&(n.onAfterRender=()=>{const h=e.getEngine().readPixels(0,0,1,1),c=new Dt(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 Pi(e.getEngine(),"HDRLuminanceDownSample"+a,()=>n,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new lt("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` -`),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=a=>{if(a.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const l=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*l?s-=this.hdrIncreaseRate*l:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=ye.Clamp(s,this.hdrMinimumLuminance,1e20),a.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new Pi(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new lt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new Pi(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new lt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new Pi(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new Re(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=k.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=k.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 a=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let h=T.Dot(a.toVector3(),new T(1,0,0))+T.Dot(l.toVector3(),new T(0,0,1));h*=4;const c=k.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 lt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,ee.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 Pi(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new rc("HDRMotionBlur",e,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new lt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR -#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,s=k.Identity();const r=k.Identity();let n=k.Identity();const a=Re.Zero();this.motionBlurPostProcess.onApply=l=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),l.setMatrix("inverseViewProjection",r),l.setMatrix("prevViewProjection",s),s=n,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,l.setVector2("screenSize",a),i=e.getEngine().getFps()/60,l.setFloat("motionScale",i),l.setFloat("motionStrength",this.motionStrength),l.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new Pi(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;enew bi(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Xe.Parse(()=>s.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),s}}bi.LuminanceSteps=6;A([D()],bi.prototype,"brightThreshold",void 0);A([D()],bi.prototype,"blurWidth",void 0);A([D()],bi.prototype,"horizontalBlur",void 0);A([D()],bi.prototype,"exposure",null);A([Jt("lensTexture")],bi.prototype,"lensTexture",void 0);A([D()],bi.prototype,"volumetricLightCoefficient",void 0);A([D()],bi.prototype,"volumetricLightPower",void 0);A([D()],bi.prototype,"volumetricLightBlurScale",void 0);A([D()],bi.prototype,"hdrMinimumLuminance",void 0);A([D()],bi.prototype,"hdrDecreaseRate",void 0);A([D()],bi.prototype,"hdrIncreaseRate",void 0);A([D()],bi.prototype,"hdrAutoExposure",null);A([Jt("lensColorTexture")],bi.prototype,"lensColorTexture",void 0);A([D()],bi.prototype,"lensFlareStrength",void 0);A([D()],bi.prototype,"lensFlareGhostDispersal",void 0);A([D()],bi.prototype,"lensFlareHaloWidth",void 0);A([D()],bi.prototype,"lensFlareDistortionStrength",void 0);A([D()],bi.prototype,"lensFlareBlurWidth",void 0);A([Jt("lensStarTexture")],bi.prototype,"lensStarTexture",void 0);A([Jt("lensFlareDirtTexture")],bi.prototype,"lensFlareDirtTexture",void 0);A([D()],bi.prototype,"depthOfFieldDistance",void 0);A([D()],bi.prototype,"depthOfFieldBlurWidth",void 0);A([D()],bi.prototype,"motionStrength",null);A([D()],bi.prototype,"objectBasedMotionBlur",null);A([D()],bi.prototype,"_ratio",void 0);A([D()],bi.prototype,"BloomEnabled",null);A([D()],bi.prototype,"DepthOfFieldEnabled",null);A([D()],bi.prototype,"LensFlareEnabled",null);A([D()],bi.prototype,"HDREnabled",null);A([D()],bi.prototype,"VLSEnabled",null);A([D()],bi.prototype,"MotionBlurEnabled",null);A([D()],bi.prototype,"fxaaEnabled",null);A([D()],bi.prototype,"screenSpaceReflectionsEnabled",null);A([D()],bi.prototype,"volumetricLightStepsCount",null);A([D()],bi.prototype,"motionBlurSamples",null);A([D()],bi.prototype,"samples",null);j("BABYLON.StandardRenderingPipeline",bi);class ZH{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const JH="screenSpaceRayTrace",eX=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +`),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=a=>{if(a.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const l=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*l?s-=this.hdrIncreaseRate*l:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=ye.Clamp(s,this.hdrMinimumLuminance,1e20),a.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new Pi(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new lt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new Pi(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new lt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new Pi(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new Re(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=k.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=k.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 a=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let h=T.Dot(a.toVector3(),new T(1,0,0))+T.Dot(l.toVector3(),new T(0,0,1));h*=4;const c=k.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 lt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,ee.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 Pi(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new nc("HDRMotionBlur",e,t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new lt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,ee.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR +#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,s=k.Identity();const r=k.Identity();let n=k.Identity();const a=Re.Zero();this.motionBlurPostProcess.onApply=l=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),l.setMatrix("inverseViewProjection",r),l.setMatrix("prevViewProjection",s),s=n,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,l.setVector2("screenSize",a),i=e.getEngine().getFps()/60,l.setFloat("motionScale",i),l.setFloat("motionStrength",this.motionStrength),l.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new Pi(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;enew bi(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Xe.Parse(()=>s.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),s}}bi.LuminanceSteps=6;A([D()],bi.prototype,"brightThreshold",void 0);A([D()],bi.prototype,"blurWidth",void 0);A([D()],bi.prototype,"horizontalBlur",void 0);A([D()],bi.prototype,"exposure",null);A([Jt("lensTexture")],bi.prototype,"lensTexture",void 0);A([D()],bi.prototype,"volumetricLightCoefficient",void 0);A([D()],bi.prototype,"volumetricLightPower",void 0);A([D()],bi.prototype,"volumetricLightBlurScale",void 0);A([D()],bi.prototype,"hdrMinimumLuminance",void 0);A([D()],bi.prototype,"hdrDecreaseRate",void 0);A([D()],bi.prototype,"hdrIncreaseRate",void 0);A([D()],bi.prototype,"hdrAutoExposure",null);A([Jt("lensColorTexture")],bi.prototype,"lensColorTexture",void 0);A([D()],bi.prototype,"lensFlareStrength",void 0);A([D()],bi.prototype,"lensFlareGhostDispersal",void 0);A([D()],bi.prototype,"lensFlareHaloWidth",void 0);A([D()],bi.prototype,"lensFlareDistortionStrength",void 0);A([D()],bi.prototype,"lensFlareBlurWidth",void 0);A([Jt("lensStarTexture")],bi.prototype,"lensStarTexture",void 0);A([Jt("lensFlareDirtTexture")],bi.prototype,"lensFlareDirtTexture",void 0);A([D()],bi.prototype,"depthOfFieldDistance",void 0);A([D()],bi.prototype,"depthOfFieldBlurWidth",void 0);A([D()],bi.prototype,"motionStrength",null);A([D()],bi.prototype,"objectBasedMotionBlur",null);A([D()],bi.prototype,"_ratio",void 0);A([D()],bi.prototype,"BloomEnabled",null);A([D()],bi.prototype,"DepthOfFieldEnabled",null);A([D()],bi.prototype,"LensFlareEnabled",null);A([D()],bi.prototype,"HDREnabled",null);A([D()],bi.prototype,"VLSEnabled",null);A([D()],bi.prototype,"MotionBlurEnabled",null);A([D()],bi.prototype,"fxaaEnabled",null);A([D()],bi.prototype,"screenSpaceReflectionsEnabled",null);A([D()],bi.prototype,"volumetricLightStepsCount",null);A([D()],bi.prototype,"motionBlurSamples",null);A([D()],bi.prototype,"samples",null);j("BABYLON.StandardRenderingPipeline",bi);class tX{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const iX="screenSpaceRayTrace",sX=`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 @@ -10984,7 +10984,7 @@ ndc.z=-projection[2].z-projection[3].z/depth; 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;} -`;ne.IncludesShadersStore[JH]=eX;const tX="screenSpaceReflection2PixelShader",iX=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +`;ne.IncludesShadersStore[iX]=sX;const rX="screenSpaceReflection2PixelShader",nX=`#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 @@ -11130,7 +11130,7 @@ gl_FragColor=vec4(finalColor,colorFull.a); gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); #endif } -`;ne.ShadersStore[tX]=iX;const sX="screenSpaceReflection2BlurPixelShader",rX=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +`;ne.ShadersStore[rX]=nX;const aX="screenSpaceReflection2BlurPixelShader",oX=`#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) @@ -11141,7 +11141,7 @@ 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);} -`;ne.ShadersStore[sX]=rX;const nX="screenSpaceReflection2BlurCombinerPixelShader",aX=`uniform sampler2D textureSampler; +`;ne.ShadersStore[aX]=oX;const lX="screenSpaceReflection2BlurCombinerPixelShader",hX=`uniform sampler2D textureSampler; uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; #include #ifdef SSR_BLEND_WITH_FRESNEL @@ -11173,12 +11173,12 @@ finalColor=toGammaSpace(finalColor); gl_FragColor=vec4(finalColor,color.a); #endif } -`;ne.ShadersStore[nX]=aX;const oX=k.Compose(new T(.5,.5,.5),Se.Identity(),new T(.5,.5,.5)),lX=k.Compose(new T(.5,.5,1),Se.Identity(),new T(.5,.5,0));class es extends Iu{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,n.generateNormalsInWorldSpace&&G.Error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{const n=t.enablePrePassRenderer();n&&(n.useSpecificClearForDepthTexture=!0,n.markAsDirty(),n.generateNormalsInWorldSpace&&G.Error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}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 e,t;const i=this._scene.getEngine(),s=this._prePassRenderer;let r={width:i.getRenderWidth(),height:i.getRenderHeight()};if(s&&((e=this._scene.activeCamera)===null||e===void 0?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const n=s.getRenderTarget();n&&n.textures&&(r=n.textures[s.getIndex(4)].getSize())}else!((t=this._ssrPostProcess)===null||t===void 0)&&t.inputTexture&&(r.width=this._ssrPostProcess.inputTexture.width,r.height=this._ssrPostProcess.inputTexture.height);return r}_updateEffectDefines(){var e;const t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(e=this._ssrPostProcess)===null||e===void 0||e.updateEffect(t.join(` -`))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const t=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=(e=this._cameras)===null||e===void 0?void 0:e[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new ic(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 Pi(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new Pi(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new Pi(t,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(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))!==null&&e!==void 0?e:-1;t!==-1&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,s;for(let r=0;r{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(cs.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(K.Matrix[0]),r.invertToRef(K.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",K.Matrix[1]),e.setMatrix("invProjectionMatrix",K.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 a=this._getTextureSize();k.ScalingToRef(a.width,a.height,1,K.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?lX:oX,K.Matrix[3]),K.Matrix[3].multiplyToRef(K.Matrix[2],K.Matrix[4]),e.setMatrix("projectionPixel",K.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 ZH)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new lt("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 n,a;const l=(a=(n=this._blurPostProcessX)===null||n===void 0?void 0:n.inputTexture.width)!==null&&a!==void 0?a:this._scene.getEngine().getRenderWidth();r.setFloat2("texelOffsetScale",this._blurDispersionStrength/l,0)}),this._blurPostProcessY=new lt("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 n,a;const l=(a=(n=this._blurPostProcessY)===null||n===void 0?void 0:n.inputTexture.height)!==null&&a!==void 0?a:this._scene.getEngine().getRenderHeight();r.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/l)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+=`#define SSRAYTRACE_DEBUG +`;ne.ShadersStore[lX]=hX;const cX=k.Compose(new T(.5,.5,.5),Se.Identity(),new T(.5,.5,.5)),uX=k.Compose(new T(.5,.5,1),Se.Identity(),new T(.5,.5,0));class es extends Iu{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,n.generateNormalsInWorldSpace&&G.Error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{const n=t.enablePrePassRenderer();n&&(n.useSpecificClearForDepthTexture=!0,n.markAsDirty(),n.generateNormalsInWorldSpace&&G.Error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}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 e,t;const i=this._scene.getEngine(),s=this._prePassRenderer;let r={width:i.getRenderWidth(),height:i.getRenderHeight()};if(s&&((e=this._scene.activeCamera)===null||e===void 0?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const n=s.getRenderTarget();n&&n.textures&&(r=n.textures[s.getIndex(4)].getSize())}else!((t=this._ssrPostProcess)===null||t===void 0)&&t.inputTexture&&(r.width=this._ssrPostProcess.inputTexture.width,r.height=this._ssrPostProcess.inputTexture.height);return r}_updateEffectDefines(){var e;const t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),this._reflectivityThreshold===0&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(e=this._ssrPostProcess)===null||e===void 0||e.updateEffect(t.join(` +`))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;const t=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=(e=this._cameras)===null||e===void 0?void 0:e[0];i&&(this._depthRendererCamera=i,this._depthRenderer=new sc(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 Pi(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new Pi(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new Pi(t,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(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))!==null&&e!==void 0?e:-1;t!==-1&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,s;for(let r=0;r{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(cs.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(K.Matrix[0]),r.invertToRef(K.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",K.Matrix[1]),e.setMatrix("invProjectionMatrix",K.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 a=this._getTextureSize();k.ScalingToRef(a.width,a.height,1,K.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?uX:cX,K.Matrix[3]),K.Matrix[3].multiplyToRef(K.Matrix[2],K.Matrix[4]),e.setMatrix("projectionPixel",K.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 tX)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new lt("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 n,a;const l=(a=(n=this._blurPostProcessX)===null||n===void 0?void 0:n.inputTexture.width)!==null&&a!==void 0?a:this._scene.getEngine().getRenderWidth();r.setFloat2("texelOffsetScale",this._blurDispersionStrength/l,0)}),this._blurPostProcessY=new lt("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 n,a;const l=(a=(n=this._blurPostProcessY)===null||n===void 0?void 0:n.inputTexture.height)!==null&&a!==void 0?a:this._scene.getEngine().getRenderHeight();r.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/l)});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 lt("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 n;const a=this._geometryBufferRenderer,l=this._prePassRenderer;if(!(!l&&!a)){if(l&&((n=this._scene.activeCamera)===null||n===void 0?void 0:n._getFirstPostProcess())===this._ssrPostProcess){const h=l.getRenderTarget();h&&h.textures&&r.setTexture("mainSampler",h.textures[l.getIndex(4)])}else r.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(a){const h=a.getTextureIndex(cs.REFLECTIVITY_TEXTURE_TYPE);r.setTexture("reflectivitySampler",a.getGBuffer().textures[h]),this.useFresnel&&(r.setTexture("normalSampler",a.getGBuffer().textures[1]),r.setTexture("depthSampler",a.getGBuffer().textures[0]))}else if(l){const h=l.getIndex(3);if(r.setTexture("reflectivitySampler",l.getRenderTarget().textures[h]),this.useFresnel){const c=l.getIndex(5),u=l.getIndex(6);r.setTexture("normalSampler",l.getRenderTarget().textures[u]),r.setTexture("depthSampler",l.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(K.Matrix[0]),r.setMatrix("projection",c),r.setMatrix("invProjectionMatrix",K.Matrix[0])}}}})}serialize(){const e=Xe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Xe.Parse(()=>new es(e._name,t,e._ratio),e,t,i)}}A([D()],es.prototype,"samples",null);A([D()],es.prototype,"maxDistance",void 0);A([D()],es.prototype,"step",void 0);A([D()],es.prototype,"thickness",void 0);A([D()],es.prototype,"strength",void 0);A([D()],es.prototype,"reflectionSpecularFalloffExponent",void 0);A([D()],es.prototype,"maxSteps",void 0);A([D()],es.prototype,"roughnessFactor",void 0);A([D()],es.prototype,"selfCollisionNumSkip",void 0);A([D()],es.prototype,"_reflectivityThreshold",void 0);A([D("_ssrDownsample")],es.prototype,"_ssrDownsample",void 0);A([D()],es.prototype,"ssrDownsample",null);A([D("blurDispersionStrength")],es.prototype,"_blurDispersionStrength",void 0);A([D("blurDownsample")],es.prototype,"_blurDownsample",void 0);A([D("enableSmoothReflections")],es.prototype,"_enableSmoothReflections",void 0);A([D("environmentTexture")],es.prototype,"_environmentTexture",void 0);A([D("environmentTextureIsProbe")],es.prototype,"_environmentTextureIsProbe",void 0);A([D("attenuateScreenBorders")],es.prototype,"_attenuateScreenBorders",void 0);A([D("attenuateIntersectionDistance")],es.prototype,"_attenuateIntersectionDistance",void 0);A([D("attenuateIntersectionIterations")],es.prototype,"_attenuateIntersectionIterations",void 0);A([D("attenuateFacingCamera")],es.prototype,"_attenuateFacingCamera",void 0);A([D("attenuateBackfaceReflection")],es.prototype,"_attenuateBackfaceReflection",void 0);A([D("clipToFrustum")],es.prototype,"_clipToFrustum",void 0);A([D("useFresnel")],es.prototype,"_useFresnel",void 0);A([D("enableAutomaticThicknessComputation")],es.prototype,"_enableAutomaticThicknessComputation",void 0);A([D("backfaceDepthTextureDownsample")],es.prototype,"_backfaceDepthTextureDownsample",void 0);A([D("backfaceForceDepthWriteTransparentMeshes")],es.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);A([D("isEnabled")],es.prototype,"_isEnabled",void 0);A([D("inputTextureColorIsInGammaSpace")],es.prototype,"_inputTextureColorIsInGammaSpace",void 0);A([D("generateOutputInGammaSpace")],es.prototype,"_generateOutputInGammaSpace",void 0);A([D("debug")],es.prototype,"_debug",void 0);j("BABYLON.SSRRenderingPipeline",es);const hX="tonemapPixelShader",cX=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +`,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new lt("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 n;const a=this._geometryBufferRenderer,l=this._prePassRenderer;if(!(!l&&!a)){if(l&&((n=this._scene.activeCamera)===null||n===void 0?void 0:n._getFirstPostProcess())===this._ssrPostProcess){const h=l.getRenderTarget();h&&h.textures&&r.setTexture("mainSampler",h.textures[l.getIndex(4)])}else r.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(a){const h=a.getTextureIndex(cs.REFLECTIVITY_TEXTURE_TYPE);r.setTexture("reflectivitySampler",a.getGBuffer().textures[h]),this.useFresnel&&(r.setTexture("normalSampler",a.getGBuffer().textures[1]),r.setTexture("depthSampler",a.getGBuffer().textures[0]))}else if(l){const h=l.getIndex(3);if(r.setTexture("reflectivitySampler",l.getRenderTarget().textures[h]),this.useFresnel){const c=l.getIndex(5),u=l.getIndex(6);r.setTexture("normalSampler",l.getRenderTarget().textures[u]),r.setTexture("depthSampler",l.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(K.Matrix[0]),r.setMatrix("projection",c),r.setMatrix("invProjectionMatrix",K.Matrix[0])}}}})}serialize(){const e=Xe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Xe.Parse(()=>new es(e._name,t,e._ratio),e,t,i)}}A([D()],es.prototype,"samples",null);A([D()],es.prototype,"maxDistance",void 0);A([D()],es.prototype,"step",void 0);A([D()],es.prototype,"thickness",void 0);A([D()],es.prototype,"strength",void 0);A([D()],es.prototype,"reflectionSpecularFalloffExponent",void 0);A([D()],es.prototype,"maxSteps",void 0);A([D()],es.prototype,"roughnessFactor",void 0);A([D()],es.prototype,"selfCollisionNumSkip",void 0);A([D()],es.prototype,"_reflectivityThreshold",void 0);A([D("_ssrDownsample")],es.prototype,"_ssrDownsample",void 0);A([D()],es.prototype,"ssrDownsample",null);A([D("blurDispersionStrength")],es.prototype,"_blurDispersionStrength",void 0);A([D("blurDownsample")],es.prototype,"_blurDownsample",void 0);A([D("enableSmoothReflections")],es.prototype,"_enableSmoothReflections",void 0);A([D("environmentTexture")],es.prototype,"_environmentTexture",void 0);A([D("environmentTextureIsProbe")],es.prototype,"_environmentTextureIsProbe",void 0);A([D("attenuateScreenBorders")],es.prototype,"_attenuateScreenBorders",void 0);A([D("attenuateIntersectionDistance")],es.prototype,"_attenuateIntersectionDistance",void 0);A([D("attenuateIntersectionIterations")],es.prototype,"_attenuateIntersectionIterations",void 0);A([D("attenuateFacingCamera")],es.prototype,"_attenuateFacingCamera",void 0);A([D("attenuateBackfaceReflection")],es.prototype,"_attenuateBackfaceReflection",void 0);A([D("clipToFrustum")],es.prototype,"_clipToFrustum",void 0);A([D("useFresnel")],es.prototype,"_useFresnel",void 0);A([D("enableAutomaticThicknessComputation")],es.prototype,"_enableAutomaticThicknessComputation",void 0);A([D("backfaceDepthTextureDownsample")],es.prototype,"_backfaceDepthTextureDownsample",void 0);A([D("backfaceForceDepthWriteTransparentMeshes")],es.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);A([D("isEnabled")],es.prototype,"_isEnabled",void 0);A([D("inputTextureColorIsInGammaSpace")],es.prototype,"_inputTextureColorIsInGammaSpace",void 0);A([D("generateOutputInGammaSpace")],es.prototype,"_generateOutputInGammaSpace",void 0);A([D("debug")],es.prototype,"_debug",void 0);j("BABYLON.SSRRenderingPipeline",es);const dX="tonemapPixelShader",fX=`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 @@ -11198,7 +11198,7 @@ colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retC #elif defined(PHOTOGRAPHIC_TONEMAPPING) colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); #endif -gl_FragColor=vec4(colour.rgb,1.0);}`;ne.ShadersStore[hX]=cX;var AC;(function(o){o[o.Hable=0]="Hable",o[o.Reinhard=1]="Reinhard",o[o.HejiDawson=2]="HejiDawson",o[o.Photographic=3]="Photographic"})(AC||(AC={}));const uX="volumetricLightScatteringPixelShader",dX=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +gl_FragColor=vec4(colour.rgb,1.0);}`;ne.ShadersStore[dX]=fX;var IC;(function(o){o[o.Hable=0]="Hable",o[o.Reinhard=1]="Reinhard",o[o.HejiDawson=2]="HejiDawson",o[o.Photographic=3]="Photographic"})(IC||(IC={}));const pX="volumetricLightScatteringPixelShader",_X=`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 @@ -11206,7 +11206,7 @@ vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/f 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 } -`;ne.ShadersStore[uX]=dX;const fX="volumetricLightScatteringPassVertexShader",pX=`attribute vec3 position; +`;ne.ShadersStore[pX]=_X;const mX="volumetricLightScatteringPassVertexShader",gX=`attribute vec3 position; #include #include #include @@ -11243,7 +11243,7 @@ vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #endif #endif } -`;ne.ShadersStore[fX]=pX;const _X="volumetricLightScatteringPassPixelShader",mX=`#if defined(ALPHATEST) || defined(NEED_UV) +`;ne.ShadersStore[mX]=gX;const vX="volumetricLightScatteringPassPixelShader",xX=`#if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV; #endif #if defined(ALPHATEST) @@ -11257,8 +11257,8 @@ vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) discard; #endif gl_FragColor=vec4(0.0,0.0,0.0,1.0);} -`;ne.ShadersStore[_X]=mX;class Ua extends lt{get useDiffuseColor(){return G.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){G.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,s,r=100,n=ee.BILINEAR_SAMPLINGMODE,a,l,h){var c,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,l,"#define NUM_SAMPLES "+r),this._screenCoordinates=Re.Zero(),this.customMeshPosition=T.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,h=(u=(c=i==null?void 0:i.getScene())!==null&&c!==void 0?c:h)!==null&&u!==void 0?u:this._scene,a=h.getEngine(),this._viewPort=new Na(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=s??Ua.CreateDefaultMesh("VolumetricLightScatteringMesh",h),this._createPass(h,t.passRatio||t),this.onActivate=d=>{this.isSupported||this.dispose(d),this.onActivate=null},this.onApplyObservable.add(d=>{this._updateMeshScreenCoordinates(h),d.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),d.setFloat("exposure",this.exposure),d.setFloat("decay",this.decay),d.setFloat("weight",this.weight),d.setFloat("density",this.density),d.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const s=e.getMesh();if(s===this.mesh&&s.material)return s.material.isReady(s);const r=(i=s._internalAbstractMeshDataInfo._materialForRenderPass)===null||i===void 0?void 0:i[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(s,e,t);const n=[],a=[P.PositionKind],l=e.getMaterial();l&&(l.needAlphaTesting()&&n.push("#define ALPHATEST"),s.isVerticesDataPresent(P.UVKind)&&(a.push(P.UVKind),n.push("#define UV1")),s.isVerticesDataPresent(P.UV2Kind)&&(a.push(P.UV2Kind),n.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders?(a.push(P.MatricesIndicesKind),a.push(P.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),Me.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const h=e._getDrawWrapper(void 0,!0),c=h.defines,u=n.join(` -`);return c!==u&&h.setEffect(s.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:s.numBoneInfluencers}),u),h.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 ms("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=ee.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=ee.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 h;const c=l.getRenderingMesh(),u=l.getEffectiveMesh();if(this._meshExcluded(c))return;u._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const d=l.getMaterial();if(!d)return;const f=c.getScene(),p=f.getEngine();p.setState(d.backFaceCulling,void 0,void 0,void 0,d.cullBackFaces);const _=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(_.mustReturn)return;const g=p.getCaps().instancedArrays&&(_.visibleInstances[l._id]!==null||c.hasThinInstances);if(this._isReady(l,g)){const v=(h=u._internalAbstractMeshDataInfo._materialForRenderPass)===null||h===void 0?void 0:h[p.currentRenderPassId];let E=l._getDrawWrapper();if(c===this.mesh&&!E&&(E=d._getDrawWrapper()),!E)return;const C=E.effect;if(p.enableEffect(E),g||c._bind(l,C,d.fillMode),c===this.mesh)d.bind(u.getWorldMatrix(),c);else if(v)v.bindForSubMesh(u.getWorldMatrix(),u,l);else{if(C.setMatrix("viewProjection",f.getTransformMatrix()),d&&d.needAlphaTesting()){const S=d.getAlphaTestTexture();C.setTexture("diffuseSampler",S),S&&C.setMatrix("diffuseMatrix",S.getTextureMatrix())}c.useBones&&c.computeBonesUsingShaders&&c.skeleton&&C.setMatrices("mBones",c.skeleton.getTransformMatrices(c))}g&&c.hasThinInstances&&C.setMatrix("world",u.getWorldMatrix()),c._processRendering(u,l,C,Ie.TriangleFillMode,_,g,(S,b)=>{S||C.setMatrix("world",b)})}};let n;const a=new Ze(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{n=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=n}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,h,c)=>{if((c||h===0)&&l.subMeshes)for(let u=0;u{const d=e.getEngine();let f;if(u.length){for(d.setColorWrite(!1),f=0;f_._alphaIndex>g._alphaIndex?1:_._alphaIndexg._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f{this.isSupported||this.dispose(d),this.onActivate=null},this.onApplyObservable.add(d=>{this._updateMeshScreenCoordinates(h),d.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),d.setFloat("exposure",this.exposure),d.setFloat("decay",this.decay),d.setFloat("weight",this.weight),d.setFloat("density",this.density),d.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const s=e.getMesh();if(s===this.mesh&&s.material)return s.material.isReady(s);const r=(i=s._internalAbstractMeshDataInfo._materialForRenderPass)===null||i===void 0?void 0:i[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(s,e,t);const n=[],a=[P.PositionKind],l=e.getMaterial();l&&(l.needAlphaTesting()&&n.push("#define ALPHATEST"),s.isVerticesDataPresent(P.UVKind)&&(a.push(P.UVKind),n.push("#define UV1")),s.isVerticesDataPresent(P.UV2Kind)&&(a.push(P.UV2Kind),n.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders?(a.push(P.MatricesIndicesKind),a.push(P.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),Me.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const h=e._getDrawWrapper(void 0,!0),c=h.defines,u=n.join(` +`);return c!==u&&h.setEffect(s.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:s.numBoneInfluencers}),u),h.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 ms("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=ee.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=ee.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 h;const c=l.getRenderingMesh(),u=l.getEffectiveMesh();if(this._meshExcluded(c))return;u._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const d=l.getMaterial();if(!d)return;const f=c.getScene(),p=f.getEngine();p.setState(d.backFaceCulling,void 0,void 0,void 0,d.cullBackFaces);const _=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(_.mustReturn)return;const g=p.getCaps().instancedArrays&&(_.visibleInstances[l._id]!==null||c.hasThinInstances);if(this._isReady(l,g)){const v=(h=u._internalAbstractMeshDataInfo._materialForRenderPass)===null||h===void 0?void 0:h[p.currentRenderPassId];let E=l._getDrawWrapper();if(c===this.mesh&&!E&&(E=d._getDrawWrapper()),!E)return;const C=E.effect;if(p.enableEffect(E),g||c._bind(l,C,d.fillMode),c===this.mesh)d.bind(u.getWorldMatrix(),c);else if(v)v.bindForSubMesh(u.getWorldMatrix(),u,l);else{if(C.setMatrix("viewProjection",f.getTransformMatrix()),d&&d.needAlphaTesting()){const S=d.getAlphaTestTexture();C.setTexture("diffuseSampler",S),S&&C.setMatrix("diffuseMatrix",S.getTextureMatrix())}c.useBones&&c.computeBonesUsingShaders&&c.skeleton&&C.setMatrices("mBones",c.skeleton.getTransformMatrices(c))}g&&c.hasThinInstances&&C.setMatrix("world",u.getWorldMatrix()),c._processRendering(u,l,C,Ie.TriangleFillMode,_,g,(S,b)=>{S||C.setMatrix("world",b)})}};let n;const a=new Ze(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{n=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=n}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,h,c)=>{if((c||h===0)&&l.subMeshes)for(let u=0;u{const d=e.getEngine();let f;if(u.length){for(d.setColorWrite(!1),f=0;f_._alphaIndex>g._alphaIndex?1:_._alphaIndexg._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f{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)}):G.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=ht.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,s){return Xe.Parse(()=>new up(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],up.prototype,"ridge",void 0);A([D()],up.prototype,"valley",void 0);j("BABYLON.ScreenSpaceCurvaturePostProcess",up);const xX="boundingBoxRendererFragmentDeclaration",TX=`uniform vec4 color; -`;ne.IncludesShadersStore[xX]=TX;const EX="boundingBoxRendererUboDeclaration",SX=`#ifdef WEBGL2 +{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;}`;ne.ShadersStore[TX]=EX;class up extends lt{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,s,r,n,a,l=0,h=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,s,r,n,a,void 0,l,void 0,null,h),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?(this._geometryBufferRenderer.generateNormalsInWorldSpace&&G.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)}):G.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=ht.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,s){return Xe.Parse(()=>new up(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}A([D()],up.prototype,"ridge",void 0);A([D()],up.prototype,"valley",void 0);j("BABYLON.ScreenSpaceCurvaturePostProcess",up);const SX="boundingBoxRendererFragmentDeclaration",CX=`uniform vec4 color; +`;ne.IncludesShadersStore[SX]=CX;const bX="boundingBoxRendererUboDeclaration",yX=`#ifdef WEBGL2 uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; @@ -11279,17 +11279,17 @@ uniform mat4 viewProjectionR; #else layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; #endif -`;ne.IncludesShadersStore[EX]=SX;const CX="boundingBoxRendererPixelShader",bX=`#include<__decl__boundingBoxRendererFragment> +`;ne.IncludesShadersStore[bX]=yX;const AX="boundingBoxRendererPixelShader",RX=`#include<__decl__boundingBoxRendererFragment> #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[CX]=bX;const yX="boundingBoxRendererVertexDeclaration",AX=`uniform mat4 world;uniform mat4 viewProjection; +}`;ne.ShadersStore[AX]=RX;const IX="boundingBoxRendererVertexDeclaration",PX=`uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif -`;ne.IncludesShadersStore[yX]=AX;const RX="boundingBoxRendererVertexShader",IX=`attribute vec3 position; +`;ne.IncludesShadersStore[IX]=PX;const MX="boundingBoxRendererVertexShader",DX=`attribute vec3 position; #include<__decl__boundingBoxRendererVertex> #define CUSTOM_VERTEX_DEFINITIONS void main(void) { @@ -11302,11 +11302,11 @@ gl_Position=viewProjection*worldPos; #endif #define CUSTOM_VERTEX_MAIN_END } -`;ne.ShadersStore[RX]=IX;Object.defineProperty(Qe.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(o){this._forceShowBoundingBoxes=o,o&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Qe.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new PX(this)),this._boundingBoxRenderer};Object.defineProperty(hi.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(o){this._showBoundingBox=o,o&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class PX{constructor(e){this.name=Fe.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Te(1,1,1),this.backColor=new Te(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new he,this.onAfterBoxRenderingObservable=new he,this.onResourcesReadyObservable=new he,this.enabled=!0,this.renderList=new qs(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new it(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new it(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(Fe.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Fe.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Fe.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Fe.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 wa("colorShader",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new wa("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=Mx({size:1});this._vertexBuffers[P.PositionKind]=new P(e,t.positions,P.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[P.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const s=this.scene.getEngine();s.setDepthWrite(!1);const r=this.scene.getTransformMatrix();for(let n=0;n{let e=o._getComponent(Fe.NAME_DEPTHRENDERER);e||(e=new MX(o),o._addComponent(e))};const DX="oitFinalPixelShader",OX=`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( +`;ne.ShadersStore[MX]=DX;Object.defineProperty(Qe.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(o){this._forceShowBoundingBoxes=o,o&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Qe.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new OX(this)),this._boundingBoxRenderer};Object.defineProperty(hi.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(o){this._showBoundingBox=o,o&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class OX{constructor(e){this.name=Fe.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Te(1,1,1),this.backColor=new Te(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new he,this.onAfterBoxRenderingObservable=new he,this.onResourcesReadyObservable=new he,this.enabled=!0,this.renderList=new qs(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new it(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new it(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(Fe.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Fe.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Fe.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Fe.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 wa("colorShader",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new wa("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=Ox({size:1});this._vertexBuffers[P.PositionKind]=new P(e,t.positions,P.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[P.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(this.renderList.length===0||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;const s=this.scene.getEngine();s.setDepthWrite(!1);const r=this.scene.getTransformMatrix();for(let n=0;n{let e=o._getComponent(Fe.NAME_DEPTHRENDERER);e||(e=new NX(o),o._addComponent(e))};const wX="oitFinalPixelShader",FX=`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 -);}`;ne.ShadersStore[DX]=OX;const NX="oitBackBlendPixelShader",wX=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { -discard;}}`;ne.ShadersStore[NX]=wX;class FX{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Al{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 qs(10),this._excludedSubMeshes=new qs(10),this._excludedMeshes=[],this._colorCache=[new Ze(Al._DEPTH_CLEAR_VALUE,Al._DEPTH_CLEAR_VALUE,0,0),new Ze(-Al._MIN_DEPTH,Al._MAX_DEPTH,0,0),new Ze(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){G.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i +);}`;ne.ShadersStore[wX]=FX;const LX="oitBackBlendPixelShader",BX=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;ne.ShadersStore[LX]=BX;class VX{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Al{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 qs(10),this._excludedSubMeshes=new qs(10),this._excludedMeshes=[],this._colorCache=[new Ze(Al._DEPTH_CLEAR_VALUE,Al._DEPTH_CLEAR_VALUE,0,0),new Ze(-Al._MIN_DEPTH,Al._MAX_DEPTH,0,0),new Ze(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){G.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i uniform vec4 color; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable @@ -11319,7 +11319,7 @@ void main(void) { #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[BX]=VX;const UX="lineVertexShader",kX=`#include +}`;ne.ShadersStore[kX]=GX;const zX="lineVertexShader",WX=`#include #include attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; #include @@ -11334,15 +11334,15 @@ vec4 worldPos=finalWorld*vec4(position,1.0); #endif #include #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[UX]=kX;hi.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};hi.prototype.enableEdgesRendering=function(o=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new Hm(this,o,e,!0,t),this};Object.defineProperty(hi.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});fh.prototype.enableEdgesRendering=function(o=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new zX(this,o,e),this};Kb.prototype.enableEdgesRendering=function(o=.95,e=!1){return fh.prototype.enableEdgesRendering.apply(this,arguments),this};class GX{constructor(){this.edges=[],this.edgesConnectedCount=0}}class Hm{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 wa("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){var n;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 qs(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Or(e.getEngine())),this._prepareRessources(),s&&(!((n=r==null?void 0:r.useAlternateEdgeFinder)!==null&&n!==void 0)||n?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=Hm._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[P.PositionKind];e&&e._rebuild(),e=this._buffers[P.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[P.PositionKind];t&&(t.dispose(),this._buffers[P.PositionKind]=null),t=this._buffers[P.NormalKind],t&&(t.dispose(),this._buffers[P.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(e=this._drawWrapper)===null||e===void 0||e.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=T.Dot(i[e],i[t]){L>=0&&O.push(L);for(let B=0;B=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 N=0;N<3;++N)N===n?e[N].sort((O,L)=>O[1]L[1]?1:0):e[N].sort((O,L)=>O[1]>L[1]?-1:O[1]=n+1;--N)r(e[N%3],l,N!==n+2?s[i[t+(N+1)%3]]:-1);const c=l.length,u=0,d=0;i.push(s[i[t+n]],a[0],l[0]),i.push(s[i[t+(n+1)%3]],l[c-1],a[h-1]);const f=h<=c,p=f?h:c,_=f?c:h,g=f?h-1:c-1,v=f?0:1;let E=h+c-2,C=f?u:d,S=f?d:u;const b=f?a:l,R=f?l:a;let I=0;for(;E-- >0;){v?i.push(b[C],R[S]):i.push(R[S],b[C]),I+=p;let N;I>=_&&CI){const B=R;R=I,I=B}const O=R+"_"+I,L=v[O];L?L.done||(T.Dot(S,L.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let 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 a=this._source._instanceDataStorage;if(r=this.customInstances.length,!a.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!a.isFrozen){let l=0;for(let h=0;h0&&(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;el!=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 a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:r&&(a=r),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_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;es!=null),t)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw xt("PrePassRendererSceneComponent")};Kr.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(Qe.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(o){o&&o.isSupported&&(this._prePassRenderer=o)},enumerable:!0,configurable:!0});Qe.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new Kr(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,G.Error(`PrePassRenderer needs WebGL 2 support. +}`;ne.ShadersStore[zX]=WX;hi.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};hi.prototype.enableEdgesRendering=function(o=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new Hm(this,o,e,!0,t),this};Object.defineProperty(hi.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});ph.prototype.enableEdgesRendering=function(o=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new XX(this,o,e),this};jb.prototype.enableEdgesRendering=function(o=.95,e=!1){return ph.prototype.enableEdgesRendering.apply(this,arguments),this};class HX{constructor(){this.edges=[],this.edgesConnectedCount=0}}class Hm{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 wa("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){var n;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 qs(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Or(e.getEngine())),this._prepareRessources(),s&&(!((n=r==null?void 0:r.useAlternateEdgeFinder)!==null&&n!==void 0)||n?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=Hm._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[P.PositionKind];e&&e._rebuild(),e=this._buffers[P.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[P.PositionKind];t&&(t.dispose(),this._buffers[P.PositionKind]=null),t=this._buffers[P.NormalKind],t&&(t.dispose(),this._buffers[P.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(e=this._drawWrapper)===null||e===void 0||e.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=T.Dot(i[e],i[t]){L>=0&&O.push(L);for(let B=0;B=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 N=0;N<3;++N)N===n?e[N].sort((O,L)=>O[1]L[1]?1:0):e[N].sort((O,L)=>O[1]>L[1]?-1:O[1]=n+1;--N)r(e[N%3],l,N!==n+2?s[i[t+(N+1)%3]]:-1);const c=l.length,u=0,d=0;i.push(s[i[t+n]],a[0],l[0]),i.push(s[i[t+(n+1)%3]],l[c-1],a[h-1]);const f=h<=c,p=f?h:c,_=f?c:h,g=f?h-1:c-1,v=f?0:1;let E=h+c-2,C=f?u:d,S=f?d:u;const b=f?a:l,R=f?l:a;let I=0;for(;E-- >0;){v?i.push(b[C],R[S]):i.push(R[S],b[C]),I+=p;let N;I>=_&&CI){const B=R;R=I,I=B}const O=R+"_"+I,L=v[O];L?L.done||(T.Dot(S,L.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let 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 a=this._source._instanceDataStorage;if(r=this.customInstances.length,!a.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!a.isFrozen){let l=0;for(let h=0;h0&&(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;el!=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 a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:r&&(a=r),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_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;es!=null),t)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw xt("PrePassRendererSceneComponent")};Kr.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(Qe.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(o){o&&o.isSupported&&(this._prePassRenderer=o)},enumerable:!0,configurable:!0});Qe.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new Kr(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,G.Error(`PrePassRenderer needs WebGL 2 support. Maybe you tried to use the following features that need the PrePassRenderer : - + Subsurface Scattering`)),this._prePassRenderer)};Qe.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class HX{constructor(e){this.name=Fe.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Fe.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Fe.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Fe.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Fe.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Fe.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Fe.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Fe.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Fe.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(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}Kr._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_PREPASSRENDERER);e||(e=new HX(o),o._addComponent(e))};const XX="fibonacci",YX=`#define rcp(x) 1./x + + Subsurface Scattering`)),this._prePassRenderer)};Qe.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class $X{constructor(e){this.name=Fe.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Fe.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Fe.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Fe.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Fe.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Fe.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Fe.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Fe.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Fe.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(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}Kr._SceneComponentInitialization=o=>{let e=o._getComponent(Fe.NAME_PREPASSRENDERER);e||(e=new $X(o),o._addComponent(e))};const KX="fibonacci",qX=`#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);}`;ne.IncludesShadersStore[XX]=YX;const $X="diffusionProfile",KX="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";ne.IncludesShadersStore[$X]=KX;const qX="subSurfaceScatteringPixelShader",jX=`#include +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;ne.IncludesShadersStore[KX]=qX;const jX="diffusionProfile",QX="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";ne.IncludesShadersStore[jX]=QX;const ZX="subSurfaceScatteringPixelShader",JX=`#include #include #include #include @@ -11405,7 +11405,7 @@ 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{if(!t.prePassRenderer||!t.subSurfaceConfiguration){G.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 dp{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=Fe.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Te(1,1,1)),this._scene=e,dp._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return G.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw xt("SubSurfaceSceneComponent")};ks.AddParser(Fe.NAME_SUBSURFACE,(o,e)=>{if(o.ssDiffusionProfileColors!==void 0&&o.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=o.ssDiffusionProfileColors.length;t{let e=o._getComponent(Fe.NAME_SUBSURFACE);e||(e=new ZX(o),o._addComponent(e))};const JX="outlinePixelShader",e5=`#ifdef LOGARITHMICDEPTH +totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;ne.ShadersStore[ZX]=JX;class e5 extends lt{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,s=null,r,n,a,l=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,s,r||ee.BILINEAR_SAMPLINGMODE,n,a,null,l,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add(h=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration){G.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 dp{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=Fe.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Te(1,1,1)),this._scene=e,dp._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return G.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw xt("SubSurfaceSceneComponent")};ks.AddParser(Fe.NAME_SUBSURFACE,(o,e)=>{if(o.ssDiffusionProfileColors!==void 0&&o.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=o.ssDiffusionProfileColors.length;t{let e=o._getComponent(Fe.NAME_SUBSURFACE);e||(e=new t5(o),o._addComponent(e))};const i5="outlinePixelShader",s5=`#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform vec4 color; @@ -11425,7 +11425,7 @@ discard; #include gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[JX]=e5;const t5="outlineVertexShader",i5=`attribute vec3 position;attribute vec3 normal; +}`;ne.ShadersStore[i5]=s5;const r5="outlineVertexShader",n5=`attribute vec3 position;attribute vec3 normal; #include #include #include @@ -11468,9 +11468,9 @@ vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); #include #include } -`;ne.ShadersStore[t5]=i5;Qe.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new Ud(this)),this._outlineRenderer};Object.defineProperty(se.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOutline=o},enumerable:!0,configurable:!0});Object.defineProperty(se.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOverlay=o},enumerable:!0,configurable:!0});class Ud{constructor(e){this.name=Fe.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(Fe.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Fe.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",g)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[P.PositionKind,P.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;const l=n.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),vh(a,l,s),n.useBones&&n.computeBonesUsingShaders?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.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&&h.numInfluencers>0&&(c=h.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(r,n,c)),t&&(s.push("#define INSTANCES"),Me.PushAttributesForInstances(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 p=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];Ao(p),u.setEffect(this.scene.getEngine().createEffect("outline",r,p,["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(Ud._StencilReference),this._engine.setStencilFunctionReference(Ud._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))}}Ud._StencilReference=4;class cA{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===void 0)&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new he,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 Il({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Il({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===void 0||e.dispose(),(t=this._thicknessEffectWrapper)===null||t===void 0||t.dispose()}}class s5 extends cA{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 yv{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._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=ee.CLAMP_ADDRESSMODE,g.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const p=new lt("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);p.samples=this._samples,p.onApplyObservable.add(g=>{g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(g=>{g.texture.wrapU=ee.CLAMP_ADDRESSMODE,g.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),f.autoClear=!1,p.autoClear=!1;const _=[];for(let g=0;g{this._postProcessRunningIndex===0?v.setTexture("textureSampler",e):v._bindTexture("textureSampler",p.inputTexture.texture),v.setInt("maxFilterSize",this.blurMaxFilterSize),v.setFloat2("blurDir",1/this._blurTextureSizeX,0),v.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),v.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(v=>{v.texture.wrapU=ee.CLAMP_ADDRESSMODE,v.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p);const _=new lt("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(v=>{v.setInt("maxFilterSize",this.blurMaxFilterSize),v.setFloat2("blurDir",0,1/this._blurTextureSizeY),v.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),v.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(v=>{v.texture.wrapU=ee.CLAMP_ADDRESSMODE,v.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),p.autoClear=!1,_.autoClear=!1;const g=[];for(let v=0;v{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan(((t=(e=this._camera)===null||e===void 0?void 0:e.fov)!==null&&t!==void 0?t: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===void 0||e.dispose(),this._rt=null,(t=this._texture)===null||t===void 0||t.dispose(),this._texture=null,(i=this._rtBlur)===null||i===void 0||i.dispose(),this._rtBlur=null,(s=this._textureBlurred)===null||s===void 0||s.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var Sa;(function(o){o[o.DepthTexture=0]="DepthTexture",o[o.DepthBlurredTexture=1]="DepthBlurredTexture",o[o.ThicknessTexture=2]="ThicknessTexture",o[o.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",o[o.DiffuseTexture=4]="DiffuseTexture",o[o.Normals=5]="Normals",o[o.DiffuseRendering=6]="DiffuseRendering"})(Sa||(Sa={}));class RC{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 Te(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new T(-2,-1,1).normalize(),this._debugFeature=Sa.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 he,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 k,this._depthClearColor=new Ze(1e6,1e6,1e6,1),this._thicknessClearColor=new Ze(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;const s=(e=this._depthMapSize)!==null&&e!==void 0?e:this._engine.getRenderWidth(),r=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new yv("Depth",this._scene,s,r,s,r,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const l=(t=this._diffuseMapSize)!==null&&t!==void 0?t:this._engine.getRenderWidth(),h=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new yv("Diffuse",this._scene,l,h,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const n=(i=this._thicknessMapSize)!==null&&i!==void 0?i:this._engine.getRenderWidth(),a=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new yv("Thickness",this._scene,n,a,n,a,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(){var e;const t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],s=["depthSampler"],r=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new Re(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&((e=this._environmentMap)!==null&&e!==void 0?e:this._scene.environmentTexture)&&(s.push("reflectionSampler"),r.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(s.push("diffuseSampler"),r.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(s.push("velocitySampler"),r.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),s.push("bgDepthSampler"),r.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),s.push("thicknessSampler")),this._debug&&(r.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===Sa.Normals?r.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===Sa.DiffuseRendering?r.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(r.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),s.push("debugSampler"),(this._debugFeature===Sa.DepthTexture||this._debugFeature===Sa.DepthBlurredTexture)&&r.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new lt("FluidRendering","fluidRenderingRender",i,s,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(r.join(` -`)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(l=>{var h,c,u,d,f,p,_,g,v,E,C,S,b,R,I,N,O,L,B,V,Z,ue,oe;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&l.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(l.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(d=(u=this._depthRenderTarget.textureBlur)===null||u===void 0?void 0:u.getInternalTexture())!==null&&d!==void 0?d:null)):(l.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(c=(h=this._depthRenderTarget.texture)===null||h===void 0?void 0:h.getInternalTexture())!==null&&c!==void 0?c:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(l.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(g=(_=this._diffuseRenderTarget.textureBlur)===null||_===void 0?void 0:_.getInternalTexture())!==null&&g!==void 0?g:null)):(l.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(p=(f=this._diffuseRenderTarget.texture)===null||f===void 0?void 0:f.getInternalTexture())!==null&&p!==void 0?p:null)):l.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(l.setFloat("thickness",this.minimumThickness),l._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&l.setTextureSampler("bgDepthSamplerSampler",(v=this._bgDepthTexture)!==null&&v!==void 0?v:null)):(this._thicknessRenderTarget.enableBlur?(l.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(b=(S=this._thicknessRenderTarget.textureBlur)===null||S===void 0?void 0:S.getInternalTexture())!==null&&b!==void 0?b:null)):(l.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(C=(E=this._thicknessRenderTarget.texture)===null||E===void 0?void 0:E.getInternalTexture())!==null&&C!==void 0?C:null)),l.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const me=(R=this._environmentMap)!==null&&R!==void 0?R:this._scene.environmentTexture;me&&(l.setTexture("reflectionSampler",me),t.isWebGPU&&l.setTextureSampler("reflectionSamplerSampler",(I=me==null?void 0:me.getInternalTexture())!==null&&I!==void 0?I:null))}if(l.setMatrix("viewMatrix",this._scene.getViewMatrix()),l.setMatrix("invProjectionMatrix",this._invProjectionMatrix),l.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),l.setVector2("texelSize",a),l.setFloat("density",this.density),l.setFloat("refractionStrength",this.refractionStrength),l.setFloat("fresnelClamp",this.fresnelClamp),l.setFloat("specularPower",this.specularPower),l.setVector3("dirLight",this.dirLight),l.setFloat("cameraFar",this._camera.maxZ),this._debug){let me=null;switch(this._debugFeature){case Sa.DepthTexture:me=this._depthRenderTarget.texture;break;case Sa.DepthBlurredTexture:me=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case Sa.ThicknessTexture:me=(O=(N=this._thicknessRenderTarget)===null||N===void 0?void 0:N.texture)!==null&&O!==void 0?O:null;break;case Sa.ThicknessBlurredTexture:me=!((L=this._thicknessRenderTarget)===null||L===void 0)&&L.enableBlur?(V=(B=this._thicknessRenderTarget)===null||B===void 0?void 0:B.textureBlur)!==null&&V!==void 0?V:null:(ue=(Z=this._thicknessRenderTarget)===null||Z===void 0?void 0:Z.texture)!==null&&ue!==void 0?ue:null;break;case Sa.DiffuseTexture:this._diffuseRenderTarget&&(me=this._diffuseRenderTarget.texture);break}this._debugFeature!==Sa.Normals&&(l.setTexture("debugSampler",me),t.isWebGPU&&l.setTextureSampler("debugSamplerSampler",(oe=me==null?void 0:me.getInternalTexture())!==null&&oe!==void 0?oe:null))}})}_clearTargets(){var e,t,i;!((e=this._depthRenderTarget)===null||e===void 0)&&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===void 0)&&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===void 0)&&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 t,i,s,r,n,a;if(this._needInitialization||!e.isReady())return;const l=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),!((t=this._depthRenderTarget)===null||t===void 0)&&t.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),!((i=this._diffuseRenderTarget)===null||i===void 0)&&i.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),!((s=this._thicknessRenderTarget)===null||s===void 0)&&s.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(r=this._depthRenderTarget)===null||r===void 0||r.applyBlurPostProcesses(),(n=this._diffuseRenderTarget)===null||n===void 0||n.applyBlurPostProcesses(),(a=this._thicknessRenderTarget)===null||a===void 0||a.applyBlurPostProcesses(),l&&this._engine.bindFramebuffer(l)}dispose(e=!1){var t,i,s,r;e||((t=this._depthRenderTarget)===null||t===void 0||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)===null||i===void 0||i.dispose(),this._diffuseRenderTarget=null,(s=this._thicknessRenderTarget)===null||s===void 0||s.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(r=this._renderPostProcess)===null||r===void 0||r.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class r5 extends cA{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 P(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new Il({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new P(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&((t=(e=this._diffuseEffectWrapper)===null||e===void 0?void 0:e.effect.isReady())!==null&&t!==void 0?t:!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===void 0||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const n5="copyTextureToTexturePixelShader",a5=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +`;ne.ShadersStore[r5]=n5;Qe.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new Ud(this)),this._outlineRenderer};Object.defineProperty(se.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOutline=o},enumerable:!0,configurable:!0});Object.defineProperty(se.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(o){o&&this.getScene().getOutlineRenderer(),this._renderOverlay=o},enumerable:!0,configurable:!0});class Ud{constructor(e){this.name=Fe.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(Fe.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Fe.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",g)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[P.PositionKind,P.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;const l=n.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),xh(a,l,s),n.useBones&&n.computeBonesUsingShaders?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.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&&h.numInfluencers>0&&(c=h.numInfluencers,s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Me.PrepareAttributesForMorphTargetsInfluencers(r,n,c)),t&&(s.push("#define INSTANCES"),Me.PushAttributesForInstances(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 p=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];Ao(p),u.setEffect(this.scene.getEngine().createEffect("outline",r,p,["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(Ud._StencilReference),this._engine.setStencilFunctionReference(Ud._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))}}Ud._StencilReference=4;class fA{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===void 0)&&e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new he,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 Il({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Il({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===void 0||e.dispose(),(t=this._thicknessEffectWrapper)===null||t===void 0||t.dispose()}}class a5 extends fA{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 yv{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._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=ee.CLAMP_ADDRESSMODE,g.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const p=new lt("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);p.samples=this._samples,p.onApplyObservable.add(g=>{g.setInt("filterSize",this.blurFilterSize),g.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(g=>{g.texture.wrapU=ee.CLAMP_ADDRESSMODE,g.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),f.autoClear=!1,p.autoClear=!1;const _=[];for(let g=0;g{this._postProcessRunningIndex===0?v.setTexture("textureSampler",e):v._bindTexture("textureSampler",p.inputTexture.texture),v.setInt("maxFilterSize",this.blurMaxFilterSize),v.setFloat2("blurDir",1/this._blurTextureSizeX,0),v.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),v.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(v=>{v.texture.wrapU=ee.CLAMP_ADDRESSMODE,v.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p);const _=new lt("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(v=>{v.setInt("maxFilterSize",this.blurMaxFilterSize),v.setFloat2("blurDir",0,1/this._blurTextureSizeY),v.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),v.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(v=>{v.texture.wrapU=ee.CLAMP_ADDRESSMODE,v.texture.wrapV=ee.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),p.autoClear=!1,_.autoClear=!1;const g=[];for(let v=0;v{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan(((t=(e=this._camera)===null||e===void 0?void 0:e.fov)!==null&&t!==void 0?t: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===void 0||e.dispose(),this._rt=null,(t=this._texture)===null||t===void 0||t.dispose(),this._texture=null,(i=this._rtBlur)===null||i===void 0||i.dispose(),this._rtBlur=null,(s=this._textureBlurred)===null||s===void 0||s.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var Sa;(function(o){o[o.DepthTexture=0]="DepthTexture",o[o.DepthBlurredTexture=1]="DepthBlurredTexture",o[o.ThicknessTexture=2]="ThicknessTexture",o[o.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",o[o.DiffuseTexture=4]="DiffuseTexture",o[o.Normals=5]="Normals",o[o.DiffuseRendering=6]="DiffuseRendering"})(Sa||(Sa={}));class PC{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 Te(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new T(-2,-1,1).normalize(),this._debugFeature=Sa.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 he,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 k,this._depthClearColor=new Ze(1e6,1e6,1e6,1),this._thicknessClearColor=new Ze(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;const s=(e=this._depthMapSize)!==null&&e!==void 0?e:this._engine.getRenderWidth(),r=this._depthMapSize!==null?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new yv("Depth",this._scene,s,r,s,r,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const l=(t=this._diffuseMapSize)!==null&&t!==void 0?t:this._engine.getRenderWidth(),h=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new yv("Diffuse",this._scene,l,h,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const n=(i=this._thicknessMapSize)!==null&&i!==void 0?i:this._engine.getRenderWidth(),a=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new yv("Thickness",this._scene,n,a,n,a,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(){var e;const t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],s=["depthSampler"],r=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new Re(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&((e=this._environmentMap)!==null&&e!==void 0?e:this._scene.environmentTexture)&&(s.push("reflectionSampler"),r.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(s.push("diffuseSampler"),r.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(s.push("velocitySampler"),r.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),s.push("bgDepthSampler"),r.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),s.push("thicknessSampler")),this._debug&&(r.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===Sa.Normals?r.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===Sa.DiffuseRendering?r.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(r.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),s.push("debugSampler"),(this._debugFeature===Sa.DepthTexture||this._debugFeature===Sa.DepthBlurredTexture)&&r.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new lt("FluidRendering","fluidRenderingRender",i,s,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(r.join(` +`)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(l=>{var h,c,u,d,f,p,_,g,v,E,C,S,b,R,I,N,O,L,B,V,Z,ue,oe;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&l.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(l.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(d=(u=this._depthRenderTarget.textureBlur)===null||u===void 0?void 0:u.getInternalTexture())!==null&&d!==void 0?d:null)):(l.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("depthSamplerSampler",(c=(h=this._depthRenderTarget.texture)===null||h===void 0?void 0:h.getInternalTexture())!==null&&c!==void 0?c:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(l.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(g=(_=this._diffuseRenderTarget.textureBlur)===null||_===void 0?void 0:_.getInternalTexture())!==null&&g!==void 0?g:null)):(l.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("diffuseSamplerSampler",(p=(f=this._diffuseRenderTarget.texture)===null||f===void 0?void 0:f.getInternalTexture())!==null&&p!==void 0?p:null)):l.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(l.setFloat("thickness",this.minimumThickness),l._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&l.setTextureSampler("bgDepthSamplerSampler",(v=this._bgDepthTexture)!==null&&v!==void 0?v:null)):(this._thicknessRenderTarget.enableBlur?(l.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(b=(S=this._thicknessRenderTarget.textureBlur)===null||S===void 0?void 0:S.getInternalTexture())!==null&&b!==void 0?b:null)):(l.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&l.setTextureSampler("thicknessSamplerSampler",(C=(E=this._thicknessRenderTarget.texture)===null||E===void 0?void 0:E.getInternalTexture())!==null&&C!==void 0?C:null)),l.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const me=(R=this._environmentMap)!==null&&R!==void 0?R:this._scene.environmentTexture;me&&(l.setTexture("reflectionSampler",me),t.isWebGPU&&l.setTextureSampler("reflectionSamplerSampler",(I=me==null?void 0:me.getInternalTexture())!==null&&I!==void 0?I:null))}if(l.setMatrix("viewMatrix",this._scene.getViewMatrix()),l.setMatrix("invProjectionMatrix",this._invProjectionMatrix),l.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),l.setVector2("texelSize",a),l.setFloat("density",this.density),l.setFloat("refractionStrength",this.refractionStrength),l.setFloat("fresnelClamp",this.fresnelClamp),l.setFloat("specularPower",this.specularPower),l.setVector3("dirLight",this.dirLight),l.setFloat("cameraFar",this._camera.maxZ),this._debug){let me=null;switch(this._debugFeature){case Sa.DepthTexture:me=this._depthRenderTarget.texture;break;case Sa.DepthBlurredTexture:me=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case Sa.ThicknessTexture:me=(O=(N=this._thicknessRenderTarget)===null||N===void 0?void 0:N.texture)!==null&&O!==void 0?O:null;break;case Sa.ThicknessBlurredTexture:me=!((L=this._thicknessRenderTarget)===null||L===void 0)&&L.enableBlur?(V=(B=this._thicknessRenderTarget)===null||B===void 0?void 0:B.textureBlur)!==null&&V!==void 0?V:null:(ue=(Z=this._thicknessRenderTarget)===null||Z===void 0?void 0:Z.texture)!==null&&ue!==void 0?ue:null;break;case Sa.DiffuseTexture:this._diffuseRenderTarget&&(me=this._diffuseRenderTarget.texture);break}this._debugFeature!==Sa.Normals&&(l.setTexture("debugSampler",me),t.isWebGPU&&l.setTextureSampler("debugSamplerSampler",(oe=me==null?void 0:me.getInternalTexture())!==null&&oe!==void 0?oe:null))}})}_clearTargets(){var e,t,i;!((e=this._depthRenderTarget)===null||e===void 0)&&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===void 0)&&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===void 0)&&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 t,i,s,r,n,a;if(this._needInitialization||!e.isReady())return;const l=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),!((t=this._depthRenderTarget)===null||t===void 0)&&t.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),!((i=this._diffuseRenderTarget)===null||i===void 0)&&i.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),!((s=this._thicknessRenderTarget)===null||s===void 0)&&s.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(r=this._depthRenderTarget)===null||r===void 0||r.applyBlurPostProcesses(),(n=this._diffuseRenderTarget)===null||n===void 0||n.applyBlurPostProcesses(),(a=this._thicknessRenderTarget)===null||a===void 0||a.applyBlurPostProcesses(),l&&this._engine.bindFramebuffer(l)}dispose(e=!1){var t,i,s,r;e||((t=this._depthRenderTarget)===null||t===void 0||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)===null||i===void 0||i.dispose(),this._diffuseRenderTarget=null,(s=this._thicknessRenderTarget)===null||s===void 0||s.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(r=this._renderPostProcess)===null||r===void 0||r.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class o5 extends fA{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 P(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new Il({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:t,uniformNames:e,samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new P(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&((t=(e=this._diffuseEffectWrapper)===null||e===void 0?void 0:e.effect.isReady())!==null&&t!==void 0?t:!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===void 0||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const l5="copyTextureToTexturePixelShader",h5=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; #include void main(void) {vec4 color=texture2D(textureSampler,vUV); @@ -11481,7 +11481,7 @@ if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {colo gl_FragColor=color; #endif } -`;ne.ShadersStore[n5]=a5;var qv;(function(o){o[o.None=0]="None",o[o.ToLinearSpace=1]="ToLinearSpace",o[o.ToGammaSpace=2]="ToGammaSpace"})(qv||(qv={}));class o5{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new am(e),this._effectWrapper=new Il({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=qv.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 l5{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new o5(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 h5="fluidRenderingParticleDepthVertexShader",c5=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +`;ne.ShadersStore[l5]=h5;var jv;(function(o){o[o.None=0]="None",o[o.ToLinearSpace=1]="ToLinearSpace",o[o.ToGammaSpace=2]="ToGammaSpace"})(jv||(jv={}));class c5{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new am(e),this._effectWrapper=new Il({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=jv.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 u5{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new c5(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 d5="fluidRenderingParticleDepthVertexShader",f5=`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 @@ -11490,7 +11490,7 @@ void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*siz velocityNorm=length(velocity); #endif } -`;ne.ShadersStore[h5]=c5;const u5="fluidRenderingParticleDepthPixelShader",d5=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +`;ne.ShadersStore[d5]=f5;const p5="fluidRenderingParticleDepthPixelShader",_5=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; #ifdef FLUIDRENDERING_VELOCITY varying float velocityNorm; #endif @@ -11513,17 +11513,17 @@ glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); glFragColor=vec4(realViewPos.z,0.,0.,1.); #endif } -`;ne.ShadersStore[u5]=d5;const f5="fluidRenderingParticleThicknessVertexShader",p5=`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;} -`;ne.ShadersStore[f5]=p5;const _5="fluidRenderingParticleThicknessPixelShader",m5=`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);} -`;ne.ShadersStore[_5]=m5;const g5="fluidRenderingParticleDiffuseVertexShader",v5=`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;} -`;ne.ShadersStore[g5]=v5;const x5="fluidRenderingParticleDiffusePixelShader",T5=`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);} -`;ne.ShadersStore[x5]=T5;const E5="fluidRenderingBilateralBlurPixelShader",S5=`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;} +`;ne.ShadersStore[p5]=_5;const m5="fluidRenderingParticleThicknessVertexShader",g5=`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;} +`;ne.ShadersStore[m5]=g5;const v5="fluidRenderingParticleThicknessPixelShader",x5=`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);} +`;ne.ShadersStore[v5]=x5;const T5="fluidRenderingParticleDiffuseVertexShader",E5=`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;} +`;ne.ShadersStore[T5]=E5;const S5="fluidRenderingParticleDiffusePixelShader",C5=`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);} +`;ne.ShadersStore[S5]=C5;const b5="fluidRenderingBilateralBlurPixelShader",y5=`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.);} -`;ne.ShadersStore[E5]=S5;const C5="fluidRenderingStandardBlurPixelShader",b5=`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;} +`;ne.ShadersStore[b5]=y5;const A5="fluidRenderingStandardBlurPixelShader",R5=`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.);} -`;ne.ShadersStore[C5]=b5;const y5="fluidRenderingRenderPixelShader",A5=`/* disable_uniformity_analysis */ +`;ne.ShadersStore[A5]=R5;const I5="fluidRenderingRenderPixelShader",P5=`/* disable_uniformity_analysis */ #define IOR 1.333 #define ETA 1.0/IOR #define F0 0.02 @@ -11606,10 +11606,10 @@ vec3 finalColor=refractionColor+specular; float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); #endif glFragColor=vec4(finalColor,transmitted.a);} -`;ne.ShadersStore[y5]=A5;Object.defineProperty(Qe.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(o){this._fluidRenderer=o},enumerable:!0,configurable:!0});Qe.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new mT(this),this._fluidRenderer)};Qe.prototype.disableFluidRenderer=function(){var o;(o=this._fluidRenderer)===null||o===void 0||o.dispose(),this._fluidRenderer=null};function R5(o){return!!o.particleSystem}class I5{constructor(e){this.name=Fe.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Fe.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Fe.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;(t=this.scene.fluidRenderer)===null||t===void 0||t._prepareRendering()}_afterCameraDraw(e){var t;(t=this.scene.fluidRenderer)===null||t===void 0||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}}class mT{static _SceneComponentInitialization(e){let t=e._getComponent(Fe.NAME_FLUIDRENDERER);t||(t=new I5(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,mT._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 s5(this._scene,e);r.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new RC(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 r5(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),s||(s=new RC(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(s.generateDiffuseTexture=i);const a={object:n,targetRenderer:s};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}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.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){const e={};for(let s=0;s{var h;n.inputTexture.depthStencilTexture||n.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,a[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${n.name}`);for(const c of a){const u=(h=c._thicknessRenderTarget)===null||h===void 0?void 0:h.renderTarget,d=u==null?void 0:u.texture;if(u&&d){const f=d.width+"_"+d.height;let p=l[f];p||(p=l[f]=new l5(this._engine,d.width,d.height)),p.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],a=e.get(s);if(a)for(const l in n)a[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{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 t;for(let s=0;s{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}Qe.prototype._internalPickSprites=function(o,e,t,i){if(!Vr)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=s.distance)&&(s=a,t))break}return s||new Vr};Qe.prototype._internalMultiPickSprites=function(o,e,t){if(!Vr)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._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 a5(this._scene,e);r.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new PC(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 o5(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),s||(s=new PC(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(s.generateDiffuseTexture=i);const a={object:n,targetRenderer:s};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}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.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){const e={};for(let s=0;s{var h;n.inputTexture.depthStencilTexture||n.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,a[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${n.name}`);for(const c of a){const u=(h=c._thicknessRenderTarget)===null||h===void 0?void 0:h.renderTarget,d=u==null?void 0:u.texture;if(u&&d){const f=d.width+"_"+d.height;let p=l[f];p||(p=l[f]=new u5(this._engine,d.width,d.height)),p.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],a=e.get(s);if(a)for(const l in n)a[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{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 t;for(let s=0;s{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}Qe.prototype._internalPickSprites=function(o,e,t,i){if(!Vr)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=s.distance)&&(s=a,t))break}return s||new Vr};Qe.prototype._internalMultiPickSprites=function(o,e,t){if(!Vr)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 #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT @@ -11630,7 +11630,7 @@ color*=vColor; gl_FragColor=color; #include #define CUSTOM_FRAGMENT_MAIN_END -}`;ne.ShadersStore[D5]=O5;const N5="spritesVertexShader",w5=`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; +}`;ne.ShadersStore[w5]=F5;const L5="spritesVertexShader",B5=`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 #define CUSTOM_VERTEX_DEFINITIONS void main(void) { @@ -11642,7 +11642,7 @@ vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts vFogDistance=viewPos; #endif #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[N5]=w5;const F5="spriteMapPixelShader",L5=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +}`;ne.ShadersStore[L5]=B5;const V5="spriteMapPixelShader",U5=`#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) @@ -11663,11 +11663,11 @@ vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0 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;}`;ne.ShadersStore[F5]=L5;const B5="spriteMapVertexShader",V5=`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;}`;ne.ShadersStore[B5]=V5;var IC;(function(o){o[o.INIT=0]="INIT",o[o.RUNNING=1]="RUNNING",o[o.DONE=2]="DONE",o[o.ERROR=3]="ERROR"})(IC||(IC={}));he.prototype.notifyObserversWithPromise=async function(o,e=-1,t,i,s){let r=Promise.resolve(o);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(a=>{n.skipNextObservers||a._willBeUnregistered||a.mask&e&&(a.scope?r=r.then(l=>(n.lastReturnValue=l,a.callback.apply(a.scope,[o,n]))):r=r.then(l=>(n.lastReturnValue=l,a.callback(o,n))),a.unregisterOnNextCall&&this._deferUnregister(a))}),await r,o};let Wl=null;function uA(o,e,t,i,s="image/png",r=!1,n){const{height:a,width:l}=dA(o,e,t);if(!(a&&l)){G.Error("Invalid 'size' parameter !");return}Wl||(Wl=document.createElement("canvas")),Wl.width=l,Wl.height=a;const h=Wl.getContext("2d"),c=o.getRenderWidth()/o.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const f=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;e.getScene().activeCamera!==e?gT(o,e,t,g=>{if(r){const v=new Blob([g]);fe.DownloadBlob(v),i&&i("")}else i&&i(g)},s,1,o.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):o.onEndFrameObservable.addOnce(()=>{const g=o.getRenderingCanvas();h&&g&&h.drawImage(g,f,p,u,d),Wl&&(r?(fe.EncodeScreenshotCanvasData(Wl,void 0,s,void 0,n),i&&i("")):fe.EncodeScreenshotCanvasData(Wl,i,s,void 0,n))})}function U5(o,e,t,i="image/png",s){return new Promise((r,n)=>{uA(o,e,t,a=>{typeof a<"u"?r(a):n(new Error("Data is undefined"))},i,void 0,s)})}function gT(o,e,t,i,s="image/png",r=1,n=!1,a,l=!1,h=!1,c=!0,u,d){const{height:f,width:p,finalWidth:_,finalHeight:g}=dA(o,e,t),v={width:p,height:f};if(!(f&&p)){G.Error("Invalid 'size' parameter !");return}const E={width:o.getRenderWidth(),height:o.getRenderHeight()};o.setSize(p,f);const C=e.getScene(),S=new ms("screenShot",v,C,!1,!1,0,!1,ee.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);S.renderList=C.meshes.slice(),S.samples=r,S.renderSprites=l,S.activeCamera=e,S.forceLayerMaskCheck=c,d==null||d(S);const b=()=>{S.isReadyForRendering()&&e.isReady(!0)?(o.onEndFrameObservable.addOnce(()=>{_===p&&g===f?S.readPixels(void 0,void 0,void 0,!1).then(I=>{tn.DumpData(p,f,I,i,s,a,!0,void 0,u),S.dispose()}):Ux("pass",S.getInternalTexture(),C,void 0,void 0,void 0,_,g).then(I=>{o._readTexturePixels(I,_,g,-1,0,null,!0,!1,0,0).then(N=>{tn.DumpData(_,g,N,i,s,a,!0,void 0,u),I.dispose()})})}),S.render(!0),C.incrementRenderId(),C.resetCachedMaterial(),o.setSize(E.width,E.height),e.getProjectionMatrix(!0),C.render()):setTimeout(b,16)},R=()=>{C.incrementRenderId(),C.resetCachedMaterial(),b()};if(n){const I=new yu("antialiasing",1,C.activeCamera);S.addPostProcess(I),I.getEffect().isReady()?R():I.getEffect().onCompiled=()=>{R()}}else R()}function k5(o,e,t,i="image/png",s=1,r=!1,n,a=!1,l=!1,h=!0,c){return new Promise((u,d)=>{gT(o,e,t,f=>{typeof f<"u"?u(f):d(new Error("Data is undefined"))},i,s,r,n,a,l,h,c)})}function dA(o,e,t){let i=0,s=0,r=0,n=0;if(typeof t=="object"){const a=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*a,s=t.width*a):t.width&&!t.height?(s=t.width*a,i=Math.round(s/o.getAspectRatio(e))):t.height&&!t.width?(i=t.height*a,s=Math.round(i*o.getAspectRatio(e))):(s=Math.round(o.getRenderWidth()*a),i=Math.round(s/o.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(n=t.finalHeight,r=t.finalWidth):t.finalWidth&&!t.finalHeight?(r=t.finalWidth,n=Math.round(r/o.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(n=t.finalHeight,r=Math.round(n*o.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 G5=()=>{fe.CreateScreenshot=uA,fe.CreateScreenshotAsync=U5,fe.CreateScreenshotUsingRenderTarget=gT,fe.CreateScreenshotUsingRenderTargetAsync=k5};G5();var PC;(function(o){o[o.Checkbox=0]="Checkbox",o[o.Slider=1]="Slider",o[o.Vector3=2]="Vector3",o[o.Quaternion=3]="Quaternion",o[o.Color3=4]="Color3",o[o.String=5]="String",o[o.Button=6]="Button",o[o.Options=7]="Options",o[o.Tab=8]="Tab",o[o.FileButton=9]="FileButton",o[o.Vector2=10]="Vector2"})(PC||(PC={}));class MC{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const t={};return{getItem:i=>{const s=t[i];return s===void 0?null:s},setItem:(i,s)=>{t[i]=s}}}}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())}}MC._Storage=MC._GetStorage();var DC;(function(o){class e{serialize(){const s={},r=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((n,a)=>{r[n]=a}),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,a=null){r=r??(()=>1),n=n??(()=>1),a=a??((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;ht._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 a=s._characters,l=r._characters,h=a.length,c=l.length,u=t._CostMatrix;u[0][0]=0;for(let d=0;dnew Array(t._MAX_SEQUENCE_LENGTH+1)),o.Sequence=t})(DC||(DC={}));new k;const z5=1.5;class Hl{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*z5),t=new Float32Array(e);t.set(this._view),this._view=t}}const Xl=1800,W5=24,H5="0",OC="timestamp",NC="numPoints",X5=/\r/g,Av="@";class vo{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=ar.Now-this._startingTimestamp,s=this.datasets.ids.length,r=this.datasets.startingIndices.itemLength;let n=0;if(r>0){const a=this.datasets.startingIndices.at(r-1);n=a+this.datasets.data.at(a+vo.NumberOfPointsOffset)+vo.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(i),this.datasets.data.push(s),this.datasets.ids.forEach(a=>{const l=this._strategies.get(a);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const a=[i,s];for(let l=0;li.callback(this._datasetMeta,new YC(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var s;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((s=this._strategies.get(e))===null||s===void 0||s.dispose(),this._strategies.delete(e));const r=a=>{let l=0,h=0;const c=a.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:()=>{a.onAfterRenderObservable.remove(c),this._customEventObservable.remove(u)}}},n={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:r,category:i}),n}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(Av,"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>s&255;i+=(H5+r.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=ar.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 Hl(Xl),this.datasets.ids.length=0,this.datasets.startingIndices=new Hl(Xl),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(X5,"").split(` -`).map(u=>u.split(",").filter(d=>d.length>0)).filter(u=>u.length>0),s=0,r=vo.NumberOfPointsOffset;if(i.length<2)return!1;const n={ids:[],data:new Hl(Xl),startingIndices:new Hl(Xl)},[a,...l]=i;if(a.length<2||a[s]!==OC||a[r]!==NC)return!1;const h=new Map;for(let u=vo.SliceDataOffset;uu.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+=`${OC},${NC}`;for(let i=0;i{n.skipNextObservers||a._willBeUnregistered||a.mask&e&&(a.scope?r=r.then(l=>(n.lastReturnValue=l,a.callback.apply(a.scope,[o,n]))):r=r.then(l=>(n.lastReturnValue=l,a.callback(o,n))),a.unregisterOnNextCall&&this._deferUnregister(a))}),await r,o};let Hl=null;function pA(o,e,t,i,s="image/png",r=!1,n){const{height:a,width:l}=_A(o,e,t);if(!(a&&l)){G.Error("Invalid 'size' parameter !");return}Hl||(Hl=document.createElement("canvas")),Hl.width=l,Hl.height=a;const h=Hl.getContext("2d"),c=o.getRenderWidth()/o.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const f=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;e.getScene().activeCamera!==e?xT(o,e,t,g=>{if(r){const v=new Blob([g]);fe.DownloadBlob(v),i&&i("")}else i&&i(g)},s,1,o.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):o.onEndFrameObservable.addOnce(()=>{const g=o.getRenderingCanvas();h&&g&&h.drawImage(g,f,p,u,d),Hl&&(r?(fe.EncodeScreenshotCanvasData(Hl,void 0,s,void 0,n),i&&i("")):fe.EncodeScreenshotCanvasData(Hl,i,s,void 0,n))})}function z5(o,e,t,i="image/png",s){return new Promise((r,n)=>{pA(o,e,t,a=>{typeof a<"u"?r(a):n(new Error("Data is undefined"))},i,void 0,s)})}function xT(o,e,t,i,s="image/png",r=1,n=!1,a,l=!1,h=!1,c=!0,u,d){const{height:f,width:p,finalWidth:_,finalHeight:g}=_A(o,e,t),v={width:p,height:f};if(!(f&&p)){G.Error("Invalid 'size' parameter !");return}const E={width:o.getRenderWidth(),height:o.getRenderHeight()};o.setSize(p,f);const C=e.getScene(),S=new ms("screenShot",v,C,!1,!1,0,!1,ee.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);S.renderList=C.meshes.slice(),S.samples=r,S.renderSprites=l,S.activeCamera=e,S.forceLayerMaskCheck=c,d==null||d(S);const b=()=>{S.isReadyForRendering()&&e.isReady(!0)?(o.onEndFrameObservable.addOnce(()=>{_===p&&g===f?S.readPixels(void 0,void 0,void 0,!1).then(I=>{tn.DumpData(p,f,I,i,s,a,!0,void 0,u),S.dispose()}):Gx("pass",S.getInternalTexture(),C,void 0,void 0,void 0,_,g).then(I=>{o._readTexturePixels(I,_,g,-1,0,null,!0,!1,0,0).then(N=>{tn.DumpData(_,g,N,i,s,a,!0,void 0,u),I.dispose()})})}),S.render(!0),C.incrementRenderId(),C.resetCachedMaterial(),o.setSize(E.width,E.height),e.getProjectionMatrix(!0),C.render()):setTimeout(b,16)},R=()=>{C.incrementRenderId(),C.resetCachedMaterial(),b()};if(n){const I=new yu("antialiasing",1,C.activeCamera);S.addPostProcess(I),I.getEffect().isReady()?R():I.getEffect().onCompiled=()=>{R()}}else R()}function W5(o,e,t,i="image/png",s=1,r=!1,n,a=!1,l=!1,h=!0,c){return new Promise((u,d)=>{xT(o,e,t,f=>{typeof f<"u"?u(f):d(new Error("Data is undefined"))},i,s,r,n,a,l,h,c)})}function _A(o,e,t){let i=0,s=0,r=0,n=0;if(typeof t=="object"){const a=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*a,s=t.width*a):t.width&&!t.height?(s=t.width*a,i=Math.round(s/o.getAspectRatio(e))):t.height&&!t.width?(i=t.height*a,s=Math.round(i*o.getAspectRatio(e))):(s=Math.round(o.getRenderWidth()*a),i=Math.round(s/o.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(n=t.finalHeight,r=t.finalWidth):t.finalWidth&&!t.finalHeight?(r=t.finalWidth,n=Math.round(r/o.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(n=t.finalHeight,r=Math.round(n*o.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 H5=()=>{fe.CreateScreenshot=pA,fe.CreateScreenshotAsync=z5,fe.CreateScreenshotUsingRenderTarget=xT,fe.CreateScreenshotUsingRenderTargetAsync=W5};H5();var DC;(function(o){o[o.Checkbox=0]="Checkbox",o[o.Slider=1]="Slider",o[o.Vector3=2]="Vector3",o[o.Quaternion=3]="Quaternion",o[o.Color3=4]="Color3",o[o.String=5]="String",o[o.Button=6]="Button",o[o.Options=7]="Options",o[o.Tab=8]="Tab",o[o.FileButton=9]="FileButton",o[o.Vector2=10]="Vector2"})(DC||(DC={}));class OC{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const t={};return{getItem:i=>{const s=t[i];return s===void 0?null:s},setItem:(i,s)=>{t[i]=s}}}}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())}}OC._Storage=OC._GetStorage();var NC;(function(o){class e{serialize(){const s={},r=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((n,a)=>{r[n]=a}),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,a=null){r=r??(()=>1),n=n??(()=>1),a=a??((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;ht._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 a=s._characters,l=r._characters,h=a.length,c=l.length,u=t._CostMatrix;u[0][0]=0;for(let d=0;dnew Array(t._MAX_SEQUENCE_LENGTH+1)),o.Sequence=t})(NC||(NC={}));new k;const X5=1.5;class Xl{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*X5),t=new Float32Array(e);t.set(this._view),this._view=t}}const Yl=1800,Y5=24,$5="0",wC="timestamp",FC="numPoints",K5=/\r/g,Av="@";class vo{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=ar.Now-this._startingTimestamp,s=this.datasets.ids.length,r=this.datasets.startingIndices.itemLength;let n=0;if(r>0){const a=this.datasets.startingIndices.at(r-1);n=a+this.datasets.data.at(a+vo.NumberOfPointsOffset)+vo.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(i),this.datasets.data.push(s),this.datasets.ids.forEach(a=>{const l=this._strategies.get(a);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const a=[i,s];for(let l=0;li.callback(this._datasetMeta,new KC(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var s;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((s=this._strategies.get(e))===null||s===void 0||s.dispose(),this._strategies.delete(e));const r=a=>{let l=0,h=0;const c=a.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:()=>{a.onAfterRenderObservable.remove(c),this._customEventObservable.remove(u)}}},n={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:r,category:i}),n}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(Av,"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>s&255;i+=($5+r.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=ar.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 Xl(Yl),this.datasets.ids.length=0,this.datasets.startingIndices=new Xl(Yl),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(K5,"").split(` +`).map(u=>u.split(",").filter(d=>d.length>0)).filter(u=>u.length>0),s=0,r=vo.NumberOfPointsOffset;if(i.length<2)return!1;const n={ids:[],data:new Xl(Yl),startingIndices:new Xl(Yl)},[a,...l]=i;if(a.length<2||a[s]!==wC||a[r]!==FC)return!1;const h=new Map;for(let u=vo.SliceDataOffset;uu.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+=`${wC},${FC}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}Qe.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new vo(this)),this._perfCollector};function Y5(o){const e=new Array,t=new Array,i=new Array,s=o.add(()=>{const n=e.length;for(let a=0;a{e.push(n),t.push(a),i.push(l)},dispose:()=>{o.remove(s)}}}he.prototype.runCoroutineAsync=function(o){if(!this._coroutineScheduler){const e=Y5(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return vb(o,this._coroutineScheduler)};he.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const $5="equirectangularPanoramaPixelShader",K5=`#ifdef GL_ES +`}const t=`${new Date().toISOString()}-perfdata.csv`;fe.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?this._startingTimestamp===void 0&&(this._startingTimestamp=ar.Now):(this.datasets.data=new Xl(Yl),this.datasets.startingIndices=new Xl(Yl),this._startingTimestamp=ar.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}}Qe.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new vo(this)),this._perfCollector};function q5(o){const e=new Array,t=new Array,i=new Array,s=o.add(()=>{const n=e.length;for(let a=0;a{e.push(n),t.push(a),i.push(l)},dispose:()=>{o.remove(s)}}}he.prototype.runCoroutineAsync=function(o){if(!this._coroutineScheduler){const e=q5(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Tb(o,this._coroutineScheduler)};he.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const j5="equirectangularPanoramaPixelShader",Q5=`#ifdef GL_ES precision highp float; #endif #define M_PI 3.1415926535897932384626433832795 @@ -11675,7 +11675,7 @@ varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float - sin( longitude )*sin( latitude ), cos( latitude ), - cos( longitude )*sin( latitude ) -);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;ne.ShadersStore[$5]=K5;class ah extends Cr{constructor(e,t={}){super(e),this.options=t,this._direction=new T(0,0,-1),this._mat=new k,this._onSelectEnabled=!1,this._origin=new T(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new he,this._onHitTestResults=i=>{const s=i.map(r=>{const n=k.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&&ah.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",fe.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||(a=>!!a.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;k.FromArrayToRef(t.transform.matrix,0,this._mat),T.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),T.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});ah.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}ah.Name=oi.HIT_TEST;ah.Version=1;_s.AddWebXRFeature(ah.Name,(o,e)=>()=>new ah(o,e),ah.Version,!1);let q5=0;class ad extends Cr{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 he,this.onAnchorRemovedObservable=new he,this.onAnchorUpdatedObservable=new he,this._tmpVector=new T,this._tmpQuaternion=new Se,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 T,i=new Se){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,a)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!0,xrTransformation:s,resolve:n,reject:a})})}catch(r){throw new Error(r)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new Se,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,a)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:n,reject:a})})}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),a=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(r,a,e),a.attachedNode&&(a.attachedNode.rotationQuaternion=a.attachedNode.rotationQuaternion||new Se,a.transformationMatrix.decompose(a.attachedNode.scaling,a.attachedNode.rotationQuaternion,a.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(a)}catch{fe.Warn("Anchor could not be updated")}}else{const n={id:q5++,xrAnchor:r,remove:()=>r.delete()},a=this._updateAnchorWithXRFrame(r,n,e);this._trackedAnchors.push(a),this.onAnchorAddedObservable.notifyObservers(a);const h=this._futureAnchors.filter(c=>c.nativeAnchor===r)[0];h&&(h.resolve(a),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()=>new ad(o,e),ad.Version);let j5=0;class od extends Cr{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new he,this.onPlaneRemovedObservable=new he,this.onPlaneUpdatedObservable=new he,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 t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||((t=e.worldInformation)===null||t===void 0?void 0:t.detectedPlanes);if(i){for(let s=0;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:j5++,xrPlane:s,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(s,r,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}}),this._lastFrameDetected=i}}_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 T(r.x,r.y,r.z*n)});const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new k;k.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()=>new od(o,e),od.Version);class ld extends Cr{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new he}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)}}ld.Name=oi.BACKGROUND_REMOVER;ld.Version=1;_s.AddWebXRFeature(ld.Name,(o,e)=>()=>new ld(o,e),ld.Version,!0);class hd extends Cr{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||Ct.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=Qo("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 Se;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new Ct(s,t,Object.assign({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()||G.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 Ct(s.rootMesh,Ct.MeshImpostor,Object.assign({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 Se,this._tmpVector=new T,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:Ct.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Qo("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 Se,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Ct(this._headsetMesh,e.impostorType,Object.assign({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=Object.assign(Object.assign({},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===void 0)&&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===void 0)&&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 r,n;const a=this._controllers[s],l=a.xrController.grip||a.xrController.pointer,h=a.oldPos||a.impostorMesh.position;if(!((r=a.xrController._lastXRPose)===null||r===void 0)&&r.linearVelocity){const u=a.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),a.impostor.setLinearVelocity(this._tmpVector)}else l.position.subtractToRef(h,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),a.impostor.setLinearVelocity(this._tmpVector);h.copyFrom(l.position),this._debugMode&&G.Log([this._tmpVector,"linear"]);const c=a.oldRotation||a.impostorMesh.rotationQuaternion;if(!((n=a.xrController._lastXRPose)===null||n===void 0)&&n.angularVelocity){const u=a.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),a.impostor.setAngularVelocity(this._tmpVector)}else if(!c.equalsWithEpsilon(l.rotationQuaternion)){c.conjugateInPlace().multiplyToRef(l.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)))}a.impostor.setAngularVelocity(this._tmpVector)}c.copyFrom(l.rotationQuaternion),this._debugMode&&G.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}hd.Name=oi.PHYSICS_CONTROLLERS;hd.Version=1;_s.AddWebXRFeature(hd.Name,(o,e)=>()=>new hd(o,e),hd.Version,!0);class cd extends Cr{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new k,this._tmpPos=new T,this._tmpQuat=new Se,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){fe.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 he,this.paused=!1,this.xrNativeFeatureName="hit-test",fe.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,a=r.transform.orientation;this._tmpPos.set(n.x,n.y,n.z),this._tmpQuat.set(a.x,a.y,a.z,a.w),k.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)}}cd.Name=oi.HIT_TEST;cd.Version=2;_s.AddWebXRFeature(cd.Name,(o,e)=>()=>new cd(o,e),cd.Version,!1);class ud extends Cr{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new he,this.onFeaturePointsUpdatedObservable=new he,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;n0&&this.onFeaturePointsAddedObservable.notifyObservers(r),s.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(s)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}ud.Name=oi.FEATURE_POINTS;ud.Version=1;_s.AddWebXRFeature(ud.Name,o=>()=>new ud(o),ud.Version);let Q5=0;class dd extends Cr{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new he,this.onMeshRemovedObservable=new he,this.onMeshUpdatedObservable=new he,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||t===void 0?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:Q5++,xrMesh:r},a=this._updateVertexDataWithXRMesh(r,n,e);this._detectedMeshes.set(r,a),this.onMeshAddedObservable.notifyObservers(a)}})}}catch(i){G.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 s;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let a=0;a()=>new dd(o,e),dd.Version,!1);var Fo;(function(o){o[o.NotReceived=0]="NotReceived",o[o.Waiting=1]="Waiting",o[o.Received=2]="Received"})(Fo||(Fo={}));class fd extends Cr{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new he,this.onTrackableImageFoundObservable=new he,this.onTrackedImageUpdatedObservable=new he,this._trackableScoreStatus=Fo.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 fe.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===Fo.Waiting)return;if(this._trackableScoreStatus===Fo.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 a=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(a){const c=n.transformationMatrix;k.FromArrayToRef(a.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!==Fo.NotReceived)return;this._trackableScoreStatus=Fo.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=Fo.NotReceived;return}for(let t=0;t0?Fo.Received:Fo.NotReceived}}fd.Name=oi.IMAGE_TRACKING;fd.Version=1;_s.AddWebXRFeature(fd.Name,(o,e)=>()=>new fd(o,e),fd.Version,!1);class pd extends Cr{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",fe.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 fe.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 fe.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}}}}pd.Name=oi.DOM_OVERLAY;pd.Version=1;_s.AddWebXRFeature(pd.Name,(o,e)=>()=>new pd(o,e),pd.Version,!1);class oh extends Cr{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){var i,s,r,n,a,l;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new Se,this._tmpRotationMatrix=k.Identity(),this._tmpTranslationDirection=new T,this._tmpMovementTranslation=new T,this._tempCacheQuaternion=new Se,this._attachController=h=>{if(this._controllers[h.uniqueId])return;this._controllers[h.uniqueId]={xrController:h,registeredComponents:[]};const c=this._controllers[h.uniqueId];if(c.xrController.inputSource.targetRayMode==="tracked-pointer"&&c.xrController.inputSource.gamepad){const u=()=>{if(h.motionController)for(const d of this._currentRegistrationConfigurations){let f=null;if(d.allowedComponentTypes)for(const _ of d.allowedComponentTypes){const g=h.motionController.getComponentOfType(_);if(g!==null){f=g;break}}if(d.mainComponentOnly){const _=h.motionController.getMainComponent();if(_===null)continue;f=_}if(typeof d.componentSelectionPredicate=="function"&&(f=d.componentSelectionPredicate(h)),f&&d.forceHandedness&&h.inputSource.handedness!==d.forceHandedness||f===null)continue;const p={registrationConfiguration:d,component:f};c.registeredComponents.push(p),"axisChangedHandler"in d&&(p.onAxisChangedObserver=f.onAxisValueChangedObservable.add(_=>{d.axisChangedHandler(_,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in d&&(p.onButtonChangedObserver=f.onButtonStateChangedObservable.add(()=>{f.changes.pressed&&d.buttonChangedhandler(f.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};h.motionController?u():h.onMotionControllerInitObservable.addOnce(()=>{u()})}},!t||t.xrInput===void 0){fe.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=oh.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:(i=t.movementOrientationFollowsViewerPose)!==null&&i!==void 0?i:!0,movementSpeed:(s=t.movementSpeed)!==null&&s!==void 0?s:1,movementThreshold:(r=t.movementThreshold)!==null&&r!==void 0?r:.25,rotationEnabled:(n=t.rotationEnabled)!==null&&n!==void 0?n:!0,rotationSpeed:(a=t.rotationSpeed)!==null&&a!==void 0?a:1,rotationThreshold:(l=t.rotationThreshold)!==null&&l!==void 0?l:.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,Se.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(Se.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&&(k.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),T.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]}}}oh.Name=oi.MOVEMENT;oh.REGISTRATIONS={default:[{allowedComponentTypes:[la.THUMBSTICK_TYPE,la.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(o,e,t)=>{e.rotateX=Math.abs(o.x)>t.rotationThreshold?o.x:0,e.rotateY=Math.abs(o.y)>t.rotationThreshold?o.y:0}},{allowedComponentTypes:[la.THUMBSTICK_TYPE,la.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(o,e,t)=>{e.moveX=Math.abs(o.x)>t.movementThreshold?o.x:0,e.moveY=Math.abs(o.y)>t.movementThreshold?o.y:0}}]};oh.Version=1;_s.AddWebXRFeature(oh.Name,(o,e)=>()=>new oh(o,e),oh.Version,!0);class _d extends Cr{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=T.Up().negateInPlace(),this._lightColor=Te.White(),this._intensity=1,this._sphericalHarmonics=new su,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new he,this._updateReflectionCubeMap=()=>{var i;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const r=Date.now();if(r-this._cubeMapPollTime{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 ro("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new T(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Bi.FALLOFF_GLTF),this._hdrFilter=new xy(this._xrSessionManager.scene.getEngine()),fe.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(){var e;if(!super.attach())return!1;const t=(e=this.options.reflectionFormat)!==null&&e!==void 0?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(i=>{this._xrLightProbe=i,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Ei(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()=>new _d(o,e),_d.Version,!1);class md extends Cr{constructor(e){super(e),this.onEyeTrackingStartedObservable=new he,this.onEyeTrackingEndedObservable=new he,this.onEyeTrackingFrameUpdateObservable=new he,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new Kt(T.Zero(),T.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);const i=t.transform.orientation;K.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?T.RightHandedForwardReadOnly.rotateByQuaternionToRef(K.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,K.Quaternion[0].z*=-1,K.Quaternion[0].w*=-1,T.LeftHandedForwardReadOnly.rotateByQuaternionToRef(K.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))}}md.Name=oi.EYE_TRACKING;md.Version=1;_s.AddWebXRFeature(md.Name,o=>()=>new md(o),md.Version,!1);class Z5{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class J5{constructor(){this._samples=new Z5(20),this._entropy=0,this.onFirstStepDetected=new he}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=Re.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;na&&(l=b,a=S);if(an*this._squaredProjectionDistanceThreshold)return;const _=K.Vector3[0];_.set(i,s,0);const g=K.Vector3[1];g.set(c.x,c.y,0);const v=T.Cross(_,g).z>0,E=r.clone(),C=r.clone();h.subtractToRef(r,c),v?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,E),c.scaleAndAddToRef(this._axisToApexExtendFactor,C)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,E),c.scaleAndAddToRef(this._axisToApexShrinkFactor,C)),this.onFirstStepDetected.notifyObservers({leftApex:E,rightApex:C,currentPosition:r,currentStepDirection:v?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(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 gd{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new J5,this._walker=null,this._movement=new Re,this._millisecondsSinceLastUpdate=gd._MillisecondsPerUpdate,this.movementThisFrame=T.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new eY(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{G.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>=gd._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=gd._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 Rv extends Cr{static get Name(){return oi.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 T,this._forward=new T,this._position=new T,this._movement=new T,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&G.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 gd(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||T.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}_s.AddWebXRFeature(Rv.Name,(o,e)=>()=>new Rv(o,e),Rv.Version,!1);class tY extends bx{constructor(e,t,i,s,r,n){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n}}class iY extends yx{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,s,r,n;const a=this._lastSubImages.get(t),l=t=="left"?0:1,h=(i=e.colorTextureWidth)!==null&&i!==void 0?i:e.textureWidth,c=(s=e.colorTextureHeight)!==null&&s!==void 0?s:e.textureHeight;if(!this._renderTargetTextures[l]||(a==null?void 0:a.textureWidth)!==h||(a==null?void 0:a.textureHeight)!==c){let u;const d=(r=e.depthStencilTextureWidth)!==null&&r!==void 0?r:h,f=(n=e.depthStencilTextureHeight)!==null&&n!==void 0?n:c;(h===d||c===f)&&(u=e.depthStencilTexture),this._renderTargetTextures[l]=this._createRenderTargetTexture(h,c,null,e.colorTexture,u,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:h,framebufferHeight:c}}return this._lastSubImages.set(t,e),this._renderTargetTextures[l]}_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.eye)}_setViewportForSubImage(e,t){var i,s;const r=(i=t.colorTextureWidth)!==null&&i!==void 0?i:t.textureWidth,n=(s=t.colorTextureWidth)!==null&&s!==void 0?s:t.textureHeight,a=t.viewport;e.x=a.x/r,e.y=a.y/n,e.width=a.width/r,e.height=a.height/n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class sY extends tY{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,s=>new rY(s,i,this)),this.layer=e}}class rY extends iY{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 nY={},wC={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class vd extends Cr{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],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=Object.assign({},wC),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return super.detach()?(this._existingLayers.length=0,!0):!1}createXRWebGLLayer(e=nY){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Ax(t)}createProjectionLayer(e=wC,t=!1){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'.");const i=this._xrWebGLBinding.createProjectionLayer(e);return new sY(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;const t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}vd.Name=oi.LAYERS;vd.Version=1;_s.AddWebXRFeature(vd.Name,(o,e)=>()=>new vd(o,e),vd.Version,!1);class xd extends Cr{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(){var e,t;if(!this._cachedWebGLTexture)return null;const i=this._xrSessionManager.scene.getEngine(),s=new Ti(i,Vt.Unknown);return s.isCube=!1,s.invertY=!1,s._useSRGBBuffer=!1,s.format=this.depthDataFormat==="ushort"?2:5,s.generateMipMaps=!1,s.type=this.depthDataFormat==="ushort"?5:1,s.samplingMode=7,s.width=(e=this.width)!==null&&e!==void 0?e:0,s.height=(t=this.height)!==null&&t!==void 0?t:0,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new uu(this._cachedWebGLTexture,i._gl),s}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 he,this.xrNativeFeatureName="depth-sensing",fe.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===void 0||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:fe.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:a,rawValueToMeters:l,getDepthInMeters:h}=s;switch(this._width=n,this._height=a,this._rawValueToMeters=l,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(h.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ws.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,ee.NEAREST_SAMPLINGMODE,re.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:a}=s;this._width=n,this._height=a,this._cachedWebGLTexture=r;const l=this._xrSessionManager.scene,c=l.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ws.CreateRTexture(null,n,a,l,!1,!0,ee.NEAREST_SAMPLINGMODE,i==="ushort"?re.TEXTURETYPE_UNSIGNED_BYTE:re.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({})})}}xd.Name=oi.DEPTH_SENSING;xd.Version=1;_s.AddWebXRFeature(xd.Name,(o,e)=>()=>new xd(o,e),xd.Version,!1);const aY="velocityPixelShader",oY=`precision highp float; +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;ne.ShadersStore[j5]=Q5;class oh extends Cr{constructor(e,t={}){super(e),this.options=t,this._direction=new T(0,0,-1),this._mat=new k,this._onSelectEnabled=!1,this._origin=new T(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new he,this._onHitTestResults=i=>{const s=i.map(r=>{const n=k.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&&oh.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",fe.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||(a=>!!a.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;k.FromArrayToRef(t.transform.matrix,0,this._mat),T.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),T.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});oh.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}oh.Name=oi.HIT_TEST;oh.Version=1;_s.AddWebXRFeature(oh.Name,(o,e)=>()=>new oh(o,e),oh.Version,!1);let Z5=0;class ad extends Cr{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 he,this.onAnchorRemovedObservable=new he,this.onAnchorUpdatedObservable=new he,this._tmpVector=new T,this._tmpQuaternion=new Se,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 T,i=new Se){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,a)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!0,xrTransformation:s,resolve:n,reject:a})})}catch(r){throw new Error(r)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new Se,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,a)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:n,reject:a})})}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),a=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(r,a,e),a.attachedNode&&(a.attachedNode.rotationQuaternion=a.attachedNode.rotationQuaternion||new Se,a.transformationMatrix.decompose(a.attachedNode.scaling,a.attachedNode.rotationQuaternion,a.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(a)}catch{fe.Warn("Anchor could not be updated")}}else{const n={id:Z5++,xrAnchor:r,remove:()=>r.delete()},a=this._updateAnchorWithXRFrame(r,n,e);this._trackedAnchors.push(a),this.onAnchorAddedObservable.notifyObservers(a);const h=this._futureAnchors.filter(c=>c.nativeAnchor===r)[0];h&&(h.resolve(a),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()=>new ad(o,e),ad.Version);let J5=0;class od extends Cr{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new he,this.onPlaneRemovedObservable=new he,this.onPlaneUpdatedObservable=new he,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 t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||((t=e.worldInformation)===null||t===void 0?void 0:t.detectedPlanes);if(i){for(let s=0;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:J5++,xrPlane:s,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(s,r,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}}),this._lastFrameDetected=i}}_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 T(r.x,r.y,r.z*n)});const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new k;k.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()=>new od(o,e),od.Version);class ld extends Cr{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new he}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)}}ld.Name=oi.BACKGROUND_REMOVER;ld.Version=1;_s.AddWebXRFeature(ld.Name,(o,e)=>()=>new ld(o,e),ld.Version,!0);class hd extends Cr{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||Ct.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=Qo("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 Se;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new Ct(s,t,Object.assign({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()||G.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 Ct(s.rootMesh,Ct.MeshImpostor,Object.assign({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 Se,this._tmpVector=new T,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:Ct.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Qo("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 Se,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Ct(this._headsetMesh,e.impostorType,Object.assign({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=Object.assign(Object.assign({},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===void 0)&&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===void 0)&&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 r,n;const a=this._controllers[s],l=a.xrController.grip||a.xrController.pointer,h=a.oldPos||a.impostorMesh.position;if(!((r=a.xrController._lastXRPose)===null||r===void 0)&&r.linearVelocity){const u=a.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),a.impostor.setLinearVelocity(this._tmpVector)}else l.position.subtractToRef(h,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),a.impostor.setLinearVelocity(this._tmpVector);h.copyFrom(l.position),this._debugMode&&G.Log([this._tmpVector,"linear"]);const c=a.oldRotation||a.impostorMesh.rotationQuaternion;if(!((n=a.xrController._lastXRPose)===null||n===void 0)&&n.angularVelocity){const u=a.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),a.impostor.setAngularVelocity(this._tmpVector)}else if(!c.equalsWithEpsilon(l.rotationQuaternion)){c.conjugateInPlace().multiplyToRef(l.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)))}a.impostor.setAngularVelocity(this._tmpVector)}c.copyFrom(l.rotationQuaternion),this._debugMode&&G.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}hd.Name=oi.PHYSICS_CONTROLLERS;hd.Version=1;_s.AddWebXRFeature(hd.Name,(o,e)=>()=>new hd(o,e),hd.Version,!0);class cd extends Cr{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new k,this._tmpPos=new T,this._tmpQuat=new Se,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){fe.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 he,this.paused=!1,this.xrNativeFeatureName="hit-test",fe.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,a=r.transform.orientation;this._tmpPos.set(n.x,n.y,n.z),this._tmpQuat.set(a.x,a.y,a.z,a.w),k.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)}}cd.Name=oi.HIT_TEST;cd.Version=2;_s.AddWebXRFeature(cd.Name,(o,e)=>()=>new cd(o,e),cd.Version,!1);class ud extends Cr{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new he,this.onFeaturePointsUpdatedObservable=new he,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;n0&&this.onFeaturePointsAddedObservable.notifyObservers(r),s.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(s)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}ud.Name=oi.FEATURE_POINTS;ud.Version=1;_s.AddWebXRFeature(ud.Name,o=>()=>new ud(o),ud.Version);let eY=0;class dd extends Cr{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new he,this.onMeshRemovedObservable=new he,this.onMeshUpdatedObservable=new he,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||t===void 0?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:eY++,xrMesh:r},a=this._updateVertexDataWithXRMesh(r,n,e);this._detectedMeshes.set(r,a),this.onMeshAddedObservable.notifyObservers(a)}})}}catch(i){G.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 s;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let a=0;a()=>new dd(o,e),dd.Version,!1);var Fo;(function(o){o[o.NotReceived=0]="NotReceived",o[o.Waiting=1]="Waiting",o[o.Received=2]="Received"})(Fo||(Fo={}));class fd extends Cr{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new he,this.onTrackableImageFoundObservable=new he,this.onTrackedImageUpdatedObservable=new he,this._trackableScoreStatus=Fo.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 fe.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===Fo.Waiting)return;if(this._trackableScoreStatus===Fo.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 a=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(a){const c=n.transformationMatrix;k.FromArrayToRef(a.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!==Fo.NotReceived)return;this._trackableScoreStatus=Fo.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=Fo.NotReceived;return}for(let t=0;t0?Fo.Received:Fo.NotReceived}}fd.Name=oi.IMAGE_TRACKING;fd.Version=1;_s.AddWebXRFeature(fd.Name,(o,e)=>()=>new fd(o,e),fd.Version,!1);class pd extends Cr{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",fe.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 fe.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 fe.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}}}}pd.Name=oi.DOM_OVERLAY;pd.Version=1;_s.AddWebXRFeature(pd.Name,(o,e)=>()=>new pd(o,e),pd.Version,!1);class lh extends Cr{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){var i,s,r,n,a,l;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new Se,this._tmpRotationMatrix=k.Identity(),this._tmpTranslationDirection=new T,this._tmpMovementTranslation=new T,this._tempCacheQuaternion=new Se,this._attachController=h=>{if(this._controllers[h.uniqueId])return;this._controllers[h.uniqueId]={xrController:h,registeredComponents:[]};const c=this._controllers[h.uniqueId];if(c.xrController.inputSource.targetRayMode==="tracked-pointer"&&c.xrController.inputSource.gamepad){const u=()=>{if(h.motionController)for(const d of this._currentRegistrationConfigurations){let f=null;if(d.allowedComponentTypes)for(const _ of d.allowedComponentTypes){const g=h.motionController.getComponentOfType(_);if(g!==null){f=g;break}}if(d.mainComponentOnly){const _=h.motionController.getMainComponent();if(_===null)continue;f=_}if(typeof d.componentSelectionPredicate=="function"&&(f=d.componentSelectionPredicate(h)),f&&d.forceHandedness&&h.inputSource.handedness!==d.forceHandedness||f===null)continue;const p={registrationConfiguration:d,component:f};c.registeredComponents.push(p),"axisChangedHandler"in d&&(p.onAxisChangedObserver=f.onAxisValueChangedObservable.add(_=>{d.axisChangedHandler(_,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in d&&(p.onButtonChangedObserver=f.onButtonStateChangedObservable.add(()=>{f.changes.pressed&&d.buttonChangedhandler(f.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};h.motionController?u():h.onMotionControllerInitObservable.addOnce(()=>{u()})}},!t||t.xrInput===void 0){fe.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=lh.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:(i=t.movementOrientationFollowsViewerPose)!==null&&i!==void 0?i:!0,movementSpeed:(s=t.movementSpeed)!==null&&s!==void 0?s:1,movementThreshold:(r=t.movementThreshold)!==null&&r!==void 0?r:.25,rotationEnabled:(n=t.rotationEnabled)!==null&&n!==void 0?n:!0,rotationSpeed:(a=t.rotationSpeed)!==null&&a!==void 0?a:1,rotationThreshold:(l=t.rotationThreshold)!==null&&l!==void 0?l:.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,Se.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(Se.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&&(k.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),T.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]}}}lh.Name=oi.MOVEMENT;lh.REGISTRATIONS={default:[{allowedComponentTypes:[la.THUMBSTICK_TYPE,la.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(o,e,t)=>{e.rotateX=Math.abs(o.x)>t.rotationThreshold?o.x:0,e.rotateY=Math.abs(o.y)>t.rotationThreshold?o.y:0}},{allowedComponentTypes:[la.THUMBSTICK_TYPE,la.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(o,e,t)=>{e.moveX=Math.abs(o.x)>t.movementThreshold?o.x:0,e.moveY=Math.abs(o.y)>t.movementThreshold?o.y:0}}]};lh.Version=1;_s.AddWebXRFeature(lh.Name,(o,e)=>()=>new lh(o,e),lh.Version,!0);class _d extends Cr{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=T.Up().negateInPlace(),this._lightColor=Te.White(),this._intensity=1,this._sphericalHarmonics=new su,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new he,this._updateReflectionCubeMap=()=>{var i;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const r=Date.now();if(r-this._cubeMapPollTime{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 ro("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new T(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Bi.FALLOFF_GLTF),this._hdrFilter=new Ey(this._xrSessionManager.scene.getEngine()),fe.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(){var e;if(!super.attach())return!1;const t=(e=this.options.reflectionFormat)!==null&&e!==void 0?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(i=>{this._xrLightProbe=i,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Ei(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()=>new _d(o,e),_d.Version,!1);class md extends Cr{constructor(e){super(e),this.onEyeTrackingStartedObservable=new he,this.onEyeTrackingEndedObservable=new he,this.onEyeTrackingFrameUpdateObservable=new he,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new Kt(T.Zero(),T.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);const i=t.transform.orientation;K.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?T.RightHandedForwardReadOnly.rotateByQuaternionToRef(K.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,K.Quaternion[0].z*=-1,K.Quaternion[0].w*=-1,T.LeftHandedForwardReadOnly.rotateByQuaternionToRef(K.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))}}md.Name=oi.EYE_TRACKING;md.Version=1;_s.AddWebXRFeature(md.Name,o=>()=>new md(o),md.Version,!1);class tY{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class iY{constructor(){this._samples=new tY(20),this._entropy=0,this.onFirstStepDetected=new he}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=Re.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;na&&(l=b,a=S);if(an*this._squaredProjectionDistanceThreshold)return;const _=K.Vector3[0];_.set(i,s,0);const g=K.Vector3[1];g.set(c.x,c.y,0);const v=T.Cross(_,g).z>0,E=r.clone(),C=r.clone();h.subtractToRef(r,c),v?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,E),c.scaleAndAddToRef(this._axisToApexExtendFactor,C)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,E),c.scaleAndAddToRef(this._axisToApexShrinkFactor,C)),this.onFirstStepDetected.notifyObservers({leftApex:E,rightApex:C,currentPosition:r,currentStepDirection:v?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(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 gd{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new iY,this._walker=null,this._movement=new Re,this._millisecondsSinceLastUpdate=gd._MillisecondsPerUpdate,this.movementThisFrame=T.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new sY(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{G.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>=gd._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=gd._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 Rv extends Cr{static get Name(){return oi.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 T,this._forward=new T,this._position=new T,this._movement=new T,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&G.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 gd(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||T.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}_s.AddWebXRFeature(Rv.Name,(o,e)=>()=>new Rv(o,e),Rv.Version,!1);class rY extends Ax{constructor(e,t,i,s,r,n){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n}}class nY extends Rx{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,s,r,n;const a=this._lastSubImages.get(t),l=t=="left"?0:1,h=(i=e.colorTextureWidth)!==null&&i!==void 0?i:e.textureWidth,c=(s=e.colorTextureHeight)!==null&&s!==void 0?s:e.textureHeight;if(!this._renderTargetTextures[l]||(a==null?void 0:a.textureWidth)!==h||(a==null?void 0:a.textureHeight)!==c){let u;const d=(r=e.depthStencilTextureWidth)!==null&&r!==void 0?r:h,f=(n=e.depthStencilTextureHeight)!==null&&n!==void 0?n:c;(h===d||c===f)&&(u=e.depthStencilTexture),this._renderTargetTextures[l]=this._createRenderTargetTexture(h,c,null,e.colorTexture,u,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:h,framebufferHeight:c}}return this._lastSubImages.set(t,e),this._renderTargetTextures[l]}_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.eye)}_setViewportForSubImage(e,t){var i,s;const r=(i=t.colorTextureWidth)!==null&&i!==void 0?i:t.textureWidth,n=(s=t.colorTextureWidth)!==null&&s!==void 0?s:t.textureHeight,a=t.viewport;e.x=a.x/r,e.y=a.y/n,e.width=a.width/r,e.height=a.height/n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class aY extends rY{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,s=>new oY(s,i,this)),this.layer=e}}class oY extends nY{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 lY={},LC={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class vd extends Cr{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],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=Object.assign({},LC),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return super.detach()?(this._existingLayers.length=0,!0):!1}createXRWebGLLayer(e=lY){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Ix(t)}createProjectionLayer(e=LC,t=!1){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'.");const i=this._xrWebGLBinding.createProjectionLayer(e);return new aY(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;const t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}vd.Name=oi.LAYERS;vd.Version=1;_s.AddWebXRFeature(vd.Name,(o,e)=>()=>new vd(o,e),vd.Version,!1);class xd extends Cr{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(){var e,t;if(!this._cachedWebGLTexture)return null;const i=this._xrSessionManager.scene.getEngine(),s=new Ti(i,Ut.Unknown);return s.isCube=!1,s.invertY=!1,s._useSRGBBuffer=!1,s.format=this.depthDataFormat==="ushort"?2:5,s.generateMipMaps=!1,s.type=this.depthDataFormat==="ushort"?5:1,s.samplingMode=7,s.width=(e=this.width)!==null&&e!==void 0?e:0,s.height=(t=this.height)!==null&&t!==void 0?t:0,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new uu(this._cachedWebGLTexture,i._gl),s}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 he,this.xrNativeFeatureName="depth-sensing",fe.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===void 0||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:fe.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:a,rawValueToMeters:l,getDepthInMeters:h}=s;switch(this._width=n,this._height=a,this._rawValueToMeters=l,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(h.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ws.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,ee.NEAREST_SAMPLINGMODE,re.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:a}=s;this._width=n,this._height=a,this._cachedWebGLTexture=r;const l=this._xrSessionManager.scene,c=l.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Ws.CreateRTexture(null,n,a,l,!1,!0,ee.NEAREST_SAMPLINGMODE,i==="ushort"?re.TEXTURETYPE_UNSIGNED_BYTE:re.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({})})}}xd.Name=oi.DEPTH_SENSING;xd.Version=1;_s.AddWebXRFeature(xd.Name,(o,e)=>()=>new xd(o,e),xd.Version,!1);const hY="velocityPixelShader",cY=`precision highp float; #define CUSTOM_FRAGMENT_BEGIN varying vec4 clipPos;varying vec4 previousClipPos; #define CUSTOM_FRAGMENT_DEFINITIONS @@ -11683,7 +11683,7 @@ 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 -}`;ne.ShadersStore[aY]=oY;const lY="velocityVertexShader",hY=`#define CUSTOM_VERTEX_BEGIN +}`;ne.ShadersStore[hY]=cY;const uY="velocityVertexShader",dY=`#define CUSTOM_VERTEX_BEGIN #define VELOCITY attribute vec3 position; #include @@ -11704,17 +11704,17 @@ if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previous clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; #endif #define CUSTOM_VERTEX_MAIN_END -}`;ne.ShadersStore[lY]=hY;class cY extends ms{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=[k.Identity(),k.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 wa("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 uY{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},a=new cY(s,r,this._scene,n),l=a.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,a.disableRescaling(),a.renderListPredicate=()=>!0,a}_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 Td extends Cr{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[oi.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 uY(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)}}Td.Name=oi.SPACE_WARP;Td.Version=1;_s.AddWebXRFeature(Td.Name,o=>()=>new Td(o),Td.Version,!1);class Ed extends Cr{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new he,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,a=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:a,ay:l,gamma:h,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var i,s;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const r=(i=this._glBinding)===null||i===void 0?void 0:i.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(s=this._cachedInternalTextures[t]._hardwareTexture)===null||s===void 0||s.set(r);else{const n=new Ti(this._xrSessionManager.scene.getEngine(),Vt.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 uu(r,this._glContext),this._cachedInternalTextures[t]=n;const a=new Ei(this._xrSessionManager.scene);a.name=`WebXR Raw Camera Access (${t})`,a._texture=this._cachedInternalTextures[t],this.texturesData[t]=a,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)}}Ed.Name=oi.RAW_CAMERA_ACCESS;Ed.Version=1;_s.AddWebXRFeature(Ed.Name,(o,e)=>()=>new Ed(o,e),Ed.Version,!1);class dY extends Tu{constructor(e,t,i){super(e,fY[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(){}}vr.RegisterController("generic-hand-select-grasp",(o,e)=>new dY(e,o.gamepad,o.handedness));const fY={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 lh extends Tu{constructor(e,t,i){super(e,pY["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=lh.MODEL_LEFT_FILENAME:e=lh.MODEL_RIGHT_FILENAME;const t="default",i=lh.MODEL_BASE_URL+t+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=Ft.IsPluginForExtensionAvailable(".glb");return e||G.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){G.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){G.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 a=this.getComponent(t);a&&a.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else G.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){G.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(a=>{const l=s==="x-axis"?a.x:a.y;this._lerpTransform(r,l,!0)},void 0,!0):G.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new se(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew lh(e,o.gamepad,o.handedness));const pY={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 So extends Tu{constructor(e,t,i,s=!1,r=!1){super(e,_Y[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=So.MODEL_LEFT_FILENAME:e=So.MODEL_RIGHT_FILENAME;const t=this._isQuest()?So.QUEST_MODEL_BASE_URL:So.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 se(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Se.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}}So.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";So.MODEL_LEFT_FILENAME="left.babylon";So.MODEL_RIGHT_FILENAME="right.babylon";So.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";vr.RegisterController("oculus-touch",(o,e)=>new So(e,o.gamepad,o.handedness));vr.RegisterController("oculus-touch-legacy",(o,e)=>new So(e,o.gamepad,o.handedness,!0));const _Y={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 lu extends Tu{constructor(e,t,i){super(e,mY[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=lu.MODEL_FILENAME,t=lu.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 se(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=Se.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}lu.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";lu.MODEL_FILENAME="wand.babylon";vr.RegisterController("htc-vive",(o,e)=>new lu(e,o.gamepad,o.handedness));const mY={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 gY{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(8),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=()=>{var t;return(t=this._nativeImpl._imageTrackingResults)!==null&&t!==void 0?t:[]}}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")}}E2("NativeXRFrame",gY);var Zo;(function(o){o[o.Input=0]="Input",o[o.Output=1]="Output"})(Zo||(Zo={}));class jv{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=du(),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=fe.Instantiate(e.className),s=new i(e.name,e._connectionType,t);return s.deserialize(e),s}}class ua{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new ua(e.typeName,e.defaultValue)}}const qe=new ua("any",void 0),vY=new ua("string",""),zt=new ua("number",0),Nr=new ua("boolean",!1),Qv=new ua("Vector2",Re.Zero()),Pl=new ua("Vector3",T.Zero()),xY=new ua("Vector4",Dt.Zero());new ua("Matrix",k.Identity());const TY=new ua("Color3",Te.Black()),EY=new ua("Color4",new Ze(0,0,0,0)),SY=new ua("Quaternion",Se.Identity());function CY(o){switch(typeof o){case"string":return vY;case"number":return zt;case"boolean":return Nr;case"object":return o instanceof Re?Qv:o instanceof T?Pl:o instanceof Dt?xY:o instanceof Te?TY:o instanceof Ze?EY:o instanceof Se?SY:qe;default:return qe}}class Zv extends jv{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===Zo.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===Zo.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=jv.Parse(e,t);return i.richType=ua.Parse(e.richType),i}}j("FGDataConnection",Zv);const bY=/([./])({?\w+}?)/g;class Co{constructor(e){this._templateSubstitutions={},this._pathParts=[],this._templateStrings=[],this.hasTemplateStrings=!1,this._path=e;const{pathParts:t,templateStrings:i}=this._getPathPartsAndTemplateStrings(e);this._pathParts=t,this._templateStrings=i,this.hasTemplateStrings=i.length>0}_getPathPartsAndTemplateStrings(e){const t=e.matchAll(bY),i=[],s=[];let r=t.next();for(;!r.done;){const n=r.value,[,a,l]=n;let h=l,c=!1;l.startsWith("{")&&l.endsWith("}")&&(c=!0,h=l.slice(1,l.length-1),s.indexOf(h)===-1&&s.push(h)),i.push({value:l,isTemplate:c,valueWithoutBraces:h,separator:a}),r=t.next()}return{pathParts:i,templateStrings:s}}getTemplateStrings(){return this._templateStrings}setTemplateSubstitution(e,t){if(this._templateStrings.indexOf(e)===-1)throw new Error(`Template string ${e} does not exist in path ${this._path}`);this._templateSubstitutions[e]=t}_evaluateTemplates(){for(const e of this._pathParts)if(e.isTemplate){const t=this._templateSubstitutions[e.valueWithoutBraces];if(t===void 0)throw new Error(`Template string ${e.value} was not substituted`);e.replacedValue=t.toString()}}getFinalPath(){let e="";for(const t of this._pathParts)e+=t.separator,t.isTemplate?e+=t.replacedValue:e+=t.value;return e}_evaluatePath(e){this._evaluateTemplates();const t=[],i=[];let s=e.userVariables;for(const r of this._pathParts){if(s===void 0)throw new Error(`Could not find path ${this.getFinalPath()} in target context`);const n=r.isTemplate?r.replacedValue:r.value;if(!n)throw new Error(`Invalid path ${this.getFinalPath()}`);s=s[n],t.push(s),i.push(n)}return{entityChain:t,splitPath:i}}getProperty(e){for(const i of Co.Extensions)if(i.shouldProcess(this))return i.processGet(this,e);const{entityChain:t}=this._evaluatePath(e);return t[t.length-1]}setProperty(e,t){for(const a of Co.Extensions)if(a.shouldProcess(this)){a.processSet(this,e,t);return}const{entityChain:i,splitPath:s}=this._evaluatePath(e),r=i[i.length-2],n=s[s.length-1];r[n]=t}getClassName(){return Co.ClassName}serialize(e={}){return e.path=this._path,e.className=this.getClassName(),e}static Parse(e){return new Co(e.path)}}Co.Extensions=[];Co.ClassName="FGPath";j(Co.ClassName,Co);function fA(o){return o==="Mesh"||o==="AbstractMesh"||o==="GroundMesh"||o==="InstanceMesh"||o==="LinesMesh"||o==="GoldbergMesh"||o==="GreasedLineMesh"||o==="TrailMesh"}function pA(o){return o==="Vector2"||o==="Vector3"||o==="Vector4"||o==="Quaternion"||o==="Color3"||o==="Color4"}function yY(o,e){if(o==="Vector2")return Re.FromArray(e);if(o==="Vector3")return T.FromArray(e);if(o==="Vector4")return Dt.FromArray(e);if(o==="Quaternion")return Se.FromArray(e);if(o==="Color3")return new Te(e[0],e[1],e[2]);if(o==="Color4")return new Ze(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${o}`)}function vT(o,e,t){var i,s;const r=(s=(i=e==null?void 0:e.getClassName)===null||i===void 0?void 0:i.call(e))!==null&&s!==void 0?s:"";fA(r)?t[o]={name:e.name,className:r}:pA(r)?t[o]={value:e.asArray(),className:r}:t[o]=e}function _A(o,e,t){const i=e[o];let s;const r=i==null?void 0:i.className;return fA(r)?s=t.getMeshByName(i.name):pA(r)?s=yY(r,i.value):r===Co.ClassName?s=Co.Parse(i):i&&i.value!==void 0?s=i.value:s=i,s}class ac{constructor(e){this.config=e,this.uniqueId=du(),this.configure()}configure(){var e,t;this.name=(t=(e=this.config)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Zv(e,Zo.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Zv(e,Zo.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=vT){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,i=_A){const s=fe.Instantiate(e.className),r={};if(e.config)for(const a in e.config)r[a]=i(a,e.config,t);const n=new s(r);n.uniqueId=e.uniqueId;for(let a=0;at.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{var n,a,l;r.type===rt.POINTERPICK&&(!((n=r.pickInfo)===null||n===void 0)&&n.pickedMesh)&&(((a=r.pickInfo)===null||a===void 0?void 0:a.pickedMesh)===i||mA((l=r.pickInfo)===null||l===void 0?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 kd.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path.serialize()}}kd.ClassName="FGMeshPickEventBlock";j(kd.ClassName,kd);var FC;(function(o){o[o.Stopped=0]="Stopped",o[o.Started=1]="Started"})(FC||(FC={}));class ka extends oc{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Gd extends ka{constructor(e){super(e),this.message=this.registerDataInput("message",qe)}_execute(e){const t=this.message.getValue(e);G.Log(t),this.out._activateSignal(e)}getClassName(){return Gd.ClassName}}Gd.ClassName="FGConsoleLogBlock";j(Gd.ClassName,Gd);class zd extends ka{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,qe)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return zd.ClassName}}zd.ClassName="FGSetVariableBlock";j(zd.ClassName,zd);class $_{constructor(e,t){this.templateStringInputs=[],this.path=e,this.ownerBlock=t;for(const i of e.getTemplateStrings())this.templateStringInputs.push(this.ownerBlock.registerDataInput(i,zt))}substitutePath(e){for(const t of this.templateStringInputs){const i=t.getValue(e),s=t.name;this.path.setTemplateSubstitution(s,i)}return this.path}getProperty(e){return this.substitutePath(e),this.path.getProperty(e)}setProperty(e,t){this.substitutePath(e),this.path.setProperty(e,t)}}class Ym extends ka{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",qe),this.templateComponent=new $_(e.path,this)}_execute(e){const t=this.a.getValue(e);this.templateComponent.setProperty(e,t),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path.serialize()}getClassName(){return Ym.ClassName}}Ym.ClassName="FGSetPropertyBlock";j("FGSetPropertyBlock",Ym);class $m extends ka{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;es.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return $m.ClassName}}$m.ClassName="FGSendCustomEventBlock";j("FGSendCustomEventBlock",$m);class RY extends oc{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nr),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"}}j("FGBranchBlock",RY);class Wd extends ka{constructor(e={startIndex:0}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",zt),this.value=this.registerDataOutput("value",zt)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);is)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"}}j("FGThrottleBlock",PY);class Km extends xT{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 Tk({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):fe.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 Km.ClassName}}Km.ClassName="FGTimerBlock";j("FGTimerBlock",Km);class MY extends oc{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",zt)}configure(){super.configure(),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 e=0;e=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter(a=>a!==n),r.length===0)for(let a=0;a=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=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}j("FGDebounceBlock",wY);class FY extends oc{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Nr)}_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"}}j("FGFlipFlopBlock",FY);class Xd extends oc{constructor(e){super(e),this.config=e}configure(){super.configure(),this.outFlows=[];for(let e=0;ethis._onAnimationEnd(l,e));this.runningAnimatable.setValue(l,e),r.push(l)}e._setExecutionVariable(this,"runningAnimatables",r)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){var i;const s=(i=t._getExecutionVariable(this,"runningAnimatables"))!==null&&i!==void 0?i:[],r=s.indexOf(e);r!==-1&&s.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){var t;const i=(t=e._getExecutionVariable(this,"runningAnimatables"))!==null&&t!==void 0?t:[];for(const s of i)s.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath.serialize(),e.config.animationPath=this.config.animationPath.serialize()}}j("FGPlayAnimationBlock",LY);class BY extends ka{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",qe)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}j("FGStopAnimationBlock",BY);class VY extends ka{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",qe)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}j("FGPauseAnimationBlock",VY);class UY extends ac{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nr),this.trueValue=this.registerDataInput("trueValue",qe),this.falseValue=this.registerDataInput("falseValue",qe),this.output=this.registerDataOutput("output",qe)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}j("FGConditionalDataBlock",UY);class Yd extends ac{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,qe)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Yd.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Yd.ClassName="FGGetVariableBlock";j(Yd.ClassName,Yd);class kY extends ac{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",qe),this.destinationSystem=this.registerDataInput("destinationSystem",qe),this.inputCoordinates=this.registerDataInput("inputCoordinates",Pl),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Pl)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),a=K.Matrix[0].copyFrom(n);a.invert();const l=K.Matrix[1];a.multiplyToRef(r,l);const h=this.outputCoordinates.getValue(e);T.TransformCoordinatesToRef(s,l,h)}getClassName(){return"FGCoordinateTransformBlock"}}j("FGCoordinateTransformBlock",kY);class GY extends ac{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",CY(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=vT){super.serialize(e),t("value",this.config.value,e.config)}}j("FGConstantBlock",GY);class $d extends ac{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",qe),this.templateComponent=new $_(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getProperty(e);this.value.setValue(t,e)}getClassName(){return $d.ClassName}}$d.ClassName="FGGetPropertyBlock";j($d.ClassName,$d);const LC="cachedOperationValue",BC="cachedExecutionId";class qm extends ac{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,BC),i=e._getExecutionVariable(this,LC);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const s=this._doOperation(e);e._setExecutionVariable(this,LC,s),e._setExecutionVariable(this,BC,e.executionId),this.value.setValue(s,e)}}}class Qs extends qm{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 Xi extends qm{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.input=this.registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}}const Mn="FGBitwise",gA="AndBlock",vA="OrBlock",xA="XorBlock",TA="NotBlock",EA="LeftShiftBlock",SA="RightShiftBlock",CA="CountLeadingZerosBlock",bA="CountTrailingZerosBlock";class zY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t&i,`${Mn}${gA}`,e)}}j(`${Mn}${gA}`,zY);class WY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t|i,`${Mn}${vA}`,e)}}j(`${Mn}${vA}`,WY);class HY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t^i,`${Mn}${xA}`,e)}}j(`${Mn}${xA}`,HY);class XY extends Xi{constructor(e){super(zt,zt,t=>~t,`${Mn}${TA}`,e)}}j(`${Mn}${TA}`,XY);class YY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t<t>>i,`${Mn}${SA}`,e)}}j(`${Mn}${SA}`,$Y);class KY extends Xi{constructor(e){super(zt,zt,t=>Math.clz32(t),`${Mn}${CA}`,e)}}j(`${Mn}${CA}`,KY);class qY extends Xi{_ctrz(e){return e>>>=0,e===0?32:(e&=-e,31-Math.clz32(e))}constructor(e){super(zt,zt,t=>this._ctrz(t),`${Mn}${bA}`,e)}}j(`${Mn}${bA}`,qY);const Pu="FGLogic",yA="AndBlock",AA="OrBlock",RA="NotBlock";class jY extends Qs{constructor(e){super(Nr,Nr,Nr,(t,i)=>t&&i,`${Pu}${yA}`,e)}}j(`${Pu}${yA}`,jY);class QY extends Qs{constructor(e){super(Nr,Nr,Nr,(t,i)=>t||i,`${Pu}${AA}`,e)}}j(`${Pu}${AA}`,QY);class ZY extends Xi{constructor(e){super(Nr,Nr,t=>!t,`${Pu}${RA}`,e)}}j(`${Pu}${RA}`,ZY);class fp extends qm{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class TT extends qm{constructor(e,t,i,s,r,n,a){super(s,a),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 Sr(o){return o.getClassName?o.getClassName():""}function pp(o,e){return o==="Vector2"&&e==="Vector2"||o==="Vector3"&&e==="Vector3"||o==="Vector4"&&e==="Vector4"}class hu extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAdd(t,i),hu.ClassName,e)}_polymorphicAdd(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.add(t):e+t}getClassName(){return hu.ClassName}}hu.ClassName="FGAddBlock";j(hu.ClassName,hu);class cu extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAdd(t,i),cu.ClassName,e)}_polymorphicAdd(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.subtract(t):e-t}getClassName(){return cu.ClassName}}cu.ClassName="FGSubBlock";j(cu.ClassName,cu);class Kd extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMultiply(t,i),Kd.ClassName,e)}_polymorphicMultiply(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.multiply(t):e*t}}Kd.ClassName="FGMultiplyBlock";j(Kd.ClassName,Kd);class qd extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicDivide(t,i),qd.ClassName,e)}_polymorphicDivide(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.divide(t):e/t}}qd.ClassName="FGDivideBlock";j(qd.ClassName,qd);class jd extends fp{constructor(e){super(zt,()=>Math.random(),jd.ClassName,e)}}jd.ClassName="FGRandomBlock";j(jd.ClassName,jd);class Qd extends Qs{constructor(e){super(qe,qe,zt,(t,i)=>this._polymorphicDot(t,i),Qd.ClassName,e)}_polymorphicDot(e,t){switch(Sr(e)){case"Vector2":return Re.Dot(e,t);case"Vector3":return T.Dot(e,t);case"Vector4":return Dt.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}Qd.ClassName="FGDotBlock";j(Qd.ClassName,Qd);class Zd extends fp{constructor(e){super(zt,()=>Math.E,Zd.ClassName,e)}}Zd.ClassName="FGEBlock";j(Zd.ClassName,Zd);class Jd extends fp{constructor(e){super(zt,()=>Math.PI,Jd.ClassName,e)}}Jd.ClassName="FGPIBlock";j(Jd.ClassName,Jd);class ef extends fp{constructor(e){super(zt,()=>Number.POSITIVE_INFINITY,ef.ClassName,e)}}ef.ClassName="FGInfBlock";j(ef.ClassName,ef);class tf extends fp{constructor(e){super(zt,()=>Number.NaN,tf.ClassName,e)}}tf.ClassName="FGNaNBlock";j(tf.ClassName,tf);function Rs(o,e){switch(Sr(o)){case"Vector2":return new Re(e(o.x),e(o.y));case"Vector3":return new T(e(o.x),e(o.y),e(o.z));case"Vector4":return new Dt(e(o.x),e(o.y),e(o.z),e(o.w));default:return e(o)}}class sf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAbs(t),sf.ClassName,e)}_polymorphicAbs(e){return Rs(e,Math.abs)}}sf.ClassName="FGAbsBlock";j(sf.ClassName,sf);class rf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSign(t),rf.ClassName,e)}_polymorphicSign(e){return Rs(e,Math.sign)}}rf.ClassName="FGSignBlock";j(rf.ClassName,rf);class nf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTrunc(t),nf.ClassName,e)}_polymorphicTrunc(e){return Rs(e,Math.trunc)}}nf.ClassName="FGTruncBlock";j(nf.ClassName,nf);class af extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicFloor(t),af.ClassName,e)}_polymorphicFloor(e){return Rs(e,Math.floor)}}af.ClassName="FGFloorBlock";j(af.ClassName,af);class of extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCeiling(t),of.ClassName,e)}_polymorphicCeiling(e){return Rs(e,Math.ceil)}}of.ClassName="FGCeilBlock";j(of.ClassName,of);class lf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicFract(t),lf.ClassName,e)}_polymorphicFract(e){return Rs(e,t=>t-Math.floor(t))}}lf.ClassName="FGFractBlock";j(lf.ClassName,lf);class hf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicNeg(t),hf.ClassName,e)}_polymorphicNeg(e){return Rs(e,t=>-t)}}hf.ClassName="FGNegBlock";j(hf.ClassName,hf);function _p(o,e,t){switch(Sr(o)){case"Vector2":return new Re(t(o.x,e.x),t(o.y,e.y));case"Vector3":return new T(t(o.x,e.x),t(o.y,e.y),t(o.z,e.z));case"Vector4":return new Dt(t(o.x,e.x),t(o.y,e.y),t(o.z,e.z),t(o.w,e.w));default:return t(o,e)}}class cf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicRemainder(t,i),cf.ClassName,e)}_polymorphicRemainder(e,t){return _p(e,t,(i,s)=>i%s)}}cf.ClassName="FGRemainderBlock";j(cf.ClassName,cf);class uf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMin(t,i),uf.ClassName,e)}_polymorphicMin(e,t){return _p(e,t,Math.min)}}uf.ClassName="FGMinBlock";j(uf.ClassName,uf);class df extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMax(t,i),df.ClassName,e)}_polymorphicMax(e,t){return _p(e,t,Math.max)}}df.ClassName="FGMaxBlock";j(df.ClassName,df);function IA(o,e,t){return Math.min(Math.max(o,e),t)}function PA(o,e,t,i){switch(Sr(o)){case"Vector2":return new Re(i(o.x,e.x,t.x),i(o.y,e.y,t.y));case"Vector3":return new T(i(o.x,e.x,t.x),i(o.y,e.y,t.y),i(o.z,e.z,t.z));case"Vector4":return new Dt(i(o.x,e.x,t.x),i(o.y,e.y,t.y),i(o.z,e.z,t.z),i(o.w,e.w,t.w));default:return i(o,e,t)}}class ff extends TT{constructor(e){super(qe,qe,qe,qe,(t,i,s)=>this._polymorphicClamp(t,i,s),ff.ClassName,e)}_polymorphicClamp(e,t,i){return PA(e,t,i,IA)}}ff.ClassName="FGClampBlock";j(ff.ClassName,ff);class pf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSaturate(t),pf.ClassName,e)}_polymorphicSaturate(e){return Rs(e,t=>IA(t,0,1))}}pf.ClassName="FGSaturateBlock";j(pf.ClassName,pf);class _f extends TT{constructor(e){super(qe,qe,qe,qe,(t,i,s)=>this._polymorphicInterpolate(t,i,s),_f.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return PA(e,t,i,this._interpolate)}}_f.ClassName="FGInterpolateBlock";j(_f.ClassName,_f);class mf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicEq(t,i),mf.ClassName,e)}_polymorphicEq(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.equals(t):e===t}}mf.ClassName="FGEqBlock";j(mf.ClassName,mf);class gf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicLessThan(t,i),gf.ClassName,e)}_polymorphicLessThan(e,t){switch(Sr(e)){case"Vector2":return e.xthis._polymorphicLessThanOrEqual(t,i),ET.ClassName,e)}_polymorphicLessThanOrEqual(e,t){switch(Sr(e)){case"Vector2":return e.x<=t.x&&e.y<=t.y;case"Vector3":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z;case"Vector4":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z&&e.w<=t.w;default:return e<=t}}}ET.ClassName="FGLessThanOrEqualBlock";class vf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicGreaterThan(t,i),vf.ClassName,e)}_polymorphicGreaterThan(e,t){switch(Sr(e)){case"Vector2":return e.x>t.x&&e.y>t.y;case"Vector3":return e.x>t.x&&e.y>t.y&&e.z>t.z;case"Vector4":return e.x>t.x&&e.y>t.y&&e.z>t.z&&e.w>t.w;default:return e>t}}}vf.ClassName="FGGreaterThanBlock";j(vf.ClassName,vf);class xf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),xf.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){switch(Sr(e)){case"Vector2":return e.x>=t.x&&e.y>=t.y;case"Vector3":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z;case"Vector4":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z&&e.w>=t.w;default:return e>=t}}}xf.ClassName="FGGreaterThanOrEqualBlock";j(xf.ClassName,xf);class Tf extends Xi{constructor(e){super(qe,Nr,t=>this._polymorphicIsNan(t),Tf.ClassName,e)}_polymorphicIsNan(e){switch(Sr(e)){case"Vector2":return isNaN(e.x)||isNaN(e.y);case"Vector3":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z);case"Vector4":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z)||isNaN(e.w);default:return isNaN(e)}}}Tf.ClassName="FGIsNanBlock";j(Tf.ClassName,Tf);class ST extends Xi{constructor(e){super(qe,Nr,t=>this._polymorphicIsInf(t),ST.ClassName,e)}_polymorphicIsInf(e){switch(Sr(e)){case"Vector2":return!isFinite(e.x)||!isFinite(e.y);case"Vector3":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z);case"Vector4":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z)||!isFinite(e.w);default:return!isFinite(e)}}}ST.ClassName="FGIsInfBlock";class Ef extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicDegToRad(t),Ef.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Rs(e,this._degToRad)}}Ef.ClassName="FGDegToRadBlock";j(Ef.ClassName,Ef);class Sf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicRadToDeg(t),Sf.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return Rs(e,this._radToDeg)}}Sf.ClassName="FGRadToDegBlock";j(Sf.ClassName,Sf);class Cf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSin(t),Cf.ClassName,e)}_polymorphicSin(e){return Rs(e,Math.sin)}}Cf.ClassName="FGSinBlock";j(Cf.ClassName,Cf);class bf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCos(t),bf.ClassName,e)}_polymorphicCos(e){return Rs(e,Math.cos)}}bf.ClassName="FGCosBlock";j(bf.ClassName,bf);class yf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTan(t),yf.ClassName,e)}_polymorphicTan(e){return Rs(e,Math.tan)}}yf.ClassName="FGTanBlock";j(yf.ClassName,yf);class Af extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAsin(t),Af.ClassName,e)}_polymorphicAsin(e){return Rs(e,Math.asin)}}Af.ClassName="FGAsinBlock";j(Af.ClassName,Af);class Rf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAcos(t),Rf.ClassName,e)}_polymorphicAcos(e){return Rs(e,Math.acos)}}Rf.ClassName="FGAcosBlock";j(Rf.ClassName,Rf);class If extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAtan(t),If.ClassName,e)}_polymorphicAtan(e){return Rs(e,Math.atan)}}If.ClassName="FGAtanBlock";j(If.ClassName,If);class Pf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAtan2(t,i),Pf.ClassName,e)}_polymorphicAtan2(e,t){return _p(e,t,Math.atan2)}}Pf.ClassName="FGAtan2Block";j(Pf.ClassName,Pf);class Mf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSinh(t),Mf.ClassName,e)}_polymorphicSinh(e){return Rs(e,Math.sinh)}}Mf.ClassName="FGSinhBlock";j(Mf.ClassName,Mf);class Df extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCosh(t),Df.ClassName,e)}_polymorphicCosh(e){return Rs(e,Math.cosh)}}Df.ClassName="FGCoshBlock";j(Df.ClassName,Df);class Of extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTanh(t),Of.ClassName,e)}_polymorphicTanh(e){return Rs(e,Math.tanh)}}Of.ClassName="FGTanhBlock";j(Of.ClassName,Of);class Nf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAsinh(t),Nf.ClassName,e)}_polymorphicAsinh(e){return Rs(e,Math.asinh)}}Nf.ClassName="FGAsinhBlock";j(Nf.ClassName,Nf);class wf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAcosh(t),wf.ClassName,e)}_polymorphicAcosh(e){return Rs(e,Math.acosh)}}wf.ClassName="FGAcoshBlock";j(wf.ClassName,wf);class Ff extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAtanh(t),Ff.ClassName,e)}_polymorphicAtanh(e){return Rs(e,Math.atanh)}}Ff.ClassName="FGAtanhBlock";j(Ff.ClassName,Ff);class Lf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicExp(t),Lf.ClassName,e)}_polymorphicExp(e){return Rs(e,Math.exp)}}Lf.ClassName="FGExpBlock";j(Lf.ClassName,Lf);class Bf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog(t),Bf.ClassName,e)}_polymorphicLog(e){return Rs(e,Math.log)}}Bf.ClassName="FGLogBlock";j(Bf.ClassName,Bf);class Vf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog2(t),Vf.ClassName,e)}_polymorphicLog2(e){return Rs(e,Math.log2)}}Vf.ClassName="FGLog2Block";j(Vf.ClassName,Vf);class Uf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog10(t),Uf.ClassName,e)}_polymorphicLog10(e){return Rs(e,Math.log10)}}Uf.ClassName="FGLog10Block";j(Uf.ClassName,Uf);class kf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicSqrt(t),kf.ClassName,e)}_polymorphicSqrt(e){return Rs(e,Math.sqrt)}}kf.ClassName="FGSqrtBlock";j(kf.ClassName,kf);class Gf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicCubeRoot(t),Gf.ClassName,e)}_polymorphicCubeRoot(e){return Rs(e,Math.cbrt)}}Gf.ClassName="FGCubeRootBlock";j(Gf.ClassName,Gf);class zf extends Qs{constructor(e){super(qe,zt,zt,(t,i)=>this._polymorphicPow(t,i),zf.ClassName,e)}_polymorphicPow(e,t){return _p(e,t,Math.pow)}}zf.ClassName="FGPowBlock";j(zf.ClassName,zf);class Wf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLength(t),Wf.ClassName,e)}_polymorphicLength(e){switch(Sr(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Wf.ClassName="FGLengthBlock";j(Wf.ClassName,Wf);class Hf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicNormalize(t),Hf.ClassName,e)}_polymorphicNormalize(e){switch(Sr(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Hf.ClassName="FGNormalizeBlock";j(Hf.ClassName,Hf);class Xf extends Qs{constructor(e){super(Pl,Pl,Pl,(t,i)=>T.Cross(t,i),Xf.ClassName,e)}}Xf.ClassName="FGCrossBlock";j(Xf.ClassName,Xf);class Yf extends Qs{constructor(e){super(Qv,zt,Qv,(t,i)=>Re.Transform(t,k.RotationZ(i)),Yf.ClassName,e)}}Yf.ClassName="FGRotate2DBlock";j(Yf.ClassName,Yf);class $f extends TT{constructor(e){super(Pl,Pl,zt,Pl,(t,i,s)=>T.TransformCoordinates(t,k.RotationAxis(i,s)),$f.ClassName,e)}}$f.ClassName="FGRotate3DBlock";j($f.ClassName,$f);class jm extends Xm{_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 jm.ClassName}}jm.ClassName="FGSceneReadyEventBlock";j("FGSceneReadyEventBlock",jm);class Kf extends Xm{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;e{for(let s=0;s{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 qf.ClassName}}qf.ClassName="FGSceneTickEventBlock";j(qf.ClassName,qf);var K_={exports:{}};/** +}`;ne.ShadersStore[uY]=dY;class fY extends ms{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=[k.Identity(),k.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 wa("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 pY{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},a=new fY(s,r,this._scene,n),l=a.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,a.disableRescaling(),a.renderListPredicate=()=>!0,a}_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 Td extends Cr{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[oi.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 pY(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)}}Td.Name=oi.SPACE_WARP;Td.Version=1;_s.AddWebXRFeature(Td.Name,o=>()=>new Td(o),Td.Version,!1);class Ed extends Cr{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new he,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,a=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:a,ay:l,gamma:h,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var i,s;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const r=(i=this._glBinding)===null||i===void 0?void 0:i.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(s=this._cachedInternalTextures[t]._hardwareTexture)===null||s===void 0||s.set(r);else{const n=new Ti(this._xrSessionManager.scene.getEngine(),Ut.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 uu(r,this._glContext),this._cachedInternalTextures[t]=n;const a=new Ei(this._xrSessionManager.scene);a.name=`WebXR Raw Camera Access (${t})`,a._texture=this._cachedInternalTextures[t],this.texturesData[t]=a,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)}}Ed.Name=oi.RAW_CAMERA_ACCESS;Ed.Version=1;_s.AddWebXRFeature(Ed.Name,(o,e)=>()=>new Ed(o,e),Ed.Version,!1);class _Y extends Tu{constructor(e,t,i){super(e,mY[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(){}}vr.RegisterController("generic-hand-select-grasp",(o,e)=>new _Y(e,o.gamepad,o.handedness));const mY={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 hh extends Tu{constructor(e,t,i){super(e,gY["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=hh.MODEL_LEFT_FILENAME:e=hh.MODEL_RIGHT_FILENAME;const t="default",i=hh.MODEL_BASE_URL+t+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=Lt.IsPluginForExtensionAvailable(".glb");return e||G.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){G.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){G.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 a=this.getComponent(t);a&&a.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else G.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){G.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(a=>{const l=s==="x-axis"?a.x:a.y;this._lerpTransform(r,l,!0)},void 0,!0):G.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new se(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew hh(e,o.gamepad,o.handedness));const gY={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 So extends Tu{constructor(e,t,i,s=!1,r=!1){super(e,vY[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=So.MODEL_LEFT_FILENAME:e=So.MODEL_RIGHT_FILENAME;const t=this._isQuest()?So.QUEST_MODEL_BASE_URL:So.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 se(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Se.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}}So.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";So.MODEL_LEFT_FILENAME="left.babylon";So.MODEL_RIGHT_FILENAME="right.babylon";So.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";vr.RegisterController("oculus-touch",(o,e)=>new So(e,o.gamepad,o.handedness));vr.RegisterController("oculus-touch-legacy",(o,e)=>new So(e,o.gamepad,o.handedness,!0));const vY={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 lu extends Tu{constructor(e,t,i){super(e,xY[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=lu.MODEL_FILENAME,t=lu.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 se(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=Se.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}lu.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";lu.MODEL_FILENAME="wand.babylon";vr.RegisterController("htc-vive",(o,e)=>new lu(e,o.gamepad,o.handedness));const xY={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 TY{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(8),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=()=>{var t;return(t=this._nativeImpl._imageTrackingResults)!==null&&t!==void 0?t:[]}}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")}}b2("NativeXRFrame",TY);var Zo;(function(o){o[o.Input=0]="Input",o[o.Output=1]="Output"})(Zo||(Zo={}));class Qv{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=du(),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=fe.Instantiate(e.className),s=new i(e.name,e._connectionType,t);return s.deserialize(e),s}}class ua{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new ua(e.typeName,e.defaultValue)}}const qe=new ua("any",void 0),EY=new ua("string",""),zt=new ua("number",0),Nr=new ua("boolean",!1),Zv=new ua("Vector2",Re.Zero()),Pl=new ua("Vector3",T.Zero()),SY=new ua("Vector4",Dt.Zero());new ua("Matrix",k.Identity());const CY=new ua("Color3",Te.Black()),bY=new ua("Color4",new Ze(0,0,0,0)),yY=new ua("Quaternion",Se.Identity());function AY(o){switch(typeof o){case"string":return EY;case"number":return zt;case"boolean":return Nr;case"object":return o instanceof Re?Zv:o instanceof T?Pl:o instanceof Dt?SY:o instanceof Te?CY:o instanceof Ze?bY:o instanceof Se?yY:qe;default:return qe}}class Jv extends Qv{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===Zo.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===Zo.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=Qv.Parse(e,t);return i.richType=ua.Parse(e.richType),i}}j("FGDataConnection",Jv);const RY=/([./])({?\w+}?)/g;class Co{constructor(e){this._templateSubstitutions={},this._pathParts=[],this._templateStrings=[],this.hasTemplateStrings=!1,this._path=e;const{pathParts:t,templateStrings:i}=this._getPathPartsAndTemplateStrings(e);this._pathParts=t,this._templateStrings=i,this.hasTemplateStrings=i.length>0}_getPathPartsAndTemplateStrings(e){const t=e.matchAll(RY),i=[],s=[];let r=t.next();for(;!r.done;){const n=r.value,[,a,l]=n;let h=l,c=!1;l.startsWith("{")&&l.endsWith("}")&&(c=!0,h=l.slice(1,l.length-1),s.indexOf(h)===-1&&s.push(h)),i.push({value:l,isTemplate:c,valueWithoutBraces:h,separator:a}),r=t.next()}return{pathParts:i,templateStrings:s}}getTemplateStrings(){return this._templateStrings}setTemplateSubstitution(e,t){if(this._templateStrings.indexOf(e)===-1)throw new Error(`Template string ${e} does not exist in path ${this._path}`);this._templateSubstitutions[e]=t}_evaluateTemplates(){for(const e of this._pathParts)if(e.isTemplate){const t=this._templateSubstitutions[e.valueWithoutBraces];if(t===void 0)throw new Error(`Template string ${e.value} was not substituted`);e.replacedValue=t.toString()}}getFinalPath(){let e="";for(const t of this._pathParts)e+=t.separator,t.isTemplate?e+=t.replacedValue:e+=t.value;return e}_evaluatePath(e){this._evaluateTemplates();const t=[],i=[];let s=e.userVariables;for(const r of this._pathParts){if(s===void 0)throw new Error(`Could not find path ${this.getFinalPath()} in target context`);const n=r.isTemplate?r.replacedValue:r.value;if(!n)throw new Error(`Invalid path ${this.getFinalPath()}`);s=s[n],t.push(s),i.push(n)}return{entityChain:t,splitPath:i}}getProperty(e){for(const i of Co.Extensions)if(i.shouldProcess(this))return i.processGet(this,e);const{entityChain:t}=this._evaluatePath(e);return t[t.length-1]}setProperty(e,t){for(const a of Co.Extensions)if(a.shouldProcess(this)){a.processSet(this,e,t);return}const{entityChain:i,splitPath:s}=this._evaluatePath(e),r=i[i.length-2],n=s[s.length-1];r[n]=t}getClassName(){return Co.ClassName}serialize(e={}){return e.path=this._path,e.className=this.getClassName(),e}static Parse(e){return new Co(e.path)}}Co.Extensions=[];Co.ClassName="FGPath";j(Co.ClassName,Co);function mA(o){return o==="Mesh"||o==="AbstractMesh"||o==="GroundMesh"||o==="InstanceMesh"||o==="LinesMesh"||o==="GoldbergMesh"||o==="GreasedLineMesh"||o==="TrailMesh"}function gA(o){return o==="Vector2"||o==="Vector3"||o==="Vector4"||o==="Quaternion"||o==="Color3"||o==="Color4"}function IY(o,e){if(o==="Vector2")return Re.FromArray(e);if(o==="Vector3")return T.FromArray(e);if(o==="Vector4")return Dt.FromArray(e);if(o==="Quaternion")return Se.FromArray(e);if(o==="Color3")return new Te(e[0],e[1],e[2]);if(o==="Color4")return new Ze(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${o}`)}function TT(o,e,t){var i,s;const r=(s=(i=e==null?void 0:e.getClassName)===null||i===void 0?void 0:i.call(e))!==null&&s!==void 0?s:"";mA(r)?t[o]={name:e.name,className:r}:gA(r)?t[o]={value:e.asArray(),className:r}:t[o]=e}function vA(o,e,t){const i=e[o];let s;const r=i==null?void 0:i.className;return mA(r)?s=t.getMeshByName(i.name):gA(r)?s=IY(r,i.value):r===Co.ClassName?s=Co.Parse(i):i&&i.value!==void 0?s=i.value:s=i,s}class oc{constructor(e){this.config=e,this.uniqueId=du(),this.configure()}configure(){var e,t;this.name=(t=(e=this.config)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Jv(e,Zo.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Jv(e,Zo.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=TT){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,i=vA){const s=fe.Instantiate(e.className),r={};if(e.config)for(const a in e.config)r[a]=i(a,e.config,t);const n=new s(r);n.uniqueId=e.uniqueId;for(let a=0;at.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{var n,a,l;r.type===rt.POINTERPICK&&(!((n=r.pickInfo)===null||n===void 0)&&n.pickedMesh)&&(((a=r.pickInfo)===null||a===void 0?void 0:a.pickedMesh)===i||xA((l=r.pickInfo)===null||l===void 0?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 kd.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path.serialize()}}kd.ClassName="FGMeshPickEventBlock";j(kd.ClassName,kd);var BC;(function(o){o[o.Stopped=0]="Stopped",o[o.Started=1]="Started"})(BC||(BC={}));class ka extends lc{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Gd extends ka{constructor(e){super(e),this.message=this.registerDataInput("message",qe)}_execute(e){const t=this.message.getValue(e);G.Log(t),this.out._activateSignal(e)}getClassName(){return Gd.ClassName}}Gd.ClassName="FGConsoleLogBlock";j(Gd.ClassName,Gd);class zd extends ka{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,qe)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return zd.ClassName}}zd.ClassName="FGSetVariableBlock";j(zd.ClassName,zd);class $_{constructor(e,t){this.templateStringInputs=[],this.path=e,this.ownerBlock=t;for(const i of e.getTemplateStrings())this.templateStringInputs.push(this.ownerBlock.registerDataInput(i,zt))}substitutePath(e){for(const t of this.templateStringInputs){const i=t.getValue(e),s=t.name;this.path.setTemplateSubstitution(s,i)}return this.path}getProperty(e){return this.substitutePath(e),this.path.getProperty(e)}setProperty(e,t){this.substitutePath(e),this.path.setProperty(e,t)}}class Ym extends ka{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",qe),this.templateComponent=new $_(e.path,this)}_execute(e){const t=this.a.getValue(e);this.templateComponent.setProperty(e,t),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path.serialize()}getClassName(){return Ym.ClassName}}Ym.ClassName="FGSetPropertyBlock";j("FGSetPropertyBlock",Ym);class $m extends ka{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;es.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return $m.ClassName}}$m.ClassName="FGSendCustomEventBlock";j("FGSendCustomEventBlock",$m);class MY extends lc{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nr),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"}}j("FGBranchBlock",MY);class Wd extends ka{constructor(e={startIndex:0}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",zt),this.value=this.registerDataOutput("value",zt)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);is)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"}}j("FGThrottleBlock",OY);class Km extends ET{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 Ck({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):fe.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 Km.ClassName}}Km.ClassName="FGTimerBlock";j("FGTimerBlock",Km);class NY extends lc{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",zt)}configure(){super.configure(),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 e=0;e=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter(a=>a!==n),r.length===0)for(let a=0;a=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=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}j("FGDebounceBlock",BY);class VY extends lc{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Nr)}_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"}}j("FGFlipFlopBlock",VY);class Xd extends lc{constructor(e){super(e),this.config=e}configure(){super.configure(),this.outFlows=[];for(let e=0;ethis._onAnimationEnd(l,e));this.runningAnimatable.setValue(l,e),r.push(l)}e._setExecutionVariable(this,"runningAnimatables",r)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){var i;const s=(i=t._getExecutionVariable(this,"runningAnimatables"))!==null&&i!==void 0?i:[],r=s.indexOf(e);r!==-1&&s.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){var t;const i=(t=e._getExecutionVariable(this,"runningAnimatables"))!==null&&t!==void 0?t:[];for(const s of i)s.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath.serialize(),e.config.animationPath=this.config.animationPath.serialize()}}j("FGPlayAnimationBlock",UY);class kY extends ka{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",qe)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}j("FGStopAnimationBlock",kY);class GY extends ka{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",qe)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}j("FGPauseAnimationBlock",GY);class zY extends oc{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nr),this.trueValue=this.registerDataInput("trueValue",qe),this.falseValue=this.registerDataInput("falseValue",qe),this.output=this.registerDataOutput("output",qe)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}j("FGConditionalDataBlock",zY);class Yd extends oc{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,qe)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Yd.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Yd.ClassName="FGGetVariableBlock";j(Yd.ClassName,Yd);class WY extends oc{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",qe),this.destinationSystem=this.registerDataInput("destinationSystem",qe),this.inputCoordinates=this.registerDataInput("inputCoordinates",Pl),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Pl)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),a=K.Matrix[0].copyFrom(n);a.invert();const l=K.Matrix[1];a.multiplyToRef(r,l);const h=this.outputCoordinates.getValue(e);T.TransformCoordinatesToRef(s,l,h)}getClassName(){return"FGCoordinateTransformBlock"}}j("FGCoordinateTransformBlock",WY);class HY extends oc{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",AY(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=TT){super.serialize(e),t("value",this.config.value,e.config)}}j("FGConstantBlock",HY);class $d extends oc{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",qe),this.templateComponent=new $_(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getProperty(e);this.value.setValue(t,e)}getClassName(){return $d.ClassName}}$d.ClassName="FGGetPropertyBlock";j($d.ClassName,$d);const VC="cachedOperationValue",UC="cachedExecutionId";class qm extends oc{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,UC),i=e._getExecutionVariable(this,VC);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const s=this._doOperation(e);e._setExecutionVariable(this,VC,s),e._setExecutionVariable(this,UC,e.executionId),this.value.setValue(s,e)}}}class Qs extends qm{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 Xi extends qm{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.input=this.registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}}const Mn="FGBitwise",TA="AndBlock",EA="OrBlock",SA="XorBlock",CA="NotBlock",bA="LeftShiftBlock",yA="RightShiftBlock",AA="CountLeadingZerosBlock",RA="CountTrailingZerosBlock";class XY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t&i,`${Mn}${TA}`,e)}}j(`${Mn}${TA}`,XY);class YY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t|i,`${Mn}${EA}`,e)}}j(`${Mn}${EA}`,YY);class $Y extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t^i,`${Mn}${SA}`,e)}}j(`${Mn}${SA}`,$Y);class KY extends Xi{constructor(e){super(zt,zt,t=>~t,`${Mn}${CA}`,e)}}j(`${Mn}${CA}`,KY);class qY extends Qs{constructor(e){super(zt,zt,zt,(t,i)=>t<t>>i,`${Mn}${yA}`,e)}}j(`${Mn}${yA}`,jY);class QY extends Xi{constructor(e){super(zt,zt,t=>Math.clz32(t),`${Mn}${AA}`,e)}}j(`${Mn}${AA}`,QY);class ZY extends Xi{_ctrz(e){return e>>>=0,e===0?32:(e&=-e,31-Math.clz32(e))}constructor(e){super(zt,zt,t=>this._ctrz(t),`${Mn}${RA}`,e)}}j(`${Mn}${RA}`,ZY);const Pu="FGLogic",IA="AndBlock",PA="OrBlock",MA="NotBlock";class JY extends Qs{constructor(e){super(Nr,Nr,Nr,(t,i)=>t&&i,`${Pu}${IA}`,e)}}j(`${Pu}${IA}`,JY);class e6 extends Qs{constructor(e){super(Nr,Nr,Nr,(t,i)=>t||i,`${Pu}${PA}`,e)}}j(`${Pu}${PA}`,e6);class t6 extends Xi{constructor(e){super(Nr,Nr,t=>!t,`${Pu}${MA}`,e)}}j(`${Pu}${MA}`,t6);class fp extends qm{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class ST extends qm{constructor(e,t,i,s,r,n,a){super(s,a),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 Sr(o){return o.getClassName?o.getClassName():""}function pp(o,e){return o==="Vector2"&&e==="Vector2"||o==="Vector3"&&e==="Vector3"||o==="Vector4"&&e==="Vector4"}class hu extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAdd(t,i),hu.ClassName,e)}_polymorphicAdd(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.add(t):e+t}getClassName(){return hu.ClassName}}hu.ClassName="FGAddBlock";j(hu.ClassName,hu);class cu extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAdd(t,i),cu.ClassName,e)}_polymorphicAdd(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.subtract(t):e-t}getClassName(){return cu.ClassName}}cu.ClassName="FGSubBlock";j(cu.ClassName,cu);class Kd extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMultiply(t,i),Kd.ClassName,e)}_polymorphicMultiply(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.multiply(t):e*t}}Kd.ClassName="FGMultiplyBlock";j(Kd.ClassName,Kd);class qd extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicDivide(t,i),qd.ClassName,e)}_polymorphicDivide(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.divide(t):e/t}}qd.ClassName="FGDivideBlock";j(qd.ClassName,qd);class jd extends fp{constructor(e){super(zt,()=>Math.random(),jd.ClassName,e)}}jd.ClassName="FGRandomBlock";j(jd.ClassName,jd);class Qd extends Qs{constructor(e){super(qe,qe,zt,(t,i)=>this._polymorphicDot(t,i),Qd.ClassName,e)}_polymorphicDot(e,t){switch(Sr(e)){case"Vector2":return Re.Dot(e,t);case"Vector3":return T.Dot(e,t);case"Vector4":return Dt.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}Qd.ClassName="FGDotBlock";j(Qd.ClassName,Qd);class Zd extends fp{constructor(e){super(zt,()=>Math.E,Zd.ClassName,e)}}Zd.ClassName="FGEBlock";j(Zd.ClassName,Zd);class Jd extends fp{constructor(e){super(zt,()=>Math.PI,Jd.ClassName,e)}}Jd.ClassName="FGPIBlock";j(Jd.ClassName,Jd);class ef extends fp{constructor(e){super(zt,()=>Number.POSITIVE_INFINITY,ef.ClassName,e)}}ef.ClassName="FGInfBlock";j(ef.ClassName,ef);class tf extends fp{constructor(e){super(zt,()=>Number.NaN,tf.ClassName,e)}}tf.ClassName="FGNaNBlock";j(tf.ClassName,tf);function Rs(o,e){switch(Sr(o)){case"Vector2":return new Re(e(o.x),e(o.y));case"Vector3":return new T(e(o.x),e(o.y),e(o.z));case"Vector4":return new Dt(e(o.x),e(o.y),e(o.z),e(o.w));default:return e(o)}}class sf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAbs(t),sf.ClassName,e)}_polymorphicAbs(e){return Rs(e,Math.abs)}}sf.ClassName="FGAbsBlock";j(sf.ClassName,sf);class rf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSign(t),rf.ClassName,e)}_polymorphicSign(e){return Rs(e,Math.sign)}}rf.ClassName="FGSignBlock";j(rf.ClassName,rf);class nf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTrunc(t),nf.ClassName,e)}_polymorphicTrunc(e){return Rs(e,Math.trunc)}}nf.ClassName="FGTruncBlock";j(nf.ClassName,nf);class af extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicFloor(t),af.ClassName,e)}_polymorphicFloor(e){return Rs(e,Math.floor)}}af.ClassName="FGFloorBlock";j(af.ClassName,af);class of extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCeiling(t),of.ClassName,e)}_polymorphicCeiling(e){return Rs(e,Math.ceil)}}of.ClassName="FGCeilBlock";j(of.ClassName,of);class lf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicFract(t),lf.ClassName,e)}_polymorphicFract(e){return Rs(e,t=>t-Math.floor(t))}}lf.ClassName="FGFractBlock";j(lf.ClassName,lf);class hf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicNeg(t),hf.ClassName,e)}_polymorphicNeg(e){return Rs(e,t=>-t)}}hf.ClassName="FGNegBlock";j(hf.ClassName,hf);function _p(o,e,t){switch(Sr(o)){case"Vector2":return new Re(t(o.x,e.x),t(o.y,e.y));case"Vector3":return new T(t(o.x,e.x),t(o.y,e.y),t(o.z,e.z));case"Vector4":return new Dt(t(o.x,e.x),t(o.y,e.y),t(o.z,e.z),t(o.w,e.w));default:return t(o,e)}}class cf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicRemainder(t,i),cf.ClassName,e)}_polymorphicRemainder(e,t){return _p(e,t,(i,s)=>i%s)}}cf.ClassName="FGRemainderBlock";j(cf.ClassName,cf);class uf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMin(t,i),uf.ClassName,e)}_polymorphicMin(e,t){return _p(e,t,Math.min)}}uf.ClassName="FGMinBlock";j(uf.ClassName,uf);class df extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicMax(t,i),df.ClassName,e)}_polymorphicMax(e,t){return _p(e,t,Math.max)}}df.ClassName="FGMaxBlock";j(df.ClassName,df);function DA(o,e,t){return Math.min(Math.max(o,e),t)}function OA(o,e,t,i){switch(Sr(o)){case"Vector2":return new Re(i(o.x,e.x,t.x),i(o.y,e.y,t.y));case"Vector3":return new T(i(o.x,e.x,t.x),i(o.y,e.y,t.y),i(o.z,e.z,t.z));case"Vector4":return new Dt(i(o.x,e.x,t.x),i(o.y,e.y,t.y),i(o.z,e.z,t.z),i(o.w,e.w,t.w));default:return i(o,e,t)}}class ff extends ST{constructor(e){super(qe,qe,qe,qe,(t,i,s)=>this._polymorphicClamp(t,i,s),ff.ClassName,e)}_polymorphicClamp(e,t,i){return OA(e,t,i,DA)}}ff.ClassName="FGClampBlock";j(ff.ClassName,ff);class pf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSaturate(t),pf.ClassName,e)}_polymorphicSaturate(e){return Rs(e,t=>DA(t,0,1))}}pf.ClassName="FGSaturateBlock";j(pf.ClassName,pf);class _f extends ST{constructor(e){super(qe,qe,qe,qe,(t,i,s)=>this._polymorphicInterpolate(t,i,s),_f.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return OA(e,t,i,this._interpolate)}}_f.ClassName="FGInterpolateBlock";j(_f.ClassName,_f);class mf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicEq(t,i),mf.ClassName,e)}_polymorphicEq(e,t){const i=Sr(e),s=Sr(t);return pp(i,s)?e.equals(t):e===t}}mf.ClassName="FGEqBlock";j(mf.ClassName,mf);class gf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicLessThan(t,i),gf.ClassName,e)}_polymorphicLessThan(e,t){switch(Sr(e)){case"Vector2":return e.xthis._polymorphicLessThanOrEqual(t,i),CT.ClassName,e)}_polymorphicLessThanOrEqual(e,t){switch(Sr(e)){case"Vector2":return e.x<=t.x&&e.y<=t.y;case"Vector3":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z;case"Vector4":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z&&e.w<=t.w;default:return e<=t}}}CT.ClassName="FGLessThanOrEqualBlock";class vf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicGreaterThan(t,i),vf.ClassName,e)}_polymorphicGreaterThan(e,t){switch(Sr(e)){case"Vector2":return e.x>t.x&&e.y>t.y;case"Vector3":return e.x>t.x&&e.y>t.y&&e.z>t.z;case"Vector4":return e.x>t.x&&e.y>t.y&&e.z>t.z&&e.w>t.w;default:return e>t}}}vf.ClassName="FGGreaterThanBlock";j(vf.ClassName,vf);class xf extends Qs{constructor(e){super(qe,qe,Nr,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),xf.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){switch(Sr(e)){case"Vector2":return e.x>=t.x&&e.y>=t.y;case"Vector3":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z;case"Vector4":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z&&e.w>=t.w;default:return e>=t}}}xf.ClassName="FGGreaterThanOrEqualBlock";j(xf.ClassName,xf);class Tf extends Xi{constructor(e){super(qe,Nr,t=>this._polymorphicIsNan(t),Tf.ClassName,e)}_polymorphicIsNan(e){switch(Sr(e)){case"Vector2":return isNaN(e.x)||isNaN(e.y);case"Vector3":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z);case"Vector4":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z)||isNaN(e.w);default:return isNaN(e)}}}Tf.ClassName="FGIsNanBlock";j(Tf.ClassName,Tf);class bT extends Xi{constructor(e){super(qe,Nr,t=>this._polymorphicIsInf(t),bT.ClassName,e)}_polymorphicIsInf(e){switch(Sr(e)){case"Vector2":return!isFinite(e.x)||!isFinite(e.y);case"Vector3":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z);case"Vector4":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z)||!isFinite(e.w);default:return!isFinite(e)}}}bT.ClassName="FGIsInfBlock";class Ef extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicDegToRad(t),Ef.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Rs(e,this._degToRad)}}Ef.ClassName="FGDegToRadBlock";j(Ef.ClassName,Ef);class Sf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicRadToDeg(t),Sf.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return Rs(e,this._radToDeg)}}Sf.ClassName="FGRadToDegBlock";j(Sf.ClassName,Sf);class Cf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSin(t),Cf.ClassName,e)}_polymorphicSin(e){return Rs(e,Math.sin)}}Cf.ClassName="FGSinBlock";j(Cf.ClassName,Cf);class bf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCos(t),bf.ClassName,e)}_polymorphicCos(e){return Rs(e,Math.cos)}}bf.ClassName="FGCosBlock";j(bf.ClassName,bf);class yf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTan(t),yf.ClassName,e)}_polymorphicTan(e){return Rs(e,Math.tan)}}yf.ClassName="FGTanBlock";j(yf.ClassName,yf);class Af extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAsin(t),Af.ClassName,e)}_polymorphicAsin(e){return Rs(e,Math.asin)}}Af.ClassName="FGAsinBlock";j(Af.ClassName,Af);class Rf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAcos(t),Rf.ClassName,e)}_polymorphicAcos(e){return Rs(e,Math.acos)}}Rf.ClassName="FGAcosBlock";j(Rf.ClassName,Rf);class If extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicAtan(t),If.ClassName,e)}_polymorphicAtan(e){return Rs(e,Math.atan)}}If.ClassName="FGAtanBlock";j(If.ClassName,If);class Pf extends Qs{constructor(e){super(qe,qe,qe,(t,i)=>this._polymorphicAtan2(t,i),Pf.ClassName,e)}_polymorphicAtan2(e,t){return _p(e,t,Math.atan2)}}Pf.ClassName="FGAtan2Block";j(Pf.ClassName,Pf);class Mf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicSinh(t),Mf.ClassName,e)}_polymorphicSinh(e){return Rs(e,Math.sinh)}}Mf.ClassName="FGSinhBlock";j(Mf.ClassName,Mf);class Df extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicCosh(t),Df.ClassName,e)}_polymorphicCosh(e){return Rs(e,Math.cosh)}}Df.ClassName="FGCoshBlock";j(Df.ClassName,Df);class Of extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicTanh(t),Of.ClassName,e)}_polymorphicTanh(e){return Rs(e,Math.tanh)}}Of.ClassName="FGTanhBlock";j(Of.ClassName,Of);class Nf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAsinh(t),Nf.ClassName,e)}_polymorphicAsinh(e){return Rs(e,Math.asinh)}}Nf.ClassName="FGAsinhBlock";j(Nf.ClassName,Nf);class wf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAcosh(t),wf.ClassName,e)}_polymorphicAcosh(e){return Rs(e,Math.acosh)}}wf.ClassName="FGAcoshBlock";j(wf.ClassName,wf);class Ff extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicAtanh(t),Ff.ClassName,e)}_polymorphicAtanh(e){return Rs(e,Math.atanh)}}Ff.ClassName="FGAtanhBlock";j(Ff.ClassName,Ff);class Lf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicExp(t),Lf.ClassName,e)}_polymorphicExp(e){return Rs(e,Math.exp)}}Lf.ClassName="FGExpBlock";j(Lf.ClassName,Lf);class Bf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog(t),Bf.ClassName,e)}_polymorphicLog(e){return Rs(e,Math.log)}}Bf.ClassName="FGLogBlock";j(Bf.ClassName,Bf);class Vf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog2(t),Vf.ClassName,e)}_polymorphicLog2(e){return Rs(e,Math.log2)}}Vf.ClassName="FGLog2Block";j(Vf.ClassName,Vf);class Uf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLog10(t),Uf.ClassName,e)}_polymorphicLog10(e){return Rs(e,Math.log10)}}Uf.ClassName="FGLog10Block";j(Uf.ClassName,Uf);class kf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicSqrt(t),kf.ClassName,e)}_polymorphicSqrt(e){return Rs(e,Math.sqrt)}}kf.ClassName="FGSqrtBlock";j(kf.ClassName,kf);class Gf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicCubeRoot(t),Gf.ClassName,e)}_polymorphicCubeRoot(e){return Rs(e,Math.cbrt)}}Gf.ClassName="FGCubeRootBlock";j(Gf.ClassName,Gf);class zf extends Qs{constructor(e){super(qe,zt,zt,(t,i)=>this._polymorphicPow(t,i),zf.ClassName,e)}_polymorphicPow(e,t){return _p(e,t,Math.pow)}}zf.ClassName="FGPowBlock";j(zf.ClassName,zf);class Wf extends Xi{constructor(e){super(qe,zt,t=>this._polymorphicLength(t),Wf.ClassName,e)}_polymorphicLength(e){switch(Sr(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Wf.ClassName="FGLengthBlock";j(Wf.ClassName,Wf);class Hf extends Xi{constructor(e){super(qe,qe,t=>this._polymorphicNormalize(t),Hf.ClassName,e)}_polymorphicNormalize(e){switch(Sr(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Hf.ClassName="FGNormalizeBlock";j(Hf.ClassName,Hf);class Xf extends Qs{constructor(e){super(Pl,Pl,Pl,(t,i)=>T.Cross(t,i),Xf.ClassName,e)}}Xf.ClassName="FGCrossBlock";j(Xf.ClassName,Xf);class Yf extends Qs{constructor(e){super(Zv,zt,Zv,(t,i)=>Re.Transform(t,k.RotationZ(i)),Yf.ClassName,e)}}Yf.ClassName="FGRotate2DBlock";j(Yf.ClassName,Yf);class $f extends ST{constructor(e){super(Pl,Pl,zt,Pl,(t,i,s)=>T.TransformCoordinates(t,k.RotationAxis(i,s)),$f.ClassName,e)}}$f.ClassName="FGRotate3DBlock";j($f.ClassName,$f);class jm extends Xm{_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 jm.ClassName}}jm.ClassName="FGSceneReadyEventBlock";j("FGSceneReadyEventBlock",jm);class Kf extends Xm{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;e{for(let s=0;s{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 qf.ClassName}}qf.ClassName="FGSceneTickEventBlock";j(qf.ClassName,qf);var K_={exports:{}};/** * @license * Lodash * Copyright OpenJS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */K_.exports;(function(o,e){(function(){var t,i="4.17.21",s=200,r="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",n="Expected a function",a="Invalid `variable` option passed into `_.template`",l="__lodash_hash_undefined__",h=500,c="__lodash_placeholder__",u=1,d=2,f=4,p=1,_=2,g=1,v=2,E=4,C=8,S=16,b=32,R=64,I=128,N=256,O=512,L=30,B="...",V=800,Z=16,ue=1,oe=2,me=3,le=1/0,ae=9007199254740991,ce=17976931348623157e292,ie=NaN,w=4294967295,H=w-1,X=w>>>1,te=[["ary",I],["bind",g],["bindKey",v],["curry",C],["curryRight",S],["flip",O],["partial",b],["partialRight",R],["rearg",N]],Q="[object Arguments]",_e="[object Array]",q="[object AsyncFunction]",de="[object Boolean]",ge="[object Date]",ve="[object DOMException]",be="[object Error]",Le="[object Function]",Ye="[object GeneratorFunction]",He="[object Map]",Be="[object Number]",Ge="[object Null]",Lt="[object Object]",Mt="[object Promise]",Vi="[object Proxy]",at="[object RegExp]",ei="[object Set]",di="[object String]",ci="[object Symbol]",Yi="[object Undefined]",Zt="[object WeakMap]",zi="[object WeakSet]",ti="[object ArrayBuffer]",gs="[object DataView]",br="[object Float32Array]",gn="[object Float64Array]",Yn="[object Int8Array]",Dn="[object Int16Array]",jr="[object Int32Array]",Wr="[object Uint8Array]",$n="[object Uint8ClampedArray]",On="[object Uint16Array]",vn="[object Uint32Array]",Nn=/\b__p \+= '';/g,hn=/\b(__p \+=) '' \+/g,xn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Qr=/&(?:amp|lt|gt|quot|#39);/g,ur=/[&<>"']/g,da=RegExp(Qr.source),wn=RegExp(ur.source),fa=/<%-([\s\S]+?)%>/g,ao=/<%([\s\S]+?)%>/g,pa=/<%=([\s\S]+?)%>/g,Zs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ue=/^\w*$/,ke=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Je=/[\\^$.*+?()[\]{}|]/g,$e=RegExp(Je.source),Wt=/^\s+/,bt=/\s/,pt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Tt=/\{\n\/\* \[wrapped with (.+)\] \*/,Ne=/,? & /,_t=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Et=/[()=,{}\[\]\/\s]/,Nt=/\\(\\)?/g,gt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ct=/\w*$/,vt=/^[-+]0x[0-9a-f]+$/i,Ht=/^0b[01]+$/i,fi=/^\[object .+?Constructor\]$/,st=/^0o[0-7]+$/i,vi=/^(?:0|[1-9]\d*)$/,yi=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Is=/($^)/,Di=/['\n\r\u2028\u2029\\]/g,wi="\\ud800-\\udfff",ii="\\u0300-\\u036f",Kn="\\ufe20-\\ufe2f",qn="\\u20d0-\\u20ff",cn=ii+Kn+qn,Ga="\\u2700-\\u27bf",un="a-z\\xdf-\\xf6\\xf8-\\xff",vs="\\xac\\xb1\\xd7\\xf7",oo="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",Os="\\u2000-\\u206f",lo=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",dn="A-Z\\xc0-\\xd6\\xd8-\\xde",Hr="\\ufe0e\\ufe0f",wr=vs+oo+Os+lo,Tn="['’]",ho="["+wi+"]",li="["+wr+"]",Zr="["+cn+"]",yr="\\d+",rl="["+Ga+"]",Po="["+un+"]",mp="[^"+wi+wr+yr+Ga+un+dn+"]",Mu="\\ud83c[\\udffb-\\udfff]",Ns="(?:"+Zr+"|"+Mu+")",CT="[^"+wi+"]",Qm="(?:\\ud83c[\\udde6-\\uddff]){2}",Zm="[\\ud800-\\udbff][\\udc00-\\udfff]",hc="["+dn+"]",bT="\\u200d",yT="(?:"+Po+"|"+mp+")",NA="(?:"+hc+"|"+mp+")",AT="(?:"+Tn+"(?:d|ll|m|re|s|t|ve))?",RT="(?:"+Tn+"(?:D|LL|M|RE|S|T|VE))?",IT=Ns+"?",PT="["+Hr+"]?",wA="(?:"+bT+"(?:"+[CT,Qm,Zm].join("|")+")"+PT+IT+")*",FA="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",LA="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",MT=PT+IT+wA,BA="(?:"+[rl,Qm,Zm].join("|")+")"+MT,VA="(?:"+[CT+Zr+"?",Zr,Qm,Zm,ho].join("|")+")",UA=RegExp(Tn,"g"),kA=RegExp(Zr,"g"),Jm=RegExp(Mu+"(?="+Mu+")|"+VA+MT,"g"),GA=RegExp([hc+"?"+Po+"+"+AT+"(?="+[li,hc,"$"].join("|")+")",NA+"+"+RT+"(?="+[li,hc+yT,"$"].join("|")+")",hc+"?"+yT+"+"+AT,hc+"+"+RT,LA,FA,yr,BA].join("|"),"g"),zA=RegExp("["+bT+wi+cn+Hr+"]"),WA=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,HA=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],XA=-1,Gs={};Gs[br]=Gs[gn]=Gs[Yn]=Gs[Dn]=Gs[jr]=Gs[Wr]=Gs[$n]=Gs[On]=Gs[vn]=!0,Gs[Q]=Gs[_e]=Gs[ti]=Gs[de]=Gs[gs]=Gs[ge]=Gs[be]=Gs[Le]=Gs[He]=Gs[Be]=Gs[Lt]=Gs[at]=Gs[ei]=Gs[di]=Gs[Zt]=!1;var ws={};ws[Q]=ws[_e]=ws[ti]=ws[gs]=ws[de]=ws[ge]=ws[br]=ws[gn]=ws[Yn]=ws[Dn]=ws[jr]=ws[He]=ws[Be]=ws[Lt]=ws[at]=ws[ei]=ws[di]=ws[ci]=ws[Wr]=ws[$n]=ws[On]=ws[vn]=!0,ws[be]=ws[Le]=ws[Zt]=!1;var YA={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},$A={"&":"&","<":"<",">":">",'"':""","'":"'"},KA={"&":"&","<":"<",">":">",""":'"',"'":"'"},qA={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},jA=parseFloat,QA=parseInt,DT=typeof Yu=="object"&&Yu&&Yu.Object===Object&&Yu,ZA=typeof self=="object"&&self&&self.Object===Object&&self,fn=DT||ZA||Function("return this")(),eg=e&&!e.nodeType&&e,Sh=eg&&!0&&o&&!o.nodeType&&o,OT=Sh&&Sh.exports===eg,tg=OT&&DT.process,za=function(){try{var Ae=Sh&&Sh.require&&Sh.require("util").types;return Ae||tg&&tg.binding&&tg.binding("util")}catch{}}(),NT=za&&za.isArrayBuffer,wT=za&&za.isDate,FT=za&&za.isMap,LT=za&&za.isRegExp,BT=za&&za.isSet,VT=za&&za.isTypedArray;function _a(Ae,ze,Ve){switch(Ve.length){case 0:return Ae.call(ze);case 1:return Ae.call(ze,Ve[0]);case 2:return Ae.call(ze,Ve[0],Ve[1]);case 3:return Ae.call(ze,Ve[0],Ve[1],Ve[2])}return Ae.apply(ze,Ve)}function JA(Ae,ze,Ve,wt){for(var mi=-1,os=Ae==null?0:Ae.length;++mi-1}function ig(Ae,ze,Ve){for(var wt=-1,mi=Ae==null?0:Ae.length;++wt-1;);return Ve}function YT(Ae,ze){for(var Ve=Ae.length;Ve--&&cc(ze,Ae[Ve],0)>-1;);return Ve}function lR(Ae,ze){for(var Ve=Ae.length,wt=0;Ve--;)Ae[Ve]===ze&&++wt;return wt}var hR=ag(YA),cR=ag($A);function uR(Ae){return"\\"+qA[Ae]}function dR(Ae,ze){return Ae==null?t:Ae[ze]}function uc(Ae){return zA.test(Ae)}function fR(Ae){return WA.test(Ae)}function pR(Ae){for(var ze,Ve=[];!(ze=Ae.next()).done;)Ve.push(ze.value);return Ve}function cg(Ae){var ze=-1,Ve=Array(Ae.size);return Ae.forEach(function(wt,mi){Ve[++ze]=[mi,wt]}),Ve}function $T(Ae,ze){return function(Ve){return Ae(ze(Ve))}}function Ll(Ae,ze){for(var Ve=-1,wt=Ae.length,mi=0,os=[];++Ve-1}function tI(m,x){var y=this.__data__,F=wp(y,m);return F<0?(++this.size,y.push([m,x])):y[F][1]=x,this}nl.prototype.clear=QR,nl.prototype.delete=ZR,nl.prototype.get=JR,nl.prototype.has=eI,nl.prototype.set=tI;function al(m){var x=-1,y=m==null?0:m.length;for(this.clear();++x=x?m:x)),m}function Ya(m,x,y,F,z,J){var pe,xe=x&u,Pe=x&d,Ke=x&f;if(y&&(pe=z?y(m,F,z,J):y(m)),pe!==t)return pe;if(!Js(m))return m;var je=xi(m);if(je){if(pe=nP(m),!xe)return jn(m,pe)}else{var tt=Sn(m),At=tt==Le||tt==Ye;if(zl(m))return PE(m,xe);if(tt==Lt||tt==Q||At&&!z){if(pe=Pe||At?{}:KE(m),!xe)return Pe?KI(m,gI(pe,m)):$I(m,nE(pe,m))}else{if(!ws[tt])return z?m:{};pe=aP(m,tt,xe)}}J||(J=new uo);var kt=J.get(m);if(kt)return kt;J.set(m,pe),CS(m)?m.forEach(function(ai){pe.add(Ya(ai,x,y,ai,m,J))}):ES(m)&&m.forEach(function(ai,Ui){pe.set(Ui,Ya(ai,x,y,Ui,m,J))});var ni=Ke?Pe?Lg:Fg:Pe?Zn:Jr,Oi=je?t:ni(m);return Wa(Oi||m,function(ai,Ui){Oi&&(Ui=ai,ai=m[Ui]),Bu(pe,Ui,Ya(ai,x,y,Ui,m,J))}),pe}function vI(m){var x=Jr(m);return function(y){return aE(y,m,x)}}function aE(m,x,y){var F=y.length;if(m==null)return!F;for(m=Ps(m);F--;){var z=y[F],J=x[z],pe=m[z];if(pe===t&&!(z in m)||!J(pe))return!1}return!0}function oE(m,x,y){if(typeof m!="function")throw new Ha(n);return Hu(function(){m.apply(t,y)},x)}function Vu(m,x,y,F){var z=-1,J=gp,pe=!0,xe=m.length,Pe=[],Ke=x.length;if(!xe)return Pe;y&&(x=Ys(x,ma(y))),F?(J=ig,pe=!1):x.length>=s&&(J=Du,pe=!1,x=new yh(x));e:for(;++zz?0:z+y),F=F===t||F>z?z:Ai(F),F<0&&(F+=z),F=y>F?0:yS(F);y0&&y(xe)?x>1?pn(xe,x-1,y,F,z):Fl(z,xe):F||(z[z.length]=xe)}return z}var gg=FE(),cE=FE(!0);function Mo(m,x){return m&&gg(m,x,Jr)}function vg(m,x){return m&&cE(m,x,Jr)}function Lp(m,x){return wl(x,function(y){return ul(m[y])})}function Rh(m,x){x=kl(x,m);for(var y=0,F=x.length;m!=null&&yx}function EI(m,x){return m!=null&&xs.call(m,x)}function SI(m,x){return m!=null&&x in Ps(m)}function CI(m,x,y){return m>=En(x,y)&&m=120&&je.length>=120)?new yh(pe&&je):t}je=m[0];var tt=-1,At=xe[0];e:for(;++tt-1;)xe!==m&&Rp.call(xe,Pe,1),Rp.call(m,Pe,1);return m}function EE(m,x){for(var y=m?x.length:0,F=y-1;y--;){var z=x[y];if(y==F||z!==J){var J=z;cl(z)?Rp.call(m,z,1):Ig(m,z)}}return m}function yg(m,x){return m+Mp(tE()*(x-m+1))}function LI(m,x,y,F){for(var z=-1,J=Yr(Pp((x-m)/(y||1)),0),pe=Ve(J);J--;)pe[F?J:++z]=m,m+=y;return pe}function Ag(m,x){var y="";if(!m||x<1||x>ae)return y;do x%2&&(y+=m),x=Mp(x/2),x&&(m+=m);while(x);return y}function Fi(m,x){return Wg(QE(m,x,Jn),m+"")}function BI(m){return rE(Sc(m))}function VI(m,x){var y=Sc(m);return $p(y,Ah(x,0,y.length))}function Gu(m,x,y,F){if(!Js(m))return m;x=kl(x,m);for(var z=-1,J=x.length,pe=J-1,xe=m;xe!=null&&++zz?0:z+x),y=y>z?z:y,y<0&&(y+=z),z=x>y?0:y-x>>>0,x>>>=0;for(var J=Ve(z);++F>>1,pe=m[J];pe!==null&&!va(pe)&&(y?pe<=x:pe=s){var Ke=x?null:ZI(m);if(Ke)return xp(Ke);pe=!1,z=Du,Pe=new yh}else Pe=x?[]:xe;e:for(;++F=F?m:$a(m,x,y)}var IE=PR||function(m){return fn.clearTimeout(m)};function PE(m,x){if(x)return m.slice();var y=m.length,F=jT?jT(y):new m.constructor(y);return m.copy(F),F}function Og(m){var x=new m.constructor(m.byteLength);return new yp(x).set(new yp(m)),x}function WI(m,x){var y=x?Og(m.buffer):m.buffer;return new m.constructor(y,m.byteOffset,m.byteLength)}function HI(m){var x=new m.constructor(m.source,ct.exec(m));return x.lastIndex=m.lastIndex,x}function XI(m){return Lu?Ps(Lu.call(m)):{}}function ME(m,x){var y=x?Og(m.buffer):m.buffer;return new m.constructor(y,m.byteOffset,m.length)}function DE(m,x){if(m!==x){var y=m!==t,F=m===null,z=m===m,J=va(m),pe=x!==t,xe=x===null,Pe=x===x,Ke=va(x);if(!xe&&!Ke&&!J&&m>x||J&&pe&&Pe&&!xe&&!Ke||F&&pe&&Pe||!y&&Pe||!z)return 1;if(!F&&!J&&!Ke&&m=xe)return Pe;var Ke=y[F];return Pe*(Ke=="desc"?-1:1)}}return m.index-x.index}function OE(m,x,y,F){for(var z=-1,J=m.length,pe=y.length,xe=-1,Pe=x.length,Ke=Yr(J-pe,0),je=Ve(Pe+Ke),tt=!F;++xe1?y[z-1]:t,pe=z>2?y[2]:t;for(J=m.length>3&&typeof J=="function"?(z--,J):t,pe&&Ln(y[0],y[1],pe)&&(J=z<3?t:J,z=1),x=Ps(x);++F-1?z[J?x[pe]:pe]:t}}function VE(m){return hl(function(x){var y=x.length,F=y,z=Xa.prototype.thru;for(m&&x.reverse();F--;){var J=x[F];if(typeof J!="function")throw new Ha(n);if(z&&!pe&&Xp(J)=="wrapper")var pe=new Xa([],!0)}for(F=pe?F:y;++F1&&$i.reverse(),je&&Pexe))return!1;var Ke=J.get(m),je=J.get(x);if(Ke&&je)return Ke==x&&je==m;var tt=-1,At=!0,kt=y&_?new yh:t;for(J.set(m,x),J.set(x,m);++tt1?"& ":"")+x[F],x=x.join(y>2?", ":" "),m.replace(pt,`{ + */K_.exports;(function(o,e){(function(){var t,i="4.17.21",s=200,r="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",n="Expected a function",a="Invalid `variable` option passed into `_.template`",l="__lodash_hash_undefined__",h=500,c="__lodash_placeholder__",u=1,d=2,f=4,p=1,_=2,g=1,v=2,E=4,C=8,S=16,b=32,R=64,I=128,N=256,O=512,L=30,B="...",V=800,Z=16,ue=1,oe=2,me=3,le=1/0,ae=9007199254740991,ce=17976931348623157e292,ie=NaN,w=4294967295,H=w-1,X=w>>>1,te=[["ary",I],["bind",g],["bindKey",v],["curry",C],["curryRight",S],["flip",O],["partial",b],["partialRight",R],["rearg",N]],Q="[object Arguments]",_e="[object Array]",q="[object AsyncFunction]",de="[object Boolean]",ge="[object Date]",ve="[object DOMException]",be="[object Error]",Le="[object Function]",Ye="[object GeneratorFunction]",He="[object Map]",Be="[object Number]",Ge="[object Null]",Bt="[object Object]",Mt="[object Promise]",Vi="[object Proxy]",at="[object RegExp]",ei="[object Set]",di="[object String]",ci="[object Symbol]",Yi="[object Undefined]",Zt="[object WeakMap]",zi="[object WeakSet]",ti="[object ArrayBuffer]",gs="[object DataView]",br="[object Float32Array]",vn="[object Float64Array]",Yn="[object Int8Array]",Dn="[object Int16Array]",jr="[object Int32Array]",Wr="[object Uint8Array]",$n="[object Uint8ClampedArray]",On="[object Uint16Array]",xn="[object Uint32Array]",Nn=/\b__p \+= '';/g,hn=/\b(__p \+=) '' \+/g,Tn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Qr=/&(?:amp|lt|gt|quot|#39);/g,ur=/[&<>"']/g,da=RegExp(Qr.source),wn=RegExp(ur.source),fa=/<%-([\s\S]+?)%>/g,ao=/<%([\s\S]+?)%>/g,pa=/<%=([\s\S]+?)%>/g,Zs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ue=/^\w*$/,ke=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Je=/[\\^$.*+?()[\]{}|]/g,$e=RegExp(Je.source),Wt=/^\s+/,bt=/\s/,pt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Tt=/\{\n\/\* \[wrapped with (.+)\] \*/,Ne=/,? & /,_t=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Et=/[()=,{}\[\]\/\s]/,Nt=/\\(\\)?/g,gt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ct=/\w*$/,vt=/^[-+]0x[0-9a-f]+$/i,Ht=/^0b[01]+$/i,fi=/^\[object .+?Constructor\]$/,st=/^0o[0-7]+$/i,vi=/^(?:0|[1-9]\d*)$/,yi=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Is=/($^)/,Di=/['\n\r\u2028\u2029\\]/g,wi="\\ud800-\\udfff",ii="\\u0300-\\u036f",Kn="\\ufe20-\\ufe2f",qn="\\u20d0-\\u20ff",cn=ii+Kn+qn,Ga="\\u2700-\\u27bf",un="a-z\\xdf-\\xf6\\xf8-\\xff",vs="\\xac\\xb1\\xd7\\xf7",oo="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",Os="\\u2000-\\u206f",lo=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",dn="A-Z\\xc0-\\xd6\\xd8-\\xde",Hr="\\ufe0e\\ufe0f",wr=vs+oo+Os+lo,En="['’]",ho="["+wi+"]",li="["+wr+"]",Zr="["+cn+"]",yr="\\d+",rl="["+Ga+"]",Po="["+un+"]",mp="[^"+wi+wr+yr+Ga+un+dn+"]",Mu="\\ud83c[\\udffb-\\udfff]",Ns="(?:"+Zr+"|"+Mu+")",yT="[^"+wi+"]",Qm="(?:\\ud83c[\\udde6-\\uddff]){2}",Zm="[\\ud800-\\udbff][\\udc00-\\udfff]",hc="["+dn+"]",AT="\\u200d",RT="(?:"+Po+"|"+mp+")",LA="(?:"+hc+"|"+mp+")",IT="(?:"+En+"(?:d|ll|m|re|s|t|ve))?",PT="(?:"+En+"(?:D|LL|M|RE|S|T|VE))?",MT=Ns+"?",DT="["+Hr+"]?",BA="(?:"+AT+"(?:"+[yT,Qm,Zm].join("|")+")"+DT+MT+")*",VA="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",UA="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",OT=DT+MT+BA,kA="(?:"+[rl,Qm,Zm].join("|")+")"+OT,GA="(?:"+[yT+Zr+"?",Zr,Qm,Zm,ho].join("|")+")",zA=RegExp(En,"g"),WA=RegExp(Zr,"g"),Jm=RegExp(Mu+"(?="+Mu+")|"+GA+OT,"g"),HA=RegExp([hc+"?"+Po+"+"+IT+"(?="+[li,hc,"$"].join("|")+")",LA+"+"+PT+"(?="+[li,hc+RT,"$"].join("|")+")",hc+"?"+RT+"+"+IT,hc+"+"+PT,UA,VA,yr,kA].join("|"),"g"),XA=RegExp("["+AT+wi+cn+Hr+"]"),YA=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,$A=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],KA=-1,Gs={};Gs[br]=Gs[vn]=Gs[Yn]=Gs[Dn]=Gs[jr]=Gs[Wr]=Gs[$n]=Gs[On]=Gs[xn]=!0,Gs[Q]=Gs[_e]=Gs[ti]=Gs[de]=Gs[gs]=Gs[ge]=Gs[be]=Gs[Le]=Gs[He]=Gs[Be]=Gs[Bt]=Gs[at]=Gs[ei]=Gs[di]=Gs[Zt]=!1;var ws={};ws[Q]=ws[_e]=ws[ti]=ws[gs]=ws[de]=ws[ge]=ws[br]=ws[vn]=ws[Yn]=ws[Dn]=ws[jr]=ws[He]=ws[Be]=ws[Bt]=ws[at]=ws[ei]=ws[di]=ws[ci]=ws[Wr]=ws[$n]=ws[On]=ws[xn]=!0,ws[be]=ws[Le]=ws[Zt]=!1;var qA={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},jA={"&":"&","<":"<",">":">",'"':""","'":"'"},QA={"&":"&","<":"<",">":">",""":'"',"'":"'"},ZA={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},JA=parseFloat,eR=parseInt,NT=typeof Yu=="object"&&Yu&&Yu.Object===Object&&Yu,tR=typeof self=="object"&&self&&self.Object===Object&&self,fn=NT||tR||Function("return this")(),eg=e&&!e.nodeType&&e,Ch=eg&&!0&&o&&!o.nodeType&&o,wT=Ch&&Ch.exports===eg,tg=wT&&NT.process,za=function(){try{var Ae=Ch&&Ch.require&&Ch.require("util").types;return Ae||tg&&tg.binding&&tg.binding("util")}catch{}}(),FT=za&&za.isArrayBuffer,LT=za&&za.isDate,BT=za&&za.isMap,VT=za&&za.isRegExp,UT=za&&za.isSet,kT=za&&za.isTypedArray;function _a(Ae,ze,Ve){switch(Ve.length){case 0:return Ae.call(ze);case 1:return Ae.call(ze,Ve[0]);case 2:return Ae.call(ze,Ve[0],Ve[1]);case 3:return Ae.call(ze,Ve[0],Ve[1],Ve[2])}return Ae.apply(ze,Ve)}function iR(Ae,ze,Ve,Ft){for(var mi=-1,os=Ae==null?0:Ae.length;++mi-1}function ig(Ae,ze,Ve){for(var Ft=-1,mi=Ae==null?0:Ae.length;++Ft-1;);return Ve}function KT(Ae,ze){for(var Ve=Ae.length;Ve--&&cc(ze,Ae[Ve],0)>-1;);return Ve}function uR(Ae,ze){for(var Ve=Ae.length,Ft=0;Ve--;)Ae[Ve]===ze&&++Ft;return Ft}var dR=ag(qA),fR=ag(jA);function pR(Ae){return"\\"+ZA[Ae]}function _R(Ae,ze){return Ae==null?t:Ae[ze]}function uc(Ae){return XA.test(Ae)}function mR(Ae){return YA.test(Ae)}function gR(Ae){for(var ze,Ve=[];!(ze=Ae.next()).done;)Ve.push(ze.value);return Ve}function cg(Ae){var ze=-1,Ve=Array(Ae.size);return Ae.forEach(function(Ft,mi){Ve[++ze]=[mi,Ft]}),Ve}function qT(Ae,ze){return function(Ve){return Ae(ze(Ve))}}function Bl(Ae,ze){for(var Ve=-1,Ft=Ae.length,mi=0,os=[];++Ve-1}function rI(m,x){var y=this.__data__,F=wp(y,m);return F<0?(++this.size,y.push([m,x])):y[F][1]=x,this}nl.prototype.clear=eI,nl.prototype.delete=tI,nl.prototype.get=iI,nl.prototype.has=sI,nl.prototype.set=rI;function al(m){var x=-1,y=m==null?0:m.length;for(this.clear();++x=x?m:x)),m}function Ya(m,x,y,F,z,J){var pe,xe=x&u,Pe=x&d,Ke=x&f;if(y&&(pe=z?y(m,F,z,J):y(m)),pe!==t)return pe;if(!Js(m))return m;var je=xi(m);if(je){if(pe=lP(m),!xe)return jn(m,pe)}else{var tt=Cn(m),At=tt==Le||tt==Ye;if(Wl(m))return DE(m,xe);if(tt==Bt||tt==Q||At&&!z){if(pe=Pe||At?{}:jE(m),!xe)return Pe?QI(m,TI(pe,m)):jI(m,oE(pe,m))}else{if(!ws[tt])return z?m:{};pe=hP(m,tt,xe)}}J||(J=new uo);var kt=J.get(m);if(kt)return kt;J.set(m,pe),yS(m)?m.forEach(function(ai){pe.add(Ya(ai,x,y,ai,m,J))}):CS(m)&&m.forEach(function(ai,Ui){pe.set(Ui,Ya(ai,x,y,Ui,m,J))});var ni=Ke?Pe?Lg:Fg:Pe?Zn:Jr,Oi=je?t:ni(m);return Wa(Oi||m,function(ai,Ui){Oi&&(Ui=ai,ai=m[Ui]),Bu(pe,Ui,Ya(ai,x,y,Ui,m,J))}),pe}function EI(m){var x=Jr(m);return function(y){return lE(y,m,x)}}function lE(m,x,y){var F=y.length;if(m==null)return!F;for(m=Ps(m);F--;){var z=y[F],J=x[z],pe=m[z];if(pe===t&&!(z in m)||!J(pe))return!1}return!0}function hE(m,x,y){if(typeof m!="function")throw new Ha(n);return Hu(function(){m.apply(t,y)},x)}function Vu(m,x,y,F){var z=-1,J=gp,pe=!0,xe=m.length,Pe=[],Ke=x.length;if(!xe)return Pe;y&&(x=Ys(x,ma(y))),F?(J=ig,pe=!1):x.length>=s&&(J=Du,pe=!1,x=new Ah(x));e:for(;++zz?0:z+y),F=F===t||F>z?z:Ai(F),F<0&&(F+=z),F=y>F?0:RS(F);y0&&y(xe)?x>1?pn(xe,x-1,y,F,z):Ll(z,xe):F||(z[z.length]=xe)}return z}var gg=BE(),dE=BE(!0);function Mo(m,x){return m&&gg(m,x,Jr)}function vg(m,x){return m&&dE(m,x,Jr)}function Lp(m,x){return Fl(x,function(y){return ul(m[y])})}function Ih(m,x){x=Gl(x,m);for(var y=0,F=x.length;m!=null&&yx}function bI(m,x){return m!=null&&xs.call(m,x)}function yI(m,x){return m!=null&&x in Ps(m)}function AI(m,x,y){return m>=Sn(x,y)&&m=120&&je.length>=120)?new Ah(pe&&je):t}je=m[0];var tt=-1,At=xe[0];e:for(;++tt-1;)xe!==m&&Rp.call(xe,Pe,1),Rp.call(m,Pe,1);return m}function CE(m,x){for(var y=m?x.length:0,F=y-1;y--;){var z=x[y];if(y==F||z!==J){var J=z;cl(z)?Rp.call(m,z,1):Ig(m,z)}}return m}function yg(m,x){return m+Mp(sE()*(x-m+1))}function UI(m,x,y,F){for(var z=-1,J=Yr(Pp((x-m)/(y||1)),0),pe=Ve(J);J--;)pe[F?J:++z]=m,m+=y;return pe}function Ag(m,x){var y="";if(!m||x<1||x>ae)return y;do x%2&&(y+=m),x=Mp(x/2),x&&(m+=m);while(x);return y}function Fi(m,x){return Wg(JE(m,x,Jn),m+"")}function kI(m){return aE(Sc(m))}function GI(m,x){var y=Sc(m);return $p(y,Rh(x,0,y.length))}function Gu(m,x,y,F){if(!Js(m))return m;x=Gl(x,m);for(var z=-1,J=x.length,pe=J-1,xe=m;xe!=null&&++zz?0:z+x),y=y>z?z:y,y<0&&(y+=z),z=x>y?0:y-x>>>0,x>>>=0;for(var J=Ve(z);++F>>1,pe=m[J];pe!==null&&!va(pe)&&(y?pe<=x:pe=s){var Ke=x?null:tP(m);if(Ke)return xp(Ke);pe=!1,z=Du,Pe=new Ah}else Pe=x?[]:xe;e:for(;++F=F?m:$a(m,x,y)}var ME=OR||function(m){return fn.clearTimeout(m)};function DE(m,x){if(x)return m.slice();var y=m.length,F=ZT?ZT(y):new m.constructor(y);return m.copy(F),F}function Og(m){var x=new m.constructor(m.byteLength);return new yp(x).set(new yp(m)),x}function YI(m,x){var y=x?Og(m.buffer):m.buffer;return new m.constructor(y,m.byteOffset,m.byteLength)}function $I(m){var x=new m.constructor(m.source,ct.exec(m));return x.lastIndex=m.lastIndex,x}function KI(m){return Lu?Ps(Lu.call(m)):{}}function OE(m,x){var y=x?Og(m.buffer):m.buffer;return new m.constructor(y,m.byteOffset,m.length)}function NE(m,x){if(m!==x){var y=m!==t,F=m===null,z=m===m,J=va(m),pe=x!==t,xe=x===null,Pe=x===x,Ke=va(x);if(!xe&&!Ke&&!J&&m>x||J&&pe&&Pe&&!xe&&!Ke||F&&pe&&Pe||!y&&Pe||!z)return 1;if(!F&&!J&&!Ke&&m=xe)return Pe;var Ke=y[F];return Pe*(Ke=="desc"?-1:1)}}return m.index-x.index}function wE(m,x,y,F){for(var z=-1,J=m.length,pe=y.length,xe=-1,Pe=x.length,Ke=Yr(J-pe,0),je=Ve(Pe+Ke),tt=!F;++xe1?y[z-1]:t,pe=z>2?y[2]:t;for(J=m.length>3&&typeof J=="function"?(z--,J):t,pe&&Ln(y[0],y[1],pe)&&(J=z<3?t:J,z=1),x=Ps(x);++F-1?z[J?x[pe]:pe]:t}}function kE(m){return hl(function(x){var y=x.length,F=y,z=Xa.prototype.thru;for(m&&x.reverse();F--;){var J=x[F];if(typeof J!="function")throw new Ha(n);if(z&&!pe&&Xp(J)=="wrapper")var pe=new Xa([],!0)}for(F=pe?F:y;++F1&&$i.reverse(),je&&Pexe))return!1;var Ke=J.get(m),je=J.get(x);if(Ke&&je)return Ke==x&&je==m;var tt=-1,At=!0,kt=y&_?new Ah:t;for(J.set(m,x),J.set(x,m);++tt1?"& ":"")+x[F],x=x.join(y>2?", ":" "),m.replace(pt,`{ /* [wrapped with `+x+`] */ -`)}function lP(m){return xi(m)||Mh(m)||!!(JT&&m&&m[JT])}function cl(m,x){var y=typeof m;return x=x??ae,!!x&&(y=="number"||y!="symbol"&&vi.test(m))&&m>-1&&m%1==0&&m0){if(++x>=V)return arguments[0]}else x=0;return m.apply(t,arguments)}}function $p(m,x){var y=-1,F=m.length,z=F-1;for(x=x===t?F:x;++y1?m[x-1]:t;return y=typeof y=="function"?(m.pop(),y):t,hS(m,y)});function cS(m){var x=Y(m);return x.__chain__=!0,x}function xM(m,x){return x(m),m}function Kp(m,x){return x(m)}var TM=hl(function(m){var x=m.length,y=x?m[0]:0,F=this.__wrapped__,z=function(J){return mg(J,m)};return x>1||this.__actions__.length||!(F instanceof Wi)||!cl(y)?this.thru(z):(F=F.slice(y,+y+(x?1:0)),F.__actions__.push({func:Kp,args:[z],thisArg:t}),new Xa(F,this.__chain__).thru(function(J){return x&&!J.length&&J.push(t),J}))});function EM(){return cS(this)}function SM(){return new Xa(this.value(),this.__chain__)}function CM(){this.__values__===t&&(this.__values__=bS(this.value()));var m=this.__index__>=this.__values__.length,x=m?t:this.__values__[this.__index__++];return{done:m,value:x}}function bM(){return this}function yM(m){for(var x,y=this;y instanceof Np;){var F=sS(y);F.__index__=0,F.__values__=t,x?z.__wrapped__=F:x=F;var z=F;y=y.__wrapped__}return z.__wrapped__=m,x}function AM(){var m=this.__wrapped__;if(m instanceof Wi){var x=m;return this.__actions__.length&&(x=new Wi(this)),x=x.reverse(),x.__actions__.push({func:Kp,args:[Hg],thisArg:t}),new Xa(x,this.__chain__)}return this.thru(Hg)}function RM(){return AE(this.__wrapped__,this.__actions__)}var IM=kp(function(m,x,y){xs.call(m,y)?++m[y]:ol(m,y,1)});function PM(m,x,y){var F=xi(m)?UT:xI;return y&&Ln(m,x,y)&&(x=t),F(m,si(x,3))}function MM(m,x){var y=xi(m)?wl:hE;return y(m,si(x,3))}var DM=BE(rS),OM=BE(nS);function NM(m,x){return pn(qp(m,x),1)}function wM(m,x){return pn(qp(m,x),le)}function FM(m,x,y){return y=y===t?1:Ai(y),pn(qp(m,x),y)}function uS(m,x){var y=xi(m)?Wa:Vl;return y(m,si(x,3))}function dS(m,x){var y=xi(m)?eR:lE;return y(m,si(x,3))}var LM=kp(function(m,x,y){xs.call(m,y)?m[y].push(x):ol(m,y,[x])});function BM(m,x,y,F){m=Qn(m)?m:Sc(m),y=y&&!F?Ai(y):0;var z=m.length;return y<0&&(y=Yr(z+y,0)),e_(m)?y<=z&&m.indexOf(x,y)>-1:!!z&&cc(m,x,y)>-1}var VM=Fi(function(m,x,y){var F=-1,z=typeof x=="function",J=Qn(m)?Ve(m.length):[];return Vl(m,function(pe){J[++F]=z?_a(x,pe,y):Uu(pe,x,y)}),J}),UM=kp(function(m,x,y){ol(m,y,x)});function qp(m,x){var y=xi(m)?Ys:_E;return y(m,si(x,3))}function kM(m,x,y,F){return m==null?[]:(xi(x)||(x=x==null?[]:[x]),y=F?t:y,xi(y)||(y=y==null?[]:[y]),xE(m,x,y))}var GM=kp(function(m,x,y){m[y?0:1].push(x)},function(){return[[],[]]});function zM(m,x,y){var F=xi(m)?sg:WT,z=arguments.length<3;return F(m,si(x,4),y,z,Vl)}function WM(m,x,y){var F=xi(m)?tR:WT,z=arguments.length<3;return F(m,si(x,4),y,z,lE)}function HM(m,x){var y=xi(m)?wl:hE;return y(m,Zp(si(x,3)))}function XM(m){var x=xi(m)?rE:BI;return x(m)}function YM(m,x,y){(y?Ln(m,x,y):x===t)?x=1:x=Ai(x);var F=xi(m)?pI:VI;return F(m,x)}function $M(m){var x=xi(m)?_I:kI;return x(m)}function KM(m){if(m==null)return 0;if(Qn(m))return e_(m)?dc(m):m.length;var x=Sn(m);return x==He||x==ei?m.size:Sg(m).length}function qM(m,x,y){var F=xi(m)?rg:GI;return y&&Ln(m,x,y)&&(x=t),F(m,si(x,3))}var jM=Fi(function(m,x){if(m==null)return[];var y=x.length;return y>1&&Ln(m,x[0],x[1])?x=[]:y>2&&Ln(x[0],x[1],x[2])&&(x=[x[0]]),xE(m,pn(x,1),[])}),jp=MR||function(){return fn.Date.now()};function QM(m,x){if(typeof x!="function")throw new Ha(n);return m=Ai(m),function(){if(--m<1)return x.apply(this,arguments)}}function fS(m,x,y){return x=y?t:x,x=m&&x==null?m.length:x,ll(m,I,t,t,t,t,x)}function pS(m,x){var y;if(typeof x!="function")throw new Ha(n);return m=Ai(m),function(){return--m>0&&(y=x.apply(this,arguments)),m<=1&&(x=t),y}}var Yg=Fi(function(m,x,y){var F=g;if(y.length){var z=Ll(y,Tc(Yg));F|=b}return ll(m,F,x,y,z)}),_S=Fi(function(m,x,y){var F=g|v;if(y.length){var z=Ll(y,Tc(_S));F|=b}return ll(x,F,m,y,z)});function mS(m,x,y){x=y?t:x;var F=ll(m,C,t,t,t,t,t,x);return F.placeholder=mS.placeholder,F}function gS(m,x,y){x=y?t:x;var F=ll(m,S,t,t,t,t,t,x);return F.placeholder=gS.placeholder,F}function vS(m,x,y){var F,z,J,pe,xe,Pe,Ke=0,je=!1,tt=!1,At=!0;if(typeof m!="function")throw new Ha(n);x=qa(x)||0,Js(y)&&(je=!!y.leading,tt="maxWait"in y,J=tt?Yr(qa(y.maxWait)||0,x):J,At="trailing"in y?!!y.trailing:At);function kt(Rr){var po=F,fl=z;return F=z=t,Ke=Rr,pe=m.apply(fl,po),pe}function ni(Rr){return Ke=Rr,xe=Hu(Ui,x),je?kt(Rr):pe}function Oi(Rr){var po=Rr-Pe,fl=Rr-Ke,BS=x-po;return tt?En(BS,J-fl):BS}function ai(Rr){var po=Rr-Pe,fl=Rr-Ke;return Pe===t||po>=x||po<0||tt&&fl>=J}function Ui(){var Rr=jp();if(ai(Rr))return $i(Rr);xe=Hu(Ui,Oi(Rr))}function $i(Rr){return xe=t,At&&F?kt(Rr):(F=z=t,pe)}function xa(){xe!==t&&IE(xe),Ke=0,F=Pe=z=xe=t}function Bn(){return xe===t?pe:$i(jp())}function Ta(){var Rr=jp(),po=ai(Rr);if(F=arguments,z=this,Pe=Rr,po){if(xe===t)return ni(Pe);if(tt)return IE(xe),xe=Hu(Ui,x),kt(Pe)}return xe===t&&(xe=Hu(Ui,x)),pe}return Ta.cancel=xa,Ta.flush=Bn,Ta}var ZM=Fi(function(m,x){return oE(m,1,x)}),JM=Fi(function(m,x,y){return oE(m,qa(x)||0,y)});function eD(m){return ll(m,O)}function Qp(m,x){if(typeof m!="function"||x!=null&&typeof x!="function")throw new Ha(n);var y=function(){var F=arguments,z=x?x.apply(this,F):F[0],J=y.cache;if(J.has(z))return J.get(z);var pe=m.apply(this,F);return y.cache=J.set(z,pe)||J,pe};return y.cache=new(Qp.Cache||al),y}Qp.Cache=al;function Zp(m){if(typeof m!="function")throw new Ha(n);return function(){var x=arguments;switch(x.length){case 0:return!m.call(this);case 1:return!m.call(this,x[0]);case 2:return!m.call(this,x[0],x[1]);case 3:return!m.call(this,x[0],x[1],x[2])}return!m.apply(this,x)}}function tD(m){return pS(2,m)}var iD=zI(function(m,x){x=x.length==1&&xi(x[0])?Ys(x[0],ma(si())):Ys(pn(x,1),ma(si()));var y=x.length;return Fi(function(F){for(var z=-1,J=En(F.length,y);++z=x}),Mh=dE(function(){return arguments}())?dE:function(m){return dr(m)&&xs.call(m,"callee")&&!ZT.call(m,"callee")},xi=Ve.isArray,gD=NT?ma(NT):yI;function Qn(m){return m!=null&&Jp(m.length)&&!ul(m)}function Ar(m){return dr(m)&&Qn(m)}function vD(m){return m===!0||m===!1||dr(m)&&Fn(m)==de}var zl=OR||rv,xD=wT?ma(wT):AI;function TD(m){return dr(m)&&m.nodeType===1&&!Xu(m)}function ED(m){if(m==null)return!0;if(Qn(m)&&(xi(m)||typeof m=="string"||typeof m.splice=="function"||zl(m)||Ec(m)||Mh(m)))return!m.length;var x=Sn(m);if(x==He||x==ei)return!m.size;if(Wu(m))return!Sg(m).length;for(var y in m)if(xs.call(m,y))return!1;return!0}function SD(m,x){return ku(m,x)}function CD(m,x,y){y=typeof y=="function"?y:t;var F=y?y(m,x):t;return F===t?ku(m,x,t,y):!!F}function Kg(m){if(!dr(m))return!1;var x=Fn(m);return x==be||x==ve||typeof m.message=="string"&&typeof m.name=="string"&&!Xu(m)}function bD(m){return typeof m=="number"&&eE(m)}function ul(m){if(!Js(m))return!1;var x=Fn(m);return x==Le||x==Ye||x==q||x==Vi}function TS(m){return typeof m=="number"&&m==Ai(m)}function Jp(m){return typeof m=="number"&&m>-1&&m%1==0&&m<=ae}function Js(m){var x=typeof m;return m!=null&&(x=="object"||x=="function")}function dr(m){return m!=null&&typeof m=="object"}var ES=FT?ma(FT):II;function yD(m,x){return m===x||Eg(m,x,Vg(x))}function AD(m,x,y){return y=typeof y=="function"?y:t,Eg(m,x,Vg(x),y)}function RD(m){return SS(m)&&m!=+m}function ID(m){if(uP(m))throw new mi(r);return fE(m)}function PD(m){return m===null}function MD(m){return m==null}function SS(m){return typeof m=="number"||dr(m)&&Fn(m)==Be}function Xu(m){if(!dr(m)||Fn(m)!=Lt)return!1;var x=Ap(m);if(x===null)return!0;var y=xs.call(x,"constructor")&&x.constructor;return typeof y=="function"&&y instanceof y&&Sp.call(y)==AR}var qg=LT?ma(LT):PI;function DD(m){return TS(m)&&m>=-ae&&m<=ae}var CS=BT?ma(BT):MI;function e_(m){return typeof m=="string"||!xi(m)&&dr(m)&&Fn(m)==di}function va(m){return typeof m=="symbol"||dr(m)&&Fn(m)==ci}var Ec=VT?ma(VT):DI;function OD(m){return m===t}function ND(m){return dr(m)&&Sn(m)==Zt}function wD(m){return dr(m)&&Fn(m)==zi}var FD=Hp(Cg),LD=Hp(function(m,x){return m<=x});function bS(m){if(!m)return[];if(Qn(m))return e_(m)?co(m):jn(m);if(Ou&&m[Ou])return pR(m[Ou]());var x=Sn(m),y=x==He?cg:x==ei?xp:Sc;return y(m)}function dl(m){if(!m)return m===0?m:0;if(m=qa(m),m===le||m===-le){var x=m<0?-1:1;return x*ce}return m===m?m:0}function Ai(m){var x=dl(m),y=x%1;return x===x?y?x-y:x:0}function yS(m){return m?Ah(Ai(m),0,w):0}function qa(m){if(typeof m=="number")return m;if(va(m))return ie;if(Js(m)){var x=typeof m.valueOf=="function"?m.valueOf():m;m=Js(x)?x+"":x}if(typeof m!="string")return m===0?m:+m;m=HT(m);var y=Ht.test(m);return y||st.test(m)?QA(m.slice(2),y?2:8):vt.test(m)?ie:+m}function AS(m){return Do(m,Zn(m))}function BD(m){return m?Ah(Ai(m),-ae,ae):m===0?m:0}function fs(m){return m==null?"":ga(m)}var VD=vc(function(m,x){if(Wu(x)||Qn(x)){Do(x,Jr(x),m);return}for(var y in x)xs.call(x,y)&&Bu(m,y,x[y])}),RS=vc(function(m,x){Do(x,Zn(x),m)}),t_=vc(function(m,x,y,F){Do(x,Zn(x),m,F)}),UD=vc(function(m,x,y,F){Do(x,Jr(x),m,F)}),kD=hl(mg);function GD(m,x){var y=gc(m);return x==null?y:nE(y,x)}var zD=Fi(function(m,x){m=Ps(m);var y=-1,F=x.length,z=F>2?x[2]:t;for(z&&Ln(x[0],x[1],z)&&(F=1);++y1),J}),Do(m,Lg(m),y),F&&(y=Ya(y,u|d|f,JI));for(var z=x.length;z--;)Ig(y,x[z]);return y});function aO(m,x){return PS(m,Zp(si(x)))}var oO=hl(function(m,x){return m==null?{}:wI(m,x)});function PS(m,x){if(m==null)return{};var y=Ys(Lg(m),function(F){return[F]});return x=si(x),TE(m,y,function(F,z){return x(F,z[0])})}function lO(m,x,y){x=kl(x,m);var F=-1,z=x.length;for(z||(z=1,m=t);++Fx){var F=m;m=x,x=F}if(y||m%1||x%1){var z=tE();return En(m+z*(x-m+jA("1e-"+((z+"").length-1))),x)}return yg(m,x)}var xO=xc(function(m,x,y){return x=x.toLowerCase(),m+(y?OS(x):x)});function OS(m){return Zg(fs(m).toLowerCase())}function NS(m){return m=fs(m),m&&m.replace(yi,hR).replace(kA,"")}function TO(m,x,y){m=fs(m),x=ga(x);var F=m.length;y=y===t?F:Ah(Ai(y),0,F);var z=y;return y-=x.length,y>=0&&m.slice(y,z)==x}function EO(m){return m=fs(m),m&&wn.test(m)?m.replace(ur,cR):m}function SO(m){return m=fs(m),m&&$e.test(m)?m.replace(Je,"\\$&"):m}var CO=xc(function(m,x,y){return m+(y?"-":"")+x.toLowerCase()}),bO=xc(function(m,x,y){return m+(y?" ":"")+x.toLowerCase()}),yO=LE("toLowerCase");function AO(m,x,y){m=fs(m),x=Ai(x);var F=x?dc(m):0;if(!x||F>=x)return m;var z=(x-F)/2;return Wp(Mp(z),y)+m+Wp(Pp(z),y)}function RO(m,x,y){m=fs(m),x=Ai(x);var F=x?dc(m):0;return x&&F>>0,y?(m=fs(m),m&&(typeof x=="string"||x!=null&&!qg(x))&&(x=ga(x),!x&&uc(m))?Gl(co(m),0,y):m.split(x,y)):[]}var wO=xc(function(m,x,y){return m+(y?" ":"")+Zg(x)});function FO(m,x,y){return m=fs(m),y=y==null?0:Ah(Ai(y),0,m.length),x=ga(x),m.slice(y,y+x.length)==x}function LO(m,x,y){var F=Y.templateSettings;y&&Ln(m,x,y)&&(x=t),m=fs(m),x=t_({},x,F,WE);var z=t_({},x.imports,F.imports,WE),J=Jr(z),pe=hg(z,J),xe,Pe,Ke=0,je=x.interpolate||Is,tt="__p += '",At=ug((x.escape||Is).source+"|"+je.source+"|"+(je===pa?gt:Is).source+"|"+(x.evaluate||Is).source+"|$","g"),kt="//# sourceURL="+(xs.call(x,"sourceURL")?(x.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++XA+"]")+` -`;m.replace(At,function(ai,Ui,$i,xa,Bn,Ta){return $i||($i=xa),tt+=m.slice(Ke,Ta).replace(Di,uR),Ui&&(xe=!0,tt+=`' + +`)}function uP(m){return xi(m)||Dh(m)||!!(tE&&m&&m[tE])}function cl(m,x){var y=typeof m;return x=x??ae,!!x&&(y=="number"||y!="symbol"&&vi.test(m))&&m>-1&&m%1==0&&m0){if(++x>=V)return arguments[0]}else x=0;return m.apply(t,arguments)}}function $p(m,x){var y=-1,F=m.length,z=F-1;for(x=x===t?F:x;++y1?m[x-1]:t;return y=typeof y=="function"?(m.pop(),y):t,uS(m,y)});function dS(m){var x=Y(m);return x.__chain__=!0,x}function SM(m,x){return x(m),m}function Kp(m,x){return x(m)}var CM=hl(function(m){var x=m.length,y=x?m[0]:0,F=this.__wrapped__,z=function(J){return mg(J,m)};return x>1||this.__actions__.length||!(F instanceof Wi)||!cl(y)?this.thru(z):(F=F.slice(y,+y+(x?1:0)),F.__actions__.push({func:Kp,args:[z],thisArg:t}),new Xa(F,this.__chain__).thru(function(J){return x&&!J.length&&J.push(t),J}))});function bM(){return dS(this)}function yM(){return new Xa(this.value(),this.__chain__)}function AM(){this.__values__===t&&(this.__values__=AS(this.value()));var m=this.__index__>=this.__values__.length,x=m?t:this.__values__[this.__index__++];return{done:m,value:x}}function RM(){return this}function IM(m){for(var x,y=this;y instanceof Np;){var F=nS(y);F.__index__=0,F.__values__=t,x?z.__wrapped__=F:x=F;var z=F;y=y.__wrapped__}return z.__wrapped__=m,x}function PM(){var m=this.__wrapped__;if(m instanceof Wi){var x=m;return this.__actions__.length&&(x=new Wi(this)),x=x.reverse(),x.__actions__.push({func:Kp,args:[Hg],thisArg:t}),new Xa(x,this.__chain__)}return this.thru(Hg)}function MM(){return IE(this.__wrapped__,this.__actions__)}var DM=kp(function(m,x,y){xs.call(m,y)?++m[y]:ol(m,y,1)});function OM(m,x,y){var F=xi(m)?GT:SI;return y&&Ln(m,x,y)&&(x=t),F(m,si(x,3))}function NM(m,x){var y=xi(m)?Fl:uE;return y(m,si(x,3))}var wM=UE(aS),FM=UE(oS);function LM(m,x){return pn(qp(m,x),1)}function BM(m,x){return pn(qp(m,x),le)}function VM(m,x,y){return y=y===t?1:Ai(y),pn(qp(m,x),y)}function fS(m,x){var y=xi(m)?Wa:Ul;return y(m,si(x,3))}function pS(m,x){var y=xi(m)?sR:cE;return y(m,si(x,3))}var UM=kp(function(m,x,y){xs.call(m,y)?m[y].push(x):ol(m,y,[x])});function kM(m,x,y,F){m=Qn(m)?m:Sc(m),y=y&&!F?Ai(y):0;var z=m.length;return y<0&&(y=Yr(z+y,0)),e_(m)?y<=z&&m.indexOf(x,y)>-1:!!z&&cc(m,x,y)>-1}var GM=Fi(function(m,x,y){var F=-1,z=typeof x=="function",J=Qn(m)?Ve(m.length):[];return Ul(m,function(pe){J[++F]=z?_a(x,pe,y):Uu(pe,x,y)}),J}),zM=kp(function(m,x,y){ol(m,y,x)});function qp(m,x){var y=xi(m)?Ys:gE;return y(m,si(x,3))}function WM(m,x,y,F){return m==null?[]:(xi(x)||(x=x==null?[]:[x]),y=F?t:y,xi(y)||(y=y==null?[]:[y]),EE(m,x,y))}var HM=kp(function(m,x,y){m[y?0:1].push(x)},function(){return[[],[]]});function XM(m,x,y){var F=xi(m)?sg:XT,z=arguments.length<3;return F(m,si(x,4),y,z,Ul)}function YM(m,x,y){var F=xi(m)?rR:XT,z=arguments.length<3;return F(m,si(x,4),y,z,cE)}function $M(m,x){var y=xi(m)?Fl:uE;return y(m,Zp(si(x,3)))}function KM(m){var x=xi(m)?aE:kI;return x(m)}function qM(m,x,y){(y?Ln(m,x,y):x===t)?x=1:x=Ai(x);var F=xi(m)?gI:GI;return F(m,x)}function jM(m){var x=xi(m)?vI:WI;return x(m)}function QM(m){if(m==null)return 0;if(Qn(m))return e_(m)?dc(m):m.length;var x=Cn(m);return x==He||x==ei?m.size:Sg(m).length}function ZM(m,x,y){var F=xi(m)?rg:HI;return y&&Ln(m,x,y)&&(x=t),F(m,si(x,3))}var JM=Fi(function(m,x){if(m==null)return[];var y=x.length;return y>1&&Ln(m,x[0],x[1])?x=[]:y>2&&Ln(x[0],x[1],x[2])&&(x=[x[0]]),EE(m,pn(x,1),[])}),jp=NR||function(){return fn.Date.now()};function eD(m,x){if(typeof x!="function")throw new Ha(n);return m=Ai(m),function(){if(--m<1)return x.apply(this,arguments)}}function _S(m,x,y){return x=y?t:x,x=m&&x==null?m.length:x,ll(m,I,t,t,t,t,x)}function mS(m,x){var y;if(typeof x!="function")throw new Ha(n);return m=Ai(m),function(){return--m>0&&(y=x.apply(this,arguments)),m<=1&&(x=t),y}}var Yg=Fi(function(m,x,y){var F=g;if(y.length){var z=Bl(y,Tc(Yg));F|=b}return ll(m,F,x,y,z)}),gS=Fi(function(m,x,y){var F=g|v;if(y.length){var z=Bl(y,Tc(gS));F|=b}return ll(x,F,m,y,z)});function vS(m,x,y){x=y?t:x;var F=ll(m,C,t,t,t,t,t,x);return F.placeholder=vS.placeholder,F}function xS(m,x,y){x=y?t:x;var F=ll(m,S,t,t,t,t,t,x);return F.placeholder=xS.placeholder,F}function TS(m,x,y){var F,z,J,pe,xe,Pe,Ke=0,je=!1,tt=!1,At=!0;if(typeof m!="function")throw new Ha(n);x=qa(x)||0,Js(y)&&(je=!!y.leading,tt="maxWait"in y,J=tt?Yr(qa(y.maxWait)||0,x):J,At="trailing"in y?!!y.trailing:At);function kt(Rr){var po=F,fl=z;return F=z=t,Ke=Rr,pe=m.apply(fl,po),pe}function ni(Rr){return Ke=Rr,xe=Hu(Ui,x),je?kt(Rr):pe}function Oi(Rr){var po=Rr-Pe,fl=Rr-Ke,US=x-po;return tt?Sn(US,J-fl):US}function ai(Rr){var po=Rr-Pe,fl=Rr-Ke;return Pe===t||po>=x||po<0||tt&&fl>=J}function Ui(){var Rr=jp();if(ai(Rr))return $i(Rr);xe=Hu(Ui,Oi(Rr))}function $i(Rr){return xe=t,At&&F?kt(Rr):(F=z=t,pe)}function xa(){xe!==t&&ME(xe),Ke=0,F=Pe=z=xe=t}function Bn(){return xe===t?pe:$i(jp())}function Ta(){var Rr=jp(),po=ai(Rr);if(F=arguments,z=this,Pe=Rr,po){if(xe===t)return ni(Pe);if(tt)return ME(xe),xe=Hu(Ui,x),kt(Pe)}return xe===t&&(xe=Hu(Ui,x)),pe}return Ta.cancel=xa,Ta.flush=Bn,Ta}var tD=Fi(function(m,x){return hE(m,1,x)}),iD=Fi(function(m,x,y){return hE(m,qa(x)||0,y)});function sD(m){return ll(m,O)}function Qp(m,x){if(typeof m!="function"||x!=null&&typeof x!="function")throw new Ha(n);var y=function(){var F=arguments,z=x?x.apply(this,F):F[0],J=y.cache;if(J.has(z))return J.get(z);var pe=m.apply(this,F);return y.cache=J.set(z,pe)||J,pe};return y.cache=new(Qp.Cache||al),y}Qp.Cache=al;function Zp(m){if(typeof m!="function")throw new Ha(n);return function(){var x=arguments;switch(x.length){case 0:return!m.call(this);case 1:return!m.call(this,x[0]);case 2:return!m.call(this,x[0],x[1]);case 3:return!m.call(this,x[0],x[1],x[2])}return!m.apply(this,x)}}function rD(m){return mS(2,m)}var nD=XI(function(m,x){x=x.length==1&&xi(x[0])?Ys(x[0],ma(si())):Ys(pn(x,1),ma(si()));var y=x.length;return Fi(function(F){for(var z=-1,J=Sn(F.length,y);++z=x}),Dh=pE(function(){return arguments}())?pE:function(m){return dr(m)&&xs.call(m,"callee")&&!eE.call(m,"callee")},xi=Ve.isArray,TD=FT?ma(FT):II;function Qn(m){return m!=null&&Jp(m.length)&&!ul(m)}function Ar(m){return dr(m)&&Qn(m)}function ED(m){return m===!0||m===!1||dr(m)&&Fn(m)==de}var Wl=FR||rv,SD=LT?ma(LT):PI;function CD(m){return dr(m)&&m.nodeType===1&&!Xu(m)}function bD(m){if(m==null)return!0;if(Qn(m)&&(xi(m)||typeof m=="string"||typeof m.splice=="function"||Wl(m)||Ec(m)||Dh(m)))return!m.length;var x=Cn(m);if(x==He||x==ei)return!m.size;if(Wu(m))return!Sg(m).length;for(var y in m)if(xs.call(m,y))return!1;return!0}function yD(m,x){return ku(m,x)}function AD(m,x,y){y=typeof y=="function"?y:t;var F=y?y(m,x):t;return F===t?ku(m,x,t,y):!!F}function Kg(m){if(!dr(m))return!1;var x=Fn(m);return x==be||x==ve||typeof m.message=="string"&&typeof m.name=="string"&&!Xu(m)}function RD(m){return typeof m=="number"&&iE(m)}function ul(m){if(!Js(m))return!1;var x=Fn(m);return x==Le||x==Ye||x==q||x==Vi}function SS(m){return typeof m=="number"&&m==Ai(m)}function Jp(m){return typeof m=="number"&&m>-1&&m%1==0&&m<=ae}function Js(m){var x=typeof m;return m!=null&&(x=="object"||x=="function")}function dr(m){return m!=null&&typeof m=="object"}var CS=BT?ma(BT):DI;function ID(m,x){return m===x||Eg(m,x,Vg(x))}function PD(m,x,y){return y=typeof y=="function"?y:t,Eg(m,x,Vg(x),y)}function MD(m){return bS(m)&&m!=+m}function DD(m){if(pP(m))throw new mi(r);return _E(m)}function OD(m){return m===null}function ND(m){return m==null}function bS(m){return typeof m=="number"||dr(m)&&Fn(m)==Be}function Xu(m){if(!dr(m)||Fn(m)!=Bt)return!1;var x=Ap(m);if(x===null)return!0;var y=xs.call(x,"constructor")&&x.constructor;return typeof y=="function"&&y instanceof y&&Sp.call(y)==PR}var qg=VT?ma(VT):OI;function wD(m){return SS(m)&&m>=-ae&&m<=ae}var yS=UT?ma(UT):NI;function e_(m){return typeof m=="string"||!xi(m)&&dr(m)&&Fn(m)==di}function va(m){return typeof m=="symbol"||dr(m)&&Fn(m)==ci}var Ec=kT?ma(kT):wI;function FD(m){return m===t}function LD(m){return dr(m)&&Cn(m)==Zt}function BD(m){return dr(m)&&Fn(m)==zi}var VD=Hp(Cg),UD=Hp(function(m,x){return m<=x});function AS(m){if(!m)return[];if(Qn(m))return e_(m)?co(m):jn(m);if(Ou&&m[Ou])return gR(m[Ou]());var x=Cn(m),y=x==He?cg:x==ei?xp:Sc;return y(m)}function dl(m){if(!m)return m===0?m:0;if(m=qa(m),m===le||m===-le){var x=m<0?-1:1;return x*ce}return m===m?m:0}function Ai(m){var x=dl(m),y=x%1;return x===x?y?x-y:x:0}function RS(m){return m?Rh(Ai(m),0,w):0}function qa(m){if(typeof m=="number")return m;if(va(m))return ie;if(Js(m)){var x=typeof m.valueOf=="function"?m.valueOf():m;m=Js(x)?x+"":x}if(typeof m!="string")return m===0?m:+m;m=YT(m);var y=Ht.test(m);return y||st.test(m)?eR(m.slice(2),y?2:8):vt.test(m)?ie:+m}function IS(m){return Do(m,Zn(m))}function kD(m){return m?Rh(Ai(m),-ae,ae):m===0?m:0}function fs(m){return m==null?"":ga(m)}var GD=vc(function(m,x){if(Wu(x)||Qn(x)){Do(x,Jr(x),m);return}for(var y in x)xs.call(x,y)&&Bu(m,y,x[y])}),PS=vc(function(m,x){Do(x,Zn(x),m)}),t_=vc(function(m,x,y,F){Do(x,Zn(x),m,F)}),zD=vc(function(m,x,y,F){Do(x,Jr(x),m,F)}),WD=hl(mg);function HD(m,x){var y=gc(m);return x==null?y:oE(y,x)}var XD=Fi(function(m,x){m=Ps(m);var y=-1,F=x.length,z=F>2?x[2]:t;for(z&&Ln(x[0],x[1],z)&&(F=1);++y1),J}),Do(m,Lg(m),y),F&&(y=Ya(y,u|d|f,iP));for(var z=x.length;z--;)Ig(y,x[z]);return y});function hO(m,x){return DS(m,Zp(si(x)))}var cO=hl(function(m,x){return m==null?{}:BI(m,x)});function DS(m,x){if(m==null)return{};var y=Ys(Lg(m),function(F){return[F]});return x=si(x),SE(m,y,function(F,z){return x(F,z[0])})}function uO(m,x,y){x=Gl(x,m);var F=-1,z=x.length;for(z||(z=1,m=t);++Fx){var F=m;m=x,x=F}if(y||m%1||x%1){var z=sE();return Sn(m+z*(x-m+JA("1e-"+((z+"").length-1))),x)}return yg(m,x)}var SO=xc(function(m,x,y){return x=x.toLowerCase(),m+(y?wS(x):x)});function wS(m){return Zg(fs(m).toLowerCase())}function FS(m){return m=fs(m),m&&m.replace(yi,dR).replace(WA,"")}function CO(m,x,y){m=fs(m),x=ga(x);var F=m.length;y=y===t?F:Rh(Ai(y),0,F);var z=y;return y-=x.length,y>=0&&m.slice(y,z)==x}function bO(m){return m=fs(m),m&&wn.test(m)?m.replace(ur,fR):m}function yO(m){return m=fs(m),m&&$e.test(m)?m.replace(Je,"\\$&"):m}var AO=xc(function(m,x,y){return m+(y?"-":"")+x.toLowerCase()}),RO=xc(function(m,x,y){return m+(y?" ":"")+x.toLowerCase()}),IO=VE("toLowerCase");function PO(m,x,y){m=fs(m),x=Ai(x);var F=x?dc(m):0;if(!x||F>=x)return m;var z=(x-F)/2;return Wp(Mp(z),y)+m+Wp(Pp(z),y)}function MO(m,x,y){m=fs(m),x=Ai(x);var F=x?dc(m):0;return x&&F>>0,y?(m=fs(m),m&&(typeof x=="string"||x!=null&&!qg(x))&&(x=ga(x),!x&&uc(m))?zl(co(m),0,y):m.split(x,y)):[]}var BO=xc(function(m,x,y){return m+(y?" ":"")+Zg(x)});function VO(m,x,y){return m=fs(m),y=y==null?0:Rh(Ai(y),0,m.length),x=ga(x),m.slice(y,y+x.length)==x}function UO(m,x,y){var F=Y.templateSettings;y&&Ln(m,x,y)&&(x=t),m=fs(m),x=t_({},x,F,XE);var z=t_({},x.imports,F.imports,XE),J=Jr(z),pe=hg(z,J),xe,Pe,Ke=0,je=x.interpolate||Is,tt="__p += '",At=ug((x.escape||Is).source+"|"+je.source+"|"+(je===pa?gt:Is).source+"|"+(x.evaluate||Is).source+"|$","g"),kt="//# sourceURL="+(xs.call(x,"sourceURL")?(x.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++KA+"]")+` +`;m.replace(At,function(ai,Ui,$i,xa,Bn,Ta){return $i||($i=xa),tt+=m.slice(Ke,Ta).replace(Di,pR),Ui&&(xe=!0,tt+=`' + __e(`+Ui+`) + '`),Bn&&(Pe=!0,tt+=`'; `+Bn+`; @@ -11724,10 +11724,10 @@ __p += '`),$i&&(tt+=`' + `;var ni=xs.call(x,"variable")&&x.variable;if(!ni)tt=`with (obj) { `+tt+` } -`;else if(Et.test(ni))throw new mi(a);tt=(Pe?tt.replace(Nn,""):tt).replace(hn,"$1").replace(xn,"$1;"),tt="function("+(ni||"obj")+`) { +`;else if(Et.test(ni))throw new mi(a);tt=(Pe?tt.replace(Nn,""):tt).replace(hn,"$1").replace(Tn,"$1;"),tt="function("+(ni||"obj")+`) { `+(ni?"":`obj || (obj = {}); `)+"var __t, __p = ''"+(xe?", __e = _.escape":"")+(Pe?`, __j = Array.prototype.join; function print() { __p += __j.call(arguments, '') } `:`; `)+tt+`return __p -}`;var Oi=FS(function(){return os(J,kt+"return "+tt).apply(t,pe)});if(Oi.source=tt,Kg(Oi))throw Oi;return Oi}function BO(m){return fs(m).toLowerCase()}function VO(m){return fs(m).toUpperCase()}function UO(m,x,y){if(m=fs(m),m&&(y||x===t))return HT(m);if(!m||!(x=ga(x)))return m;var F=co(m),z=co(x),J=XT(F,z),pe=YT(F,z)+1;return Gl(F,J,pe).join("")}function kO(m,x,y){if(m=fs(m),m&&(y||x===t))return m.slice(0,KT(m)+1);if(!m||!(x=ga(x)))return m;var F=co(m),z=YT(F,co(x))+1;return Gl(F,0,z).join("")}function GO(m,x,y){if(m=fs(m),m&&(y||x===t))return m.replace(Wt,"");if(!m||!(x=ga(x)))return m;var F=co(m),z=XT(F,co(x));return Gl(F,z).join("")}function zO(m,x){var y=L,F=B;if(Js(x)){var z="separator"in x?x.separator:z;y="length"in x?Ai(x.length):y,F="omission"in x?ga(x.omission):F}m=fs(m);var J=m.length;if(uc(m)){var pe=co(m);J=pe.length}if(y>=J)return m;var xe=y-dc(F);if(xe<1)return F;var Pe=pe?Gl(pe,0,xe).join(""):m.slice(0,xe);if(z===t)return Pe+F;if(pe&&(xe+=Pe.length-xe),qg(z)){if(m.slice(xe).search(z)){var Ke,je=Pe;for(z.global||(z=ug(z.source,fs(ct.exec(z))+"g")),z.lastIndex=0;Ke=z.exec(je);)var tt=Ke.index;Pe=Pe.slice(0,tt===t?xe:tt)}}else if(m.indexOf(ga(z),xe)!=xe){var At=Pe.lastIndexOf(z);At>-1&&(Pe=Pe.slice(0,At))}return Pe+F}function WO(m){return m=fs(m),m&&da.test(m)?m.replace(Qr,vR):m}var HO=xc(function(m,x,y){return m+(y?" ":"")+x.toUpperCase()}),Zg=LE("toUpperCase");function wS(m,x,y){return m=fs(m),x=y?t:x,x===t?fR(m)?ER(m):rR(m):m.match(x)||[]}var FS=Fi(function(m,x){try{return _a(m,t,x)}catch(y){return Kg(y)?y:new mi(y)}}),XO=hl(function(m,x){return Wa(x,function(y){y=Oo(y),ol(m,y,Yg(m[y],m))}),m});function YO(m){var x=m==null?0:m.length,y=si();return m=x?Ys(m,function(F){if(typeof F[1]!="function")throw new Ha(n);return[y(F[0]),F[1]]}):[],Fi(function(F){for(var z=-1;++zae)return[];var y=w,F=En(m,w);x=si(x),m-=w;for(var z=lg(F,x);++y0||x<0)?new Wi(y):(m<0?y=y.takeRight(-m):m&&(y=y.drop(m)),x!==t&&(x=Ai(x),y=x<0?y.dropRight(-x):y.take(x-m)),y)},Wi.prototype.takeRightWhile=function(m){return this.reverse().takeWhile(m).reverse()},Wi.prototype.toArray=function(){return this.take(w)},Mo(Wi.prototype,function(m,x){var y=/^(?:filter|find|map|reject)|While$/.test(x),F=/^(?:head|last)$/.test(x),z=Y[F?"take"+(x=="last"?"Right":""):x],J=F||/^find/.test(x);z&&(Y.prototype[x]=function(){var pe=this.__wrapped__,xe=F?[1]:arguments,Pe=pe instanceof Wi,Ke=xe[0],je=Pe||xi(pe),tt=function(Ui){var $i=z.apply(Y,Fl([Ui],xe));return F&&At?$i[0]:$i};je&&y&&typeof Ke=="function"&&Ke.length!=1&&(Pe=je=!1);var At=this.__chain__,kt=!!this.__actions__.length,ni=J&&!At,Oi=Pe&&!kt;if(!J&&je){pe=Oi?pe:new Wi(this);var ai=m.apply(pe,xe);return ai.__actions__.push({func:Kp,args:[tt],thisArg:t}),new Xa(ai,At)}return ni&&Oi?m.apply(this,xe):(ai=this.thru(tt),ni?F?ai.value()[0]:ai.value():ai)})}),Wa(["pop","push","shift","sort","splice","unshift"],function(m){var x=Tp[m],y=/^(?:push|sort|unshift)$/.test(m)?"tap":"thru",F=/^(?:pop|shift)$/.test(m);Y.prototype[m]=function(){var z=arguments;if(F&&!this.__chain__){var J=this.value();return x.apply(xi(J)?J:[],z)}return this[y](function(pe){return x.apply(xi(pe)?pe:[],z)})}}),Mo(Wi.prototype,function(m,x){var y=Y[x];if(y){var F=y.name+"";xs.call(mc,F)||(mc[F]=[]),mc[F].push({name:x,func:y})}}),mc[Gp(t,v).name]=[{name:"wrapper",func:t}],Wi.prototype.clone=WR,Wi.prototype.reverse=HR,Wi.prototype.value=XR,Y.prototype.at=TM,Y.prototype.chain=EM,Y.prototype.commit=SM,Y.prototype.next=CM,Y.prototype.plant=yM,Y.prototype.reverse=AM,Y.prototype.toJSON=Y.prototype.valueOf=Y.prototype.value=RM,Y.prototype.first=Y.prototype.head,Ou&&(Y.prototype[Ou]=bM),Y},fc=SR();Sh?((Sh.exports=fc)._=fc,eg._=fc):fn._=fc}).call(Yu)})(K_,K_.exports);var JY=K_.exports;class e6 extends Error{constructor(e){super(`[DomSetup] ${e}`)}}class VC extends Error{constructor(e){super(`[AppError] ${e}`)}}class UC{constructor(e){Ut(this,"key");Ut(this,"used");this.key=e.key,this.used=e.used||!1}}class t6{constructor(){Ut(this,"singletonInstance",null);Ut(this,"keyState",new Map);Ut(this,"keyDownHandler",e=>{const{key:t}=e;this.keyState.set(t,new UC({key:t}))});Ut(this,"keyUpHandler",e=>{const{key:t}=e;this.keyState.has(t)&&this.keyState.delete(t)});if(this.singletonInstance)return this.singletonInstance;this.keyState=new Map,addEventListener("keydown",this.keyDownHandler),addEventListener("keyup",this.keyUpHandler),this.singletonInstance=this}clear(){removeEventListener("keydown",this.keyDownHandler),removeEventListener("keyup",this.keyUpHandler)}wasPressedOnce(e){var i;let t=!1;return this.keyState.has(e)&&(t=!((i=this.keyState.get(e))!=null&&i.used),this.keyState.set(e,new UC({key:e,used:!0}))),t}isBeingPressed(e){return!!this.keyState.has(e)}}class i6{constructor(e){Ut(this,"input",{keyboardHandler:new t6});Ut(this,"currentScene");Ut(this,"allScenes",new Map);this.engine=e}createScene(e,t){this.allScenes.set(e,t),this.currentScene||(this.currentScene=t)}goToScene(e){this.allScenes.has(e)?this.currentScene=this.allScenes.get(e):console.warn(`The scene with key ${e} was not found! Keeping previous scene!`)}runRenderLoop(){if(!this.currentScene)throw new VC("No default scene was configured!");this.engine.runRenderLoop(()=>{const e=this.engine.getDeltaTime();if(!this.currentScene)throw new VC("Trying to render undefined scene!");this.currentScene.update(e),this.currentScene.render(!0)})}}class s6 extends Qe{constructor(t,i){super(t.engine);Ut(this,"entities",[]);Ut(this,"_camera");Ut(this,"_light");this.app=t,this.enablePhysics(i!=null&&i.gravity?i.gravity:T.Down().scale(9.8),new V_),this._camera=new zn("BASE-CAMERA",T.Up().scale(50),this),this._camera.attachControl(t.engine.getRenderingCanvas(),!0),this._light=new ro("BASE-LIGHT",T.Down(),this)}update(t){this.entities.forEach(i=>this.entities.forEach(s=>{i!==s&&i.collisionType!=="none"&&s.collisionType!=="none"&&i.mesh.intersectsMesh(s.mesh)&&(i.onCollision(s,this.app),s.onCollision(i,this.app))})),this.entities.forEach(i=>i.update(this.app,t)),this.entities=this.entities.filter(i=>i.isAlive)}addEntity(t){this.entities.push(t),t.onEnterScene(this)}set camera(t){this._camera.detachControl(),this._camera.dispose(),this._camera=t,this._camera.attachControl(this.app.engine.getRenderingCanvas(),!0)}get camera(){return this._camera}set light(t){this._light.dispose(),this._light=t}get light(){return this._light}}class lc{constructor(e){Ut(this,"_mesh");Ut(this,"isAlive",!0);Ut(this,"collisionType","none");Ut(this,"meshChildren",[]);this.scene=e,this._mesh=new se("BASE-MESH")}update(e,t){}onCollision(e,t){}onEnterScene(e){}kill(){this.isAlive=!1,this.mesh&&this.scene.removeMesh(this.mesh),this.meshChildren.forEach(e=>this.scene.removeMesh(e.mesh))}set mesh(e){this._mesh=e}get mesh(){return this._mesh}}class r6{static useParabolaCurve(e){const t=e.min?e.min:0,i=e.max,s=i-t,r=t+s/2;return a=>{a=Math.min(i,Math.max(a,t));let l=0;return a<=r?l=a/r:l=1-(a-r)/r,Math.min(1,Math.max(l,0))}}}class MA{static useLinearPath(e){const t=e.start,i=e.end;return r=>{const n=Math.min(1,Math.max(r,0)),a=t.x+(i.x-t.x)*n,l=t.y+(i.y-t.y)*n,h=t.z+(i.z-t.z)*n;return new T(a,l,h)}}}class n6{static findRotationAngleBasedOnDirection(e){return e==="top"?0:e==="right"?Math.PI/2:e==="bottom"?Math.PI:Math.PI*3/2}}class a6 extends lc{constructor(t,i){super(t);Ut(this,"direction");Ut(this,"start");Ut(this,"end");Ut(this,"pathProgress");Ut(this,"velocity");Ut(this,"width");Ut(this,"height");Ut(this,"depth");Ut(this,"pathMap");this.width=i.width,this.height=i.height,this.depth=i.depth,this.direction=i.direction,this.start=i.start,this.end=i.end,this.pathProgress=i.pathProgress,this.velocity=i.velocity,this.pathMap=MA.useLinearPath({start:this.start,end:this.end}),this.collisionType="dynamic";const s=Te.Random(),r=new Te(.15,.15,.15);this.mesh=Rn.CreateBox("CAR-MESH",{width:this.width,depth:this.depth,height:this.height/2},t),this.mesh.position=i.start,this.mesh.material=new Oe("CAR-MESH-MATERIAL",t),this.mesh.material instanceof Oe&&(this.mesh.material.diffuseColor=s);const n=T.Down().scale(30),a=Rn.CreateBox("CAR-MESH",{width:this.width,depth:this.depth/2,height:this.height/2},t);a.position=n,a.material=new Oe("CAR-MESH-MATERIAL",t),a.material instanceof Oe&&(a.material.diffuseColor=s),this.meshChildren.push({mesh:a,anchorToParent:new T(0,this.height/2,0)});const l=Rn.CreateCylinder("CAR-MESH",{height:this.width*1.1,diameter:this.height*5/8});l.position=n,l.rotation=new T(0,0,Math.PI/2),l.material=new Oe("CAR-MESH-MATERIAL",t),l.material instanceof Oe&&(l.material.diffuseColor=r),this.meshChildren.push({mesh:l,anchorToParent:new T(0,-this.height/6,this.depth/3)});const h=Rn.CreateCylinder("CAR-MESH",{height:this.width*1.1,diameter:this.height*5/8});h.position=n,h.rotation=new T(0,0,Math.PI/2),h.material=new Oe("CAR-MESH-MATERIAL",t),h.material instanceof Oe&&(h.material.diffuseColor=r),this.meshChildren.push({mesh:h,anchorToParent:new T(0,-this.height/6,-this.depth/3)})}update(t,i){const s=this.direction==="right"?1:-1,r=this.velocity*i*s;this.pathProgress=(this.pathProgress+r*s+1)%1,this._mesh.position=this.pathMap(this.pathProgress),this.meshChildren.forEach(({mesh:n,anchorToParent:a})=>{n.position=this._mesh.position.add(a)})}}class o6 extends lc{constructor(t,i){super(t);Ut(this,"direction");Ut(this,"start");Ut(this,"end");Ut(this,"pathProgress");Ut(this,"velocity");Ut(this,"pathMap");this.mesh=Rn.CreateBox("LOG-MESH",{width:i.width,depth:i.depth,height:i.height},t),this.mesh.position=i.start,this.mesh.material=new Oe("LOG-MESH-MATERIAL",t),this.mesh.material instanceof Oe&&(this.mesh.material.diffuseColor=new Te(.6,.5,.3)),this.direction=i.direction,this.start=i.start,this.end=i.end,this.pathProgress=i.pathProgress,this.velocity=i.velocity,this.pathMap=MA.useLinearPath({start:this.start,end:this.end}),this.collisionType="platform"}update(t,i){const s=this.direction==="right"?1:-1,r=this.velocity*i*s;this.pathProgress=(this.pathProgress+r*s+1)%1,this._mesh.position=this.pathMap(this.pathProgress)}}const bs=16;class l6{constructor(e){this.scene=e}getClosestTile(e,t){return this.scene.tiles.find(i=>Math.abs(e-i.x)<=t)}}const h6=()=>{const o=new Map;let e="idle";return{state:()=>e,transition:i=>{const s=e;switch(e){case"idle":switch(i){case"move":e="moving";break;case"stop":e="idle";break;case"bind-to-platform":e="on-platform";break}break;case"moving":switch(i){case"move":e="moving";break;case"stop":e="idle";break;case"move-back":e="moving-back";break}break;case"moving-back":switch(i){case"stop":e="idle";break;case"move-back":e="moving-back";break}break;case"on-platform":switch(i){case"stop":e="idle";break;case"move":e="moving";break}}s!==e&&(o.get(e)||[]).forEach(n=>n())},registerCallback:(i,s)=>{o.has(i)?o.set(i,[...o.get(i),s]):o.set(i,[s])}}},j_=class j_ extends lc{constructor(t,i){super(t);Ut(this,"stateMachine");Ut(this,"jumpCurrDistance",0);Ut(this,"direction","top");Ut(this,"width");Ut(this,"depth");Ut(this,"height");Ut(this,"platform");Ut(this,"platformCenterOffset");Ut(this,"tiledSceneNavigator");Ut(this,"scene");this.scene=t;const s=i!=null&&i.size?i.size:bs,r=Te.Red();this.width=s,this.height=s*2,this.depth=s,this.mesh=Rn.CreateBox("PLAYER-MESH",{height:this.height,depth:this.depth,width:this.width},t),i!=null&&i.position&&(this.mesh.position=i.position),this.mesh.material=new Oe("PLAYER-MESH-MATERIAL",t),this.mesh.material instanceof Oe&&(this.mesh.material.diffuseColor=Te.White());const n=T.Down().scale(30),a=Rn.CreateBox("PLAYER-MESH",{height:this.height/2,depth:this.depth,width:this.width/2},t);a.position=n,a.material=new Oe("PLAYER-MESH-MATERIAL",t),a.material instanceof Oe&&(a.material.diffuseColor=Te.White()),this.meshChildren.push({mesh:a,anchorToParent:new T(-this.width*3/4,-this.height/4,0)});const l=Rn.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/4,width:this.width/2},t);l.position=n,l.material=new Oe("PLAYER-MESH-MATERIAL",t),l.material instanceof Oe&&(l.material.diffuseColor=r),this.meshChildren.push({mesh:l,anchorToParent:new T(0,this.height*9/16,0)});const h=Rn.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/2,width:this.width/4},t);h.position=n,h.material=new Oe("PLAYER-MESH-MATERIAL",t),h.material instanceof Oe&&(h.material.diffuseColor=new Te(.95,.65,.2)),this.meshChildren.push({mesh:h,anchorToParent:new T(this.width*5/8,this.height/4,0)});const c=Rn.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/4,width:this.width/4},t);c.position=n,c.material=new Oe("PLAYER-MESH-MATERIAL",t),c.material instanceof Oe&&(c.material.diffuseColor=r),this.meshChildren.push({mesh:c,anchorToParent:new T(this.width*5/8,this.height/8,0)}),this.stateMachine=h6(),this.stateMachine.registerCallback("moving",()=>this.jumpCurrDistance=0),this.stateMachine.registerCallback("idle",()=>{this._mesh.position=new T(Math.round(this._mesh.position.x),Math.round(this._mesh.position.y),Math.round(this._mesh.position.z))}),this.collisionType="dynamic",t instanceof q_&&(this.tiledSceneNavigator=new l6(t))}updateJump(t,i){const s=this.stateMachine.state();if(s==="moving-back"&&this.jumpCurrDistance<=0||s==="moving"&&this.jumpCurrDistance>=bs){this.stateMachine.transition("stop");return}const r=.08*i,n=this.direction==="top"||this.direction==="bottom"?"x":(this.direction==="right"||this.direction==="left","z");let a=this.direction==="top"||this.direction==="left"?1:-1;if(s==="moving"){const l=Math.min(r,bs-this.jumpCurrDistance);this.mesh.position[n]+=l*a,this.jumpCurrDistance+=l}else if(s==="moving-back"){const l=Math.min(r,this.jumpCurrDistance);a*=-1,this.mesh.position[n]+=l*a,this.jumpCurrDistance-=l}this.mesh.position.y=this.height/2+j_.jumpVerticalDistanceCurve(this.jumpCurrDistance)*bs}updatePlatform(t,i){this.platform&&this.platformCenterOffset&&(this._mesh.position=this.platform._mesh.position.add(this.platformCenterOffset))}handleIdle(t,i){var r;const s=(r=this.tiledSceneNavigator)==null?void 0:r.getClosestTile(this._mesh.position._x,this.depth);(s==null?void 0:s.tile.collisionType)==="dynamic"&&s.x>0&&t.engine.stopRenderLoop()}onCollision(t,i){i.engine.getFps()!==1/0&&(t.collisionType==="static"&&this.stateMachine.transition("move-back"),t.collisionType==="dynamic"&&i.engine.stopRenderLoop(),t.collisionType==="platform"&&(this.stateMachine.state()==="idle"&&(this.platform=t,this.platformCenterOffset=this._mesh.position.subtract(t._mesh.position)),this.stateMachine.transition("bind-to-platform")))}updateMesh(t,i){const s=n6.findRotationAngleBasedOnDirection(this.direction),r=new T(0,s,0);this._mesh.rotation=r,this.meshChildren.forEach(({mesh:n,anchorToParent:a})=>{n.rotation=r;const l=Se.FromEulerAngles(0,s,0),h=a.applyRotationQuaternion(l);n.position=this._mesh.position.add(h)})}update(t,i){if(t.engine.getFps()===1/0)return;const{input:{keyboardHandler:s}}=t,r=this.stateMachine.state();switch(r){case"idle":case"on-platform":s.wasPressedOnce("ArrowUp")||s.wasPressedOnce(" ")?(this.direction="top",this.stateMachine.transition("move")):s.wasPressedOnce("ArrowDown")&&(this.direction="bottom",this.stateMachine.transition("move")),s.wasPressedOnce("ArrowRight")?(this.direction="right",this.stateMachine.transition("move")):s.wasPressedOnce("ArrowLeft")&&(this.direction="left",this.stateMachine.transition("move")),r==="on-platform"&&this.updatePlatform(t,i),r==="idle"&&this.handleIdle(t,i);break;case"moving":case"moving-back":this.updateJump(t,i);break}this.updateMesh(t,i)}};Ut(j_,"jumpVerticalDistanceCurve",r6.useParabolaCurve({min:0,max:bs}));let ex=j_;class Iv extends lc{constructor(t,i){super(t);Ut(this,"width");Ut(this,"depth");this.width=i.width,this.depth=i.depth;const s=bs;this.mesh=Rn.CreateBox("LIMIT-MESH",{width:this.width,height:s*1.1,depth:this.depth},t),this._mesh.position=new T(i.x,-bs/2,i.z),this._mesh.material=new Oe("TILE-MESH-MATERIAL",t),this._mesh.material instanceof Oe&&(this._mesh.material.diffuseColor=new Te(.05,.05,.05)),this.collisionType="static"}}class c6 extends lc{constructor(e,t){super(e);const i=bs/2,s=new Te(.45,.45,.45);this.mesh=Rn.CreateBox("STONE-MESH",{size:i},e),this.mesh.position=new T(t.x,i/2,t.z),this.mesh.material=new Oe("STONE-MESH-MATERIAL",e),this.mesh.material instanceof Oe&&(this.mesh.material.diffuseColor=s);const r=Rn.CreateBox("STONE-MESH",{size:i/2},e);r.position=new T(t.x,i*5/4,t.z),r.material=new Oe("STONE-MESH-MATERIAL",e),r.material instanceof Oe&&(r.material.diffuseColor=s),this.meshChildren.push({mesh:r,anchorToParent:T.Zero()}),this.collisionType="static"}}class u6 extends lc{constructor(e,t){super(e);const i=bs*1/4,s=bs*2;this.mesh=Rn.CreateBox("TREE-MESH",{width:i,depth:i,height:s},e),this.mesh.position=new T(t.x,s/2,t.z),this.mesh.material=new Oe("TREE-MESH-MATERIAL",e),this.mesh.material instanceof Oe&&(this.mesh.material.diffuseColor=new Te(.55,.45,.3));const r=Rn.CreateBox("TREE-MESH",{size:bs},e);r.position=new T(t.x,s,t.z),r.material=new Oe("TREE-MESH-MATERIAL",e),r.material instanceof Oe&&(r.material.diffuseColor=new Te(.5,.7,.4)),this.meshChildren.push({mesh:r,anchorToParent:T.Zero()}),this.collisionType="static"}}const kC=["nature","empty","track","river"],GC=[c6,u6],zC=(o,e,t)=>{const i=[],s=t._mesh.position.z-t.depth/2,r=t._mesh.position.z+t.depth/2;for(let n=0;n[],WC=[a6],f6=(o,e,t)=>{const i=[],s=Math.random()<.5?"right":"left",r=t._mesh.position.z-t.depth/2,n=t._mesh.position.z+t.depth/2,a=bs*3/4,l=a,h=new T(t._mesh.position.x,l/2,s==="right"?r:n),c=new T(t._mesh.position.x,l/2,s==="right"?n:r),u=12e-5+Math.random()*6e-5;h.y+=l/8,c.y+=l/8;let d=Math.random();const f=WC[Math.floor(WC.length*Math.random())];for(let p=0;p<=e;p++){const _=new f(o,{direction:s,start:h,end:c,width:a,depth:a*3,height:l,pathProgress:d,velocity:u});i.push(_),d=(d+1/e)%1}return i},HC=[o6],p6=(o,e,t)=>{const i=[],s=Math.random()<.5?"right":"left",r=7e-5+Math.random()*5e-5,n=t._mesh.position.z-t.depth/2,a=t._mesh.position.z+t.depth/2,l=bs*3/4,h=l,c=new T(t._mesh.position.x,-h/2,s==="right"?n:a),u=new T(t._mesh.position.x,-h/2,s==="right"?a:n);let d=Math.random();const f=HC[Math.floor(HC.length*Math.random())];for(let p=0;p<=e;p++){const _=new f(o,{direction:s,start:c,end:u,width:l,depth:l*4,height:h,velocity:r,pathProgress:d});i.push(_),d=(d+1/e)%1}return i};class _6 extends lc{constructor(t,i){super(t);Ut(this,"width");Ut(this,"depth");Ut(this,"objects",[]);Ut(this,"isEmpty");Ut(this,"tileType",kC[Math.floor(kC.length*Math.random())]);this.isEmpty=!!i.isEmpty,this.isEmpty&&(this.tileType="empty"),this.width=i.width,this.depth=i.depth;const s=this.tileType==="river"?bs*7/8:bs;this.mesh=Rn.CreateBox("TILE-MESH",{width:this.width,height:s,depth:this.depth},t),this._mesh.position=new T(i.x,-bs/2,i.z),this._mesh.material=new Oe("TILE-MESH-MATERIAL",t),this._mesh.material instanceof Oe&&(this._mesh.material.diffuseColor=this.tileType==="track"?new Te(.15,.15,.15):this.tileType==="river"?new Te(.5,.75,.85):new Te(.6,.85,.5)),this.collisionType=this.tileType==="river"?"dynamic":"none"}onEnterScene(t){const i=1+Math.floor(2*Math.random()),s=this.isEmpty?d6:this.tileType==="nature"?zC:this.tileType==="track"?f6:this.tileType==="river"?p6:zC;this.objects=s(t,i,this),this.objects.forEach(r=>t.addEntity(r))}update(t,i){this.objects.forEach(s=>s.update(t,i))}kill(){super.kill(),this.objects.forEach(t=>{this.scene.removeMesh(t._mesh),t.kill()}),this.objects=[]}}const vl=class vl extends s6{constructor(t,i){super(t,i);Ut(this,"player");Ut(this,"tiles",[]);Ut(this,"farthestAwayPlayerXCoordinate",0);Ut(this,"farthestAwayTileXCoordinate",0);Ut(this,"closestLimitXCoordinate",-1e4);Ut(this,"sideLimits",[]);Ut(this,"gameAreaLimits",[]);Ut(this,"updateCamera",(t,i)=>{this.farthestAwayPlayerXCoordinate=Math.max(this.farthestAwayPlayerXCoordinate,this.player._mesh.position.x);const s=new T(-90,90,-32).scale(1),r=this.player.mesh.position.multiply(new T(1,0,1));r.x=Math.max(this.farthestAwayPlayerXCoordinate,r.x),this.camera.position=r.add(s),this.camera.setTarget(r)});Ut(this,"handleTileLifeCycle",(t,i)=>{const s=bs*15;this.farthestAwayTileXCoordinate-this.player.mesh.position.x=r;){const n=this.tiles[0].tile._mesh.position.x;if(n>this.closestLimitXCoordinate){const a=this.tiles.shift();a==null||a.tile.kill();const l=new Iv(this,{depth:vl.TILE_DEPTH,width:bs,z:0,x:n});this.gameAreaLimits.push(l),this.addEntity(l),this.closestLimitXCoordinate=n}else break}for(;this.sideLimits[0]._mesh.position.xi(this.app,t))}};Ut(vl,"TILE_DEPTH",bs*20);let q_=vl;window.CANNON=wN;const DA=document.getElementsByTagName("canvas");if(JY.isEmpty(DA))throw new e6("Canvas not found");const m6=DA[0],OA=new re(m6,!0),tx=new i6(OA);tx.createScene("home",new q_(tx));tx.runRenderLoop();window.addEventListener("resize",()=>{OA.resize()}); +}`;var Oi=BS(function(){return os(J,kt+"return "+tt).apply(t,pe)});if(Oi.source=tt,Kg(Oi))throw Oi;return Oi}function kO(m){return fs(m).toLowerCase()}function GO(m){return fs(m).toUpperCase()}function zO(m,x,y){if(m=fs(m),m&&(y||x===t))return YT(m);if(!m||!(x=ga(x)))return m;var F=co(m),z=co(x),J=$T(F,z),pe=KT(F,z)+1;return zl(F,J,pe).join("")}function WO(m,x,y){if(m=fs(m),m&&(y||x===t))return m.slice(0,jT(m)+1);if(!m||!(x=ga(x)))return m;var F=co(m),z=KT(F,co(x))+1;return zl(F,0,z).join("")}function HO(m,x,y){if(m=fs(m),m&&(y||x===t))return m.replace(Wt,"");if(!m||!(x=ga(x)))return m;var F=co(m),z=$T(F,co(x));return zl(F,z).join("")}function XO(m,x){var y=L,F=B;if(Js(x)){var z="separator"in x?x.separator:z;y="length"in x?Ai(x.length):y,F="omission"in x?ga(x.omission):F}m=fs(m);var J=m.length;if(uc(m)){var pe=co(m);J=pe.length}if(y>=J)return m;var xe=y-dc(F);if(xe<1)return F;var Pe=pe?zl(pe,0,xe).join(""):m.slice(0,xe);if(z===t)return Pe+F;if(pe&&(xe+=Pe.length-xe),qg(z)){if(m.slice(xe).search(z)){var Ke,je=Pe;for(z.global||(z=ug(z.source,fs(ct.exec(z))+"g")),z.lastIndex=0;Ke=z.exec(je);)var tt=Ke.index;Pe=Pe.slice(0,tt===t?xe:tt)}}else if(m.indexOf(ga(z),xe)!=xe){var At=Pe.lastIndexOf(z);At>-1&&(Pe=Pe.slice(0,At))}return Pe+F}function YO(m){return m=fs(m),m&&da.test(m)?m.replace(Qr,ER):m}var $O=xc(function(m,x,y){return m+(y?" ":"")+x.toUpperCase()}),Zg=VE("toUpperCase");function LS(m,x,y){return m=fs(m),x=y?t:x,x===t?mR(m)?bR(m):oR(m):m.match(x)||[]}var BS=Fi(function(m,x){try{return _a(m,t,x)}catch(y){return Kg(y)?y:new mi(y)}}),KO=hl(function(m,x){return Wa(x,function(y){y=Oo(y),ol(m,y,Yg(m[y],m))}),m});function qO(m){var x=m==null?0:m.length,y=si();return m=x?Ys(m,function(F){if(typeof F[1]!="function")throw new Ha(n);return[y(F[0]),F[1]]}):[],Fi(function(F){for(var z=-1;++zae)return[];var y=w,F=Sn(m,w);x=si(x),m-=w;for(var z=lg(F,x);++y0||x<0)?new Wi(y):(m<0?y=y.takeRight(-m):m&&(y=y.drop(m)),x!==t&&(x=Ai(x),y=x<0?y.dropRight(-x):y.take(x-m)),y)},Wi.prototype.takeRightWhile=function(m){return this.reverse().takeWhile(m).reverse()},Wi.prototype.toArray=function(){return this.take(w)},Mo(Wi.prototype,function(m,x){var y=/^(?:filter|find|map|reject)|While$/.test(x),F=/^(?:head|last)$/.test(x),z=Y[F?"take"+(x=="last"?"Right":""):x],J=F||/^find/.test(x);z&&(Y.prototype[x]=function(){var pe=this.__wrapped__,xe=F?[1]:arguments,Pe=pe instanceof Wi,Ke=xe[0],je=Pe||xi(pe),tt=function(Ui){var $i=z.apply(Y,Ll([Ui],xe));return F&&At?$i[0]:$i};je&&y&&typeof Ke=="function"&&Ke.length!=1&&(Pe=je=!1);var At=this.__chain__,kt=!!this.__actions__.length,ni=J&&!At,Oi=Pe&&!kt;if(!J&&je){pe=Oi?pe:new Wi(this);var ai=m.apply(pe,xe);return ai.__actions__.push({func:Kp,args:[tt],thisArg:t}),new Xa(ai,At)}return ni&&Oi?m.apply(this,xe):(ai=this.thru(tt),ni?F?ai.value()[0]:ai.value():ai)})}),Wa(["pop","push","shift","sort","splice","unshift"],function(m){var x=Tp[m],y=/^(?:push|sort|unshift)$/.test(m)?"tap":"thru",F=/^(?:pop|shift)$/.test(m);Y.prototype[m]=function(){var z=arguments;if(F&&!this.__chain__){var J=this.value();return x.apply(xi(J)?J:[],z)}return this[y](function(pe){return x.apply(xi(pe)?pe:[],z)})}}),Mo(Wi.prototype,function(m,x){var y=Y[x];if(y){var F=y.name+"";xs.call(mc,F)||(mc[F]=[]),mc[F].push({name:x,func:y})}}),mc[Gp(t,v).name]=[{name:"wrapper",func:t}],Wi.prototype.clone=YR,Wi.prototype.reverse=$R,Wi.prototype.value=KR,Y.prototype.at=CM,Y.prototype.chain=bM,Y.prototype.commit=yM,Y.prototype.next=AM,Y.prototype.plant=IM,Y.prototype.reverse=PM,Y.prototype.toJSON=Y.prototype.valueOf=Y.prototype.value=MM,Y.prototype.first=Y.prototype.head,Ou&&(Y.prototype[Ou]=RM),Y},fc=yR();Ch?((Ch.exports=fc)._=fc,eg._=fc):fn._=fc}).call(Yu)})(K_,K_.exports);var i6=K_.exports;class s6 extends Error{constructor(e){super(`[DomSetup] ${e}`)}}class kC extends Error{constructor(e){super(`[AppError] ${e}`)}}class GC{constructor(e){wt(this,"key");wt(this,"used");this.key=e.key,this.used=e.used||!1}}class r6{constructor(){wt(this,"singletonInstance",null);wt(this,"keyState",new Map);wt(this,"keyDownHandler",e=>{const{key:t}=e;this.keyState.set(t,new GC({key:t}))});wt(this,"keyUpHandler",e=>{const{key:t}=e;this.keyState.has(t)&&this.keyState.delete(t)});if(this.singletonInstance)return this.singletonInstance;this.keyState=new Map,addEventListener("keydown",this.keyDownHandler),addEventListener("keyup",this.keyUpHandler),this.singletonInstance=this}clear(){removeEventListener("keydown",this.keyDownHandler),removeEventListener("keyup",this.keyUpHandler)}wasPressedOnce(e){var i;let t=!1;return this.keyState.has(e)&&(t=!((i=this.keyState.get(e))!=null&&i.used),this.keyState.set(e,new GC({key:e,used:!0}))),t}isBeingPressed(e){return!!this.keyState.has(e)}}class n6{constructor(e){wt(this,"input",{keyboardHandler:new r6});wt(this,"currentScene");wt(this,"allScenes",new Map);this.engine=e}createScene(e,t){this.allScenes.set(e,t),this.currentScene||(this.currentScene=t)}goToScene(e){this.allScenes.has(e)?this.currentScene=this.allScenes.get(e):console.warn(`The scene with key ${e} was not found! Keeping previous scene!`)}runRenderLoop(){if(!this.currentScene)throw new kC("No default scene was configured!");this.engine.runRenderLoop(()=>{const e=this.engine.getDeltaTime();if(!this.currentScene)throw new kC("Trying to render undefined scene!");this.currentScene.update(e),this.currentScene.render(!0)})}}class a6 extends Qe{constructor(t,i){super(t.engine);wt(this,"entities",[]);wt(this,"_camera");wt(this,"_light");this.app=t,this.enablePhysics(i!=null&&i.gravity?i.gravity:T.Down().scale(9.8),new V_),this._camera=new zn("BASE-CAMERA",T.Up().scale(50),this),this._camera.attachControl(t.engine.getRenderingCanvas(),!0),this._light=new ro("BASE-LIGHT",T.Down(),this)}update(t){this.entities.forEach(i=>this.entities.forEach(s=>{i!==s&&i.collisionType!=="none"&&s.collisionType!=="none"&&i.mesh.intersectsMesh(s.mesh)&&(i.onCollision(s,this.app),s.onCollision(i,this.app))})),this.entities.forEach(i=>i.update(this.app,t)),this.entities=this.entities.filter(i=>i.isAlive)}addEntity(t){this.entities.push(t),t.onEnterScene(this)}set camera(t){this._camera.detachControl(),this._camera.dispose(),this._camera=t,this._camera.attachControl(this.app.engine.getRenderingCanvas(),!0)}get camera(){return this._camera}set light(t){this._light.dispose(),this._light=t}get light(){return this._light}}class wl{constructor(e){wt(this,"_mesh");wt(this,"isAlive",!0);wt(this,"collisionType","none");wt(this,"meshChildren",[]);this.scene=e,this._mesh=new se("BASE-MESH")}update(e,t){}onCollision(e,t){}onEnterScene(e){}kill(){this.isAlive=!1,this.mesh&&this.scene.removeMesh(this.mesh),this.meshChildren.forEach(e=>this.scene.removeMesh(e.mesh))}set mesh(e){this._mesh=e}get mesh(){return this._mesh}}class o6{static useParabolaCurve(e){const t=e.min?e.min:0,i=e.max,s=i-t,r=t+s/2;return a=>{a=Math.min(i,Math.max(a,t));let l=0;return a<=r?l=a/r:l=1-(a-r)/r,Math.min(1,Math.max(l,0))}}}class NA{static useLinearPath(e){const t=e.start,i=e.end;return r=>{const n=Math.min(1,Math.max(r,0)),a=t.x+(i.x-t.x)*n,l=t.y+(i.y-t.y)*n,h=t.z+(i.z-t.z)*n;return new T(a,l,h)}}}class l6{static findRotationAngleBasedOnDirection(e){return e==="top"?0:e==="right"?Math.PI/2:e==="bottom"?Math.PI:Math.PI*3/2}}class h6 extends wl{constructor(t,i){super(t);wt(this,"direction");wt(this,"start");wt(this,"end");wt(this,"pathProgress");wt(this,"velocity");wt(this,"width");wt(this,"height");wt(this,"depth");wt(this,"pathMap");this.width=i.width,this.height=i.height,this.depth=i.depth,this.direction=i.direction,this.start=i.start,this.end=i.end,this.pathProgress=i.pathProgress,this.velocity=i.velocity,this.pathMap=NA.useLinearPath({start:this.start,end:this.end}),this.collisionType="dynamic";const s=Te.Random(),r=new Te(.15,.15,.15);this.mesh=_n.CreateBox("CAR-MESH",{width:this.width,depth:this.depth,height:this.height/2},t),this.mesh.position=i.start,this.mesh.material=new De("CAR-MESH-MATERIAL",t),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=s);const n=T.Down().scale(30),a=_n.CreateBox("CAR-MESH",{width:this.width,depth:this.depth/2,height:this.height/2},t);a.position=n,a.material=new De("CAR-MESH-MATERIAL",t),a.material instanceof De&&(a.material.diffuseColor=s),this.meshChildren.push({mesh:a,anchorToParent:new T(0,this.height/2,0)});const l=_n.CreateCylinder("CAR-MESH",{height:this.width*1.1,diameter:this.height*5/8});l.position=n,l.rotation=new T(0,0,Math.PI/2),l.material=new De("CAR-MESH-MATERIAL",t),l.material instanceof De&&(l.material.diffuseColor=r),this.meshChildren.push({mesh:l,anchorToParent:new T(0,-this.height/6,this.depth/3)});const h=_n.CreateCylinder("CAR-MESH",{height:this.width*1.1,diameter:this.height*5/8});h.position=n,h.rotation=new T(0,0,Math.PI/2),h.material=new De("CAR-MESH-MATERIAL",t),h.material instanceof De&&(h.material.diffuseColor=r),this.meshChildren.push({mesh:h,anchorToParent:new T(0,-this.height/6,-this.depth/3)})}update(t,i){const s=this.direction==="right"?1:-1,r=this.velocity*i*s;this.pathProgress=(this.pathProgress+r*s+1)%1,this._mesh.position=this.pathMap(this.pathProgress),this.meshChildren.forEach(({mesh:n,anchorToParent:a})=>{n.position=this._mesh.position.add(a)})}}class c6 extends wl{constructor(t,i){super(t);wt(this,"direction");wt(this,"start");wt(this,"end");wt(this,"pathProgress");wt(this,"velocity");wt(this,"pathMap");this.mesh=_n.CreateBox("LOG-MESH",{width:i.width,depth:i.depth,height:i.height},t),this.mesh.position=i.start,this.mesh.material=new De("LOG-MESH-MATERIAL",t),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=new Te(.6,.5,.3)),this.direction=i.direction,this.start=i.start,this.end=i.end,this.pathProgress=i.pathProgress,this.velocity=i.velocity,this.pathMap=NA.useLinearPath({start:this.start,end:this.end}),this.collisionType="platform"}update(t,i){const s=this.direction==="right"?1:-1,r=this.velocity*i*s;this.pathProgress=(this.pathProgress+r*s+1)%1,this._mesh.position=this.pathMap(this.pathProgress)}}const Ss=16;class u6{constructor(e){this.scene=e}getClosestTile(e,t){return this.scene.tiles.find(i=>Math.abs(e-i.x)<=t)}}const d6=()=>{const o=new Map;let e="idle";return{state:()=>e,transition:i=>{const s=e;switch(e){case"idle":switch(i){case"move":e="moving";break;case"stop":e="idle";break;case"bind-to-platform":e="on-platform";break;case"move-back":break;case"die":e="dead";break}break;case"moving":switch(i){case"move":e="moving";break;case"stop":e="idle";break;case"move-back":e="moving-back";break;case"bind-to-platform":break;case"die":e="dead";break}break;case"moving-back":switch(i){case"stop":e="idle";break;case"move-back":e="moving-back";break;case"move":case"bind-to-platform":break;case"die":e="dead";break}break;case"on-platform":switch(i){case"stop":e="idle";break;case"move":e="moving";break;case"move-back":case"bind-to-platform":break;case"die":e="dead";break}break}s!==e&&(o.get(e)||[]).forEach(n=>n())},registerCallback:(i,s)=>{o.has(i)?o.set(i,[...o.get(i),s]):o.set(i,[s])}}},Sd=class Sd extends wl{constructor(t,i){super(t);wt(this,"scene");wt(this,"particles",[]);wt(this,"life",0);const s=20;for(let r=0;rSd.TTL){this.kill(),this.scene.restart();return}this.life+=i}kill(){super.kill(),this.particles.forEach(t=>t.kill())}};wt(Sd,"TTL",1e3);let tx=Sd;class f6 extends wl{constructor(t,i){super(t);wt(this,"pointingTo");wt(this,"ttl");wt(this,"life",0);this._mesh=_n.CreateBox("PARTICLE-MESH",{size:Ss/16},t),this.mesh.material=new De("PLAYER-MESH-MATERIAL",t),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=Math.random()<.5?Te.White():Te.Red()),this.mesh.position=i.start,this.ttl=i.TTL;const s=()=>-1+Math.floor(3*Math.random());this.pointingTo=new T(s(),s(),s())}update(t,i){this.life+=i,this.mesh.position=this.mesh.position.add(this.pointingTo.scale(.01*i)),this.mesh.material&&(this.mesh.material.alpha=1-this.life/this.ttl)}}const j_=class j_ extends wl{constructor(t,i){super(t);wt(this,"stateMachine");wt(this,"jumpCurrDistance",0);wt(this,"direction","top");wt(this,"width");wt(this,"depth");wt(this,"height");wt(this,"platform");wt(this,"platformCenterOffset");wt(this,"tiledSceneNavigator");wt(this,"scene");this.scene=t;const s=i!=null&&i.size?i.size:Ss,r=Te.Red();this.width=s,this.height=s*2,this.depth=s,this.mesh=_n.CreateBox("PLAYER-MESH",{height:this.height,depth:this.depth,width:this.width},t),i!=null&&i.position&&(this.mesh.position=i.position),this.mesh.material=new De("PLAYER-MESH-MATERIAL",t),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=Te.White());const n=T.Down().scale(30),a=_n.CreateBox("PLAYER-MESH",{height:this.height/2,depth:this.depth,width:this.width/2},t);a.position=n,a.material=new De("PLAYER-MESH-MATERIAL",t),a.material instanceof De&&(a.material.diffuseColor=Te.White()),this.meshChildren.push({mesh:a,anchorToParent:new T(-this.width*3/4,-this.height/4,0)});const l=_n.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/4,width:this.width/2},t);l.position=n,l.material=new De("PLAYER-MESH-MATERIAL",t),l.material instanceof De&&(l.material.diffuseColor=r),this.meshChildren.push({mesh:l,anchorToParent:new T(0,this.height*9/16,0)});const h=_n.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/2,width:this.width/4},t);h.position=n,h.material=new De("PLAYER-MESH-MATERIAL",t),h.material instanceof De&&(h.material.diffuseColor=new Te(.95,.65,.2)),this.meshChildren.push({mesh:h,anchorToParent:new T(this.width*5/8,this.height/4,0)});const c=_n.CreateBox("PLAYER-MESH",{height:this.height/8,depth:this.depth/4,width:this.width/4},t);c.position=n,c.material=new De("PLAYER-MESH-MATERIAL",t),c.material instanceof De&&(c.material.diffuseColor=r),this.meshChildren.push({mesh:c,anchorToParent:new T(this.width*5/8,this.height/8,0)}),this.stateMachine=d6(),this.stateMachine.registerCallback("moving",()=>this.jumpCurrDistance=0),this.stateMachine.registerCallback("idle",()=>{this._mesh.position=new T(Math.round(this._mesh.position.x),Math.round(this._mesh.position.y),Math.round(this._mesh.position.z))}),this.collisionType="dynamic",t instanceof q_&&(this.tiledSceneNavigator=new u6(t))}updateJump(t,i){const s=this.stateMachine.state();if(s==="moving-back"&&this.jumpCurrDistance<=0||s==="moving"&&this.jumpCurrDistance>=Ss){this.stateMachine.transition("stop");return}const r=.08*i,n=this.direction==="top"||this.direction==="bottom"?"x":(this.direction==="right"||this.direction==="left","z");let a=this.direction==="top"||this.direction==="left"?1:-1;if(s==="moving"){const l=Math.min(r,Ss-this.jumpCurrDistance);this.mesh.position[n]+=l*a,this.jumpCurrDistance+=l}else if(s==="moving-back"){const l=Math.min(r,this.jumpCurrDistance);a*=-1,this.mesh.position[n]+=l*a,this.jumpCurrDistance-=l}this.mesh.position.y=this.height/2+j_.jumpVerticalDistanceCurve(this.jumpCurrDistance)*Ss}updatePlatform(t,i){this.platform&&this.platformCenterOffset&&(this._mesh.position=this.platform._mesh.position.add(this.platformCenterOffset))}handleIdle(t,i){var r;const s=(r=this.tiledSceneNavigator)==null?void 0:r.getClosestTile(this._mesh.position._x,this.depth);(s==null?void 0:s.tile.collisionType)==="dynamic"&&s.x>0&&this.handleDeath()}onCollision(t,i){i.engine.getFps()!==1/0&&(t.collisionType==="static"&&this.stateMachine.transition("move-back"),t.collisionType==="dynamic"&&this.scene&&this.handleDeath(),t.collisionType==="platform"&&(this.stateMachine.state()==="idle"&&(this.platform=t,this.platformCenterOffset=this._mesh.position.subtract(t._mesh.position)),this.stateMachine.transition("bind-to-platform")))}updateMesh(t,i){const s=l6.findRotationAngleBasedOnDirection(this.direction),r=new T(0,s,0);this._mesh.rotation=r,this.meshChildren.forEach(({mesh:n,anchorToParent:a})=>{n.rotation=r;const l=Se.FromEulerAngles(0,s,0),h=a.applyRotationQuaternion(l);n.position=this._mesh.position.add(h)})}handleDeath(){if(this.stateMachine.state()==="dead")return;this.stateMachine.transition("die"),this.mesh.material&&(this.mesh.material.alpha=0),this.meshChildren.forEach(s=>{s.mesh.material&&(s.mesh.material.alpha=0)});const t=this._mesh.position.clone(),i=new tx(this.scene,{start:t});this.scene.addEntity(i)}update(t,i){if(t.engine.getFps()===1/0)return;const{input:{keyboardHandler:s}}=t,r=this.stateMachine.state();switch(r){case"idle":case"on-platform":s.wasPressedOnce("ArrowUp")||s.wasPressedOnce(" ")?(this.direction="top",this.stateMachine.transition("move")):s.wasPressedOnce("ArrowDown")&&(this.direction="bottom",this.stateMachine.transition("move")),s.wasPressedOnce("ArrowRight")?(this.direction="right",this.stateMachine.transition("move")):s.wasPressedOnce("ArrowLeft")&&(this.direction="left",this.stateMachine.transition("move")),r==="on-platform"&&this.updatePlatform(t,i),r==="idle"&&this.handleIdle(t,i);break;case"moving":case"moving-back":this.updateJump(t,i);break}this.updateMesh(t,i)}};wt(j_,"jumpVerticalDistanceCurve",o6.useParabolaCurve({min:0,max:Ss}));let ix=j_;class Iv extends wl{constructor(t,i){super(t);wt(this,"width");wt(this,"depth");this.width=i.width,this.depth=i.depth;const s=Ss;this.mesh=_n.CreateBox("LIMIT-MESH",{width:this.width,height:s*1.1,depth:this.depth},t),this._mesh.position=new T(i.x,-Ss/2,i.z),this._mesh.material=new De("TILE-MESH-MATERIAL",t),this._mesh.material instanceof De&&(this._mesh.material.diffuseColor=new Te(.05,.05,.05)),this.collisionType="static"}}class p6 extends wl{constructor(e,t){super(e);const i=Ss/2,s=new Te(.45,.45,.45);this.mesh=_n.CreateBox("STONE-MESH",{size:i},e),this.mesh.position=new T(t.x,i/2,t.z),this.mesh.material=new De("STONE-MESH-MATERIAL",e),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=s);const r=_n.CreateBox("STONE-MESH",{size:i/2},e);r.position=new T(t.x,i*5/4,t.z),r.material=new De("STONE-MESH-MATERIAL",e),r.material instanceof De&&(r.material.diffuseColor=s),this.meshChildren.push({mesh:r,anchorToParent:T.Zero()}),this.collisionType="static"}}class _6 extends wl{constructor(e,t){super(e);const i=Ss*1/4,s=Ss*2;this.mesh=_n.CreateBox("TREE-MESH",{width:i,depth:i,height:s},e),this.mesh.position=new T(t.x,s/2,t.z),this.mesh.material=new De("TREE-MESH-MATERIAL",e),this.mesh.material instanceof De&&(this.mesh.material.diffuseColor=new Te(.55,.45,.3));const r=_n.CreateBox("TREE-MESH",{size:Ss},e);r.position=new T(t.x,s,t.z),r.material=new De("TREE-MESH-MATERIAL",e),r.material instanceof De&&(r.material.diffuseColor=new Te(.5,.7,.4)),this.meshChildren.push({mesh:r,anchorToParent:T.Zero()}),this.collisionType="static"}}const zC=["nature","empty","track","river"],WC=[p6,_6],HC=(o,e,t)=>{const i=[],s=t._mesh.position.z-t.depth/2,r=t._mesh.position.z+t.depth/2;for(let n=0;n[],XC=[h6],g6=(o,e,t)=>{const i=[],s=Math.random()<.5?"right":"left";e=Math.min(2,e);const r=t._mesh.position.z-t.depth/2,n=t._mesh.position.z+t.depth/2,a=Ss*3/4,l=a,h=new T(t._mesh.position.x,l/2,s==="right"?r:n),c=new T(t._mesh.position.x,l/2,s==="right"?n:r),u=12e-5+Math.random()*6e-5;h.y+=l/8,c.y+=l/8;let d=Math.random();const f=XC[Math.floor(XC.length*Math.random())];for(let p=0;p<=e;p++){const _=new f(o,{direction:s,start:h,end:c,width:a,depth:a*3,height:l,pathProgress:d,velocity:u});i.push(_),d=(d+1/e)%1}return i},YC=[c6],v6=(o,e,t)=>{const i=[],s=Math.random()<.5?"right":"left",r=7e-5+Math.random()*5e-5,n=t._mesh.position.z-t.depth/2,a=t._mesh.position.z+t.depth/2,l=Ss*3/4,h=l,c=new T(t._mesh.position.x,-h/2,s==="right"?n:a),u=new T(t._mesh.position.x,-h/2,s==="right"?a:n);let d=Math.random();const f=YC[Math.floor(YC.length*Math.random())];for(let p=0;p<=e;p++){const _=new f(o,{direction:s,start:c,end:u,width:l,depth:l*4,height:h,velocity:r,pathProgress:d});i.push(_),d=(d+1/e)%1}return i};class x6 extends wl{constructor(t,i){super(t);wt(this,"width");wt(this,"depth");wt(this,"objects",[]);wt(this,"isEmpty");wt(this,"tileType",zC[Math.floor(zC.length*Math.random())]);this.isEmpty=!!i.isEmpty,this.isEmpty&&(this.tileType="empty"),this.width=i.width,this.depth=i.depth;const s=this.tileType==="river"?Ss*7/8:Ss;this.mesh=_n.CreateBox("TILE-MESH",{width:this.width,height:s,depth:this.depth},t),this._mesh.position=new T(i.x,-Ss/2,i.z),this._mesh.material=new De("TILE-MESH-MATERIAL",t),this._mesh.material instanceof De&&(this._mesh.material.diffuseColor=this.tileType==="track"?new Te(.15,.15,.15):this.tileType==="river"?new Te(.5,.75,.85):new Te(.6,.85,.5)),this.collisionType=this.tileType==="river"?"dynamic":"none"}onEnterScene(t){const i=1+Math.floor(3*Math.random()),s=this.isEmpty?m6:this.tileType==="nature"?HC:this.tileType==="track"?g6:this.tileType==="river"?v6:HC;this.objects=s(t,i,this),this.objects.forEach(r=>t.addEntity(r))}update(t,i){this.objects.forEach(s=>s.update(t,i))}kill(){super.kill(),this.objects.forEach(t=>{this.scene.removeMesh(t._mesh),t.kill()}),this.objects=[]}}const vl=class vl extends a6{constructor(t,i){super(t,i);wt(this,"player");wt(this,"tiles",[]);wt(this,"farthestAwayPlayerXCoordinate",0);wt(this,"farthestAwayTileXCoordinate",0);wt(this,"closestLimitXCoordinate",-1e4);wt(this,"sideLimits",[]);wt(this,"gameAreaLimits",[]);wt(this,"updateCamera",(t,i)=>{this.farthestAwayPlayerXCoordinate=Math.max(this.farthestAwayPlayerXCoordinate,this.player._mesh.position.x);const s=new T(-90,90,-32).scale(1),r=this.player.mesh.position.multiply(new T(1,0,1));r.x=Math.max(this.farthestAwayPlayerXCoordinate,r.x),this.camera.position=r.add(s),this.camera.setTarget(r)});wt(this,"handleTileLifeCycle",(t,i)=>{const s=Ss*15;this.farthestAwayTileXCoordinate-this.player.mesh.position.x=r;){const n=this.tiles[0].tile._mesh.position.x;if(n>this.closestLimitXCoordinate){const a=this.tiles.shift();a==null||a.tile.kill();const l=new Iv(this,{depth:vl.TILE_DEPTH,width:Ss,z:0,x:n});this.gameAreaLimits.push(l),this.addEntity(l),this.closestLimitXCoordinate=n}else break}for(;this.sideLimits[0]._mesh.position.xt.tile.kill()),this.sideLimits.forEach(t=>t.kill()),this.gameAreaLimits.forEach(t=>t.kill()),this.tiles=[],this.sideLimits=[],this.gameAreaLimits=[],this.farthestAwayPlayerXCoordinate=0,this.farthestAwayTileXCoordinate=0,this.closestLimitXCoordinate=-1e4}addTile(t,i=!1){const s=new x6(this,{depth:vl.TILE_DEPTH,width:Ss,z:0,x:t,isEmpty:i});this.tiles.push({tile:s,x:t}),this.addEntity(s),this.farthestAwayTileXCoordinate=t;const[r,n]=[new Iv(this,{depth:vl.TILE_DEPTH,width:Ss,z:-vl.TILE_DEPTH,x:t}),new Iv(this,{depth:vl.TILE_DEPTH,width:Ss,z:vl.TILE_DEPTH,x:t})];this.sideLimits.push(r),this.addEntity(r),this.sideLimits.push(n),this.addEntity(n)}setUpInitialTiles(){for(let i=-3*5;i<5*2;i++){const s=i*Ss;this.addTile(s,i<=0)}}update(t){super.update(t),this.updateHandlers.forEach(i=>i(this.app,t))}};wt(vl,"TILE_DEPTH",Ss*20);let q_=vl;window.CANNON=BN;const wA=document.getElementsByTagName("canvas");if(i6.isEmpty(wA))throw new s6("Canvas not found");const T6=wA[0],FA=new re(T6,!0),sx=new n6(FA);sx.createScene("home",new q_(sx));sx.runRenderLoop();window.addEventListener("resize",()=>{FA.resize()}); diff --git a/docs/index.html b/docs/index.html index d60ff8e..1b1ac38 100644 --- a/docs/index.html +++ b/docs/index.html @@ -5,7 +5,7 @@ Crossy Road - + diff --git a/src/object/actor/player/player.actor.ts b/src/object/actor/player/player.actor.ts index 177321c..bfae268 100644 --- a/src/object/actor/player/player.actor.ts +++ b/src/object/actor/player/player.actor.ts @@ -4,11 +4,12 @@ import { Entity } from "../.."; import { Game } from "../../../app"; import { BASE_SIZE } from "../../../config"; import { TiledSceneNavigator } from "../../../handler"; -import { BaseScene, HomeScene } from "../../../scene"; +import { HomeScene } from "../../../scene"; import { Direction, StateMachine } from "../../../types"; import { Curve, CurveUtil, DirectionUtil } from "../../../util"; import { PlayerStateMachineState, PlayerStateMachineTransition, getPlayerStateMachine } from "./player.state-machine"; +import { DeathParticlesGroup } from "../../particles-group"; type PlayerOptions = { size?: number, @@ -34,9 +35,9 @@ export class Player extends Entity{ private platformCenterOffset: Vector3 | undefined; private tiledSceneNavigator: TiledSceneNavigator | undefined; - public scene: BaseScene; + public scene: HomeScene; - constructor(scene: BaseScene, options?: PlayerOptions){ + constructor(scene: HomeScene, options?: PlayerOptions){ super(scene); this.scene = scene; @@ -190,14 +191,14 @@ export class Player extends Entity{ private handleIdle(_game: Game, _delta: number){ const metaTile = this.tiledSceneNavigator?.getClosestTile(this._mesh.position._x, this.depth); - if (metaTile?.tile.collisionType === 'dynamic' && metaTile.x > 0) _game.engine.stopRenderLoop(); + if (metaTile?.tile.collisionType === 'dynamic' && metaTile.x > 0) this.handleDeath(); } public onCollision(_other: Entity, _game: Game): void { if (_game.engine.getFps() === Infinity) return; if (_other.collisionType === 'static') this.stateMachine.transition('move-back'); - if (_other.collisionType === 'dynamic') _game.engine.stopRenderLoop(); + if (_other.collisionType === 'dynamic' && this.scene) this.handleDeath(); if (_other.collisionType === 'platform') { if (this.stateMachine.state() === 'idle'){ this.platform = _other; @@ -224,6 +225,23 @@ export class Player extends Entity{ ) } + private handleDeath(){ + if (this.stateMachine.state() === 'dead') return; + this.stateMachine.transition('die'); + + if (this.mesh.material) this.mesh.material.alpha = 0; + this.meshChildren.forEach(child => { + if (child.mesh.material) child.mesh.material.alpha = 0; + }); + + const start = this._mesh.position.clone(); + const particlesGroup = new DeathParticlesGroup(this.scene, { + start: start, + }); + + this.scene.addEntity(particlesGroup); + } + public update(_game: Game, _delta: number): void { if (_game.engine.getFps() === Infinity) return; @@ -257,6 +275,8 @@ export class Player extends Entity{ case 'moving-back': this.updateJump(_game, _delta); break; + case 'dead': + break; } this.updateMesh(_game, _delta) diff --git a/src/object/actor/player/player.state-machine.ts b/src/object/actor/player/player.state-machine.ts index b5489ef..54720cf 100644 --- a/src/object/actor/player/player.state-machine.ts +++ b/src/object/actor/player/player.state-machine.ts @@ -1,7 +1,7 @@ import { IndependentCallback, StateMachine } from "../../../types"; -export type PlayerStateMachineState = 'moving' | 'idle' | 'moving-back' | 'on-platform'; -export type PlayerStateMachineTransition = 'move' | 'stop' | 'move-back' | 'bind-to-platform'; +export type PlayerStateMachineState = 'moving' | 'idle' | 'moving-back' | 'on-platform' | 'dead'; +export type PlayerStateMachineTransition = 'move' | 'stop' | 'move-back' | 'bind-to-platform' | 'die'; export const getPlayerStateMachine = (): StateMachine< PlayerStateMachineState, @@ -28,6 +28,9 @@ export const getPlayerStateMachine = (): StateMachine< break; case 'move-back': break; + case 'die': + currentState = 'dead'; + break; } break; case 'moving': @@ -43,6 +46,9 @@ export const getPlayerStateMachine = (): StateMachine< break; case 'bind-to-platform': break; + case 'die': + currentState = 'dead'; + break; } break; case 'moving-back': @@ -56,6 +62,9 @@ export const getPlayerStateMachine = (): StateMachine< case 'move': case 'bind-to-platform': break; + case 'die': + currentState = 'dead'; + break; } break; case 'on-platform': @@ -69,7 +78,13 @@ export const getPlayerStateMachine = (): StateMachine< case 'move-back': case 'bind-to-platform': break; + case 'die': + currentState = 'dead'; + break; } + break; + case 'dead': + break; } const CURR_STATE = currentState; diff --git a/src/object/enviroment/tile/tile.object.ts b/src/object/enviroment/tile/tile.object.ts index a1d3694..9894f84 100644 --- a/src/object/enviroment/tile/tile.object.ts +++ b/src/object/enviroment/tile/tile.object.ts @@ -62,7 +62,7 @@ export class Tile extends Entity{ } public onEnterScene(_scene: BaseScene): void { - const N_ENTITIES_TO_ADD = 1 + Math.floor(2 * Math.random()); + const N_ENTITIES_TO_ADD = 1 + Math.floor(3 * Math.random()); const TileFactory = this.isEmpty ? EmptyTileFactory diff --git a/src/object/enviroment/tile/track.factory.ts b/src/object/enviroment/tile/track.factory.ts index 5c9e080..de9a407 100644 --- a/src/object/enviroment/tile/track.factory.ts +++ b/src/object/enviroment/tile/track.factory.ts @@ -16,6 +16,7 @@ export const TrackTileFactory: TileFactory = (scene: BaseScene, amount: number, const direction: Direction = Math.random() < 0.5 ? 'right' : 'left'; + amount = Math.min(2, amount); const MIN = tile._mesh.position.z - tile.depth/2; const MAX = tile._mesh.position.z + tile.depth/2; diff --git a/src/object/particles-group/death-particles.group.ts b/src/object/particles-group/death-particles.group.ts new file mode 100644 index 0000000..b732270 --- /dev/null +++ b/src/object/particles-group/death-particles.group.ts @@ -0,0 +1,49 @@ +import { Vector3 } from "@babylonjs/core"; +import { Particle } from "."; +import { Entity } from ".."; +import { Game } from "../../app"; +import { HomeScene } from "../../scene"; + +type DeathParticlesGroupOptions = { + start: Vector3; +} + +export class DeathParticlesGroup extends Entity{ + public static TTL = 1000; + public scene: HomeScene; + + private particles: Entity[] = []; + private life = 0; + + constructor(scene: HomeScene, options: DeathParticlesGroupOptions){ + super(scene); + + const NUMBER_OF_PARTICLES = 20; + for (let i = 0; i < NUMBER_OF_PARTICLES; i++){ + const particle = new Particle(scene, { + start: options.start, + TTL: DeathParticlesGroup.TTL, + }); + + this.particles.push(particle); + scene.addEntity(particle); + } + + this.scene = scene; + } + + public update(_game: Game, _delta: number): void { + if (this.life > DeathParticlesGroup.TTL) { + this.kill(); + this.scene.restart(); + return; + } + + this.life += _delta; + } + + kill(): void { + super.kill(); + this.particles.forEach(particle => particle.kill()); + } +} \ No newline at end of file diff --git a/src/object/particles-group/index.ts b/src/object/particles-group/index.ts new file mode 100644 index 0000000..06d60b7 --- /dev/null +++ b/src/object/particles-group/index.ts @@ -0,0 +1,2 @@ +export * from './death-particles.group'; +export * from './particle'; diff --git a/src/object/particles-group/particle.ts b/src/object/particles-group/particle.ts new file mode 100644 index 0000000..985706b --- /dev/null +++ b/src/object/particles-group/particle.ts @@ -0,0 +1,45 @@ +import { Color3, MeshBuilder, StandardMaterial, Vector3 } from "@babylonjs/core"; +import { Entity } from ".."; + +import { Game } from "../../app"; +import { HomeScene } from "../../scene"; +import { BASE_SIZE } from "../../config"; + +type ParticleOptions = { + start: Vector3; + TTL: number; +} + +export class Particle extends Entity{ + private pointingTo: Vector3; + + private ttl: number; + private life: number = 0; + + constructor(scene: HomeScene, options: ParticleOptions){ + super(scene); + this._mesh = MeshBuilder.CreateBox('PARTICLE-MESH', { + size: BASE_SIZE/16, + }, scene); + this.mesh.material = new StandardMaterial('PLAYER-MESH-MATERIAL', scene); + if (this.mesh.material instanceof StandardMaterial) this.mesh.material.diffuseColor = Math.random() < 0.5 ? Color3.White() : Color3.Red(); + + this.mesh.position = options.start; + this.ttl = options.TTL; + + const getNormalizedComponent = () => (-1 + Math.floor(3 * Math.random())); + + this.pointingTo = new Vector3( + getNormalizedComponent(), + getNormalizedComponent(), + getNormalizedComponent(), + ); + } + + public update(_game: Game, _delta: number): void { + this.life += _delta; + this.mesh.position = this.mesh.position.add(this.pointingTo.scale(0.01*_delta)); + + if (this.mesh.material) this.mesh.material.alpha = 1 - (this.life / this.ttl); + } +} diff --git a/src/scene/home.scene.ts b/src/scene/home.scene.ts index 5135702..bb4d785 100644 --- a/src/scene/home.scene.ts +++ b/src/scene/home.scene.ts @@ -9,7 +9,7 @@ import { BASE_SIZE } from "../config"; type HomeSceneOptions = BaseSceneOptions; export class HomeScene extends BaseScene{ - private player: Player; + private player!: Player; public tiles: MetaTile[] = []; private static TILE_DEPTH = BASE_SIZE * 20; @@ -25,6 +25,10 @@ export class HomeScene extends BaseScene{ super(app, options); this.clearColor = new Color4(0.5, 0.75, 0.85); + this.setup(); + } + + private setup(){ this.player = new Player(this, { position: new Vector3(-BASE_SIZE, BASE_SIZE/4, 0), size: BASE_SIZE/4, @@ -46,6 +50,25 @@ export class HomeScene extends BaseScene{ ) } + public restart(){ + this.cleanup(); + this.setup(); + } + + private cleanup(){ + this.player.kill(); + this.tiles.forEach(tile => tile.tile.kill()); + this.sideLimits.forEach(limit => limit.kill()); + this.gameAreaLimits.forEach(limit => limit.kill()); + + this.tiles = []; + this.sideLimits = []; + this.gameAreaLimits = []; + this.farthestAwayPlayerXCoordinate = 0; + this.farthestAwayTileXCoordinate = 0; + this.closestLimitXCoordinate = -10000; + } + private addTile(x: number, isEmpty: boolean = false){ const tile = new Tile(this, { depth: HomeScene.TILE_DEPTH,